diff --git a/tools/ui/node_modules/eslint-config-prettier/LICENSE b/tools/ui/node_modules/eslint-config-prettier/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4b17469e8038a832051611418c2bf8d569f88c44 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint-config-prettier/README.md b/tools/ui/node_modules/eslint-config-prettier/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2bdb30c30ebc4ec51c2108ed1c6b5256af412b6c --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint-config-prettier/bin/cli.js b/tools/ui/node_modules/eslint-config-prettier/bin/cli.js new file mode 100644 index 0000000000000000000000000000000000000000..da85433640340258448a748ac62b830855f8a668 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint-config-prettier/bin/validators.js b/tools/ui/node_modules/eslint-config-prettier/bin/validators.js new file mode 100644 index 0000000000000000000000000000000000000000..175d67a11196bef9cd0e4d8834fb5fa656d9d016 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint-config-prettier/flat.d.ts b/tools/ui/node_modules/eslint-config-prettier/flat.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..980b69e6c23d917c1d52be4eb10539fcdd73e73f --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint-config-prettier/flat.js b/tools/ui/node_modules/eslint-config-prettier/flat.js new file mode 100644 index 0000000000000000000000000000000000000000..adf9deec17c58f2c6e1036f3b5264467dad54f2b --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint-config-prettier/index.d.ts b/tools/ui/node_modules/eslint-config-prettier/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3548ea38c54adba1db6b1c818b9bb0ab7d95affb --- /dev/null +++ b/tools/ui/node_modules/eslint-config-prettier/index.d.ts @@ -0,0 +1,5 @@ +declare const eslintConfigPrettier: { + rules: Record; +}; + +export = eslintConfigPrettier; diff --git a/tools/ui/node_modules/eslint-config-prettier/index.js b/tools/ui/node_modules/eslint-config-prettier/index.js new file mode 100644 index 0000000000000000000000000000000000000000..dc39bee2999f3de532c56f16734d24a3e678d956 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint-config-prettier/package.json b/tools/ui/node_modules/eslint-config-prettier/package.json new file mode 100644 index 0000000000000000000000000000000000000000..20fd2b8b336f8c75916b0e74fd2edd53ebeb177d --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint-config-prettier/prettier.d.ts b/tools/ui/node_modules/eslint-config-prettier/prettier.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..19b02c2c60c906ce45be1d95c9ec8313278ebd59 --- /dev/null +++ b/tools/ui/node_modules/eslint-config-prettier/prettier.d.ts @@ -0,0 +1 @@ +export const rules: Record; diff --git a/tools/ui/node_modules/eslint-config-prettier/prettier.js b/tools/ui/node_modules/eslint-config-prettier/prettier.js new file mode 100644 index 0000000000000000000000000000000000000000..b9ec0f73602cde3ea57d72c475b1ada105899331 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint-plugin-perfectionist/dist/alphabet.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/alphabet.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d6a025e9dab5bc9a50f15638f6a25b883d6f6c4 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/alphabet.d.ts @@ -0,0 +1,2 @@ +export * from './utils/alphabet.js' +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/index.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e45abd43901cd12deae9c528e4d435b37c3f7590 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/index.d.ts @@ -0,0 +1,43 @@ +import { ESLint, Linter } from 'eslint' +interface PluginConfigs extends Record< + string, + Linter.LegacyConfig | Linter.Config[] | Linter.Config +> { + 'recommended-alphabetical-legacy': Linter.LegacyConfig + 'recommended-line-length-legacy': Linter.LegacyConfig + 'recommended-natural-legacy': Linter.LegacyConfig + 'recommended-custom-legacy': Linter.LegacyConfig + 'recommended-alphabetical': Linter.Config + 'recommended-line-length': Linter.Config + 'recommended-natural': Linter.Config + 'recommended-custom': Linter.Config +} +export declare let rules: ESLint.Plugin['rules'] +export declare let configs: PluginConfigs +declare const _default: { + configs: PluginConfigs +} & ESLint.Plugin +export default _default +export type { Options as SortVariableDeclarationsOptions } from './rules/sort-variable-declarations/types.js' +export type { Options as SortIntersectionTypesOptions } from './rules/sort-intersection-types/types.js' +export type { Options as SortImportAttributesOptions } from './rules/sort-import-attributes/types.js' +export type { Options as SortExportAttributesOptions } from './rules/sort-export-attributes/types.js' +export type { Options as SortHeritageClausesOptions } from './rules/sort-heritage-clauses/types.js' +export type { Options as SortArrayIncludesOptions } from './rules/sort-array-includes/types.js' +export type { Options as SortNamedImportsOptions } from './rules/sort-named-imports/types.js' +export type { Options as SortNamedExportsOptions } from './rules/sort-named-exports/types.js' +export type { Options as SortObjectTypesOptions } from './rules/sort-object-types/types.js' +export type { Options as SortSwitchCaseOptions } from './rules/sort-switch-case/types.js' +export type { Options as SortUnionTypesOptions } from './rules/sort-union-types/types.js' +export type { Options as SortInterfacesOptions } from './rules/sort-interfaces/types.js' +export type { Options as SortDecoratorsOptions } from './rules/sort-decorators/types.js' +export type { Options as SortJsxPropsOptions } from './rules/sort-jsx-props/types.js' +export type { Options as SortClassesOptions } from './rules/sort-classes/types.js' +export type { Options as SortImportsOptions } from './rules/sort-imports/types.js' +export type { Options as SortExportsOptions } from './rules/sort-exports/types.js' +export type { Options as SortObjectsOptions } from './rules/sort-objects/types.js' +export type { Options as SortModulesOptions } from './rules/sort-modules/types.js' +export type { Options as SortArraysOptions } from './rules/sort-arrays/types.js' +export type { Options as SortEnumsOptions } from './rules/sort-enums/types.js' +export type { Options as SortMapsOptions } from './rules/sort-maps/types.js' +export type { Options as SortSetsOptions } from './rules/sort-sets/types.js' diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/index.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9c1d705197a177de6b23f88a9cbaa8e2c9e63928 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/index.js @@ -0,0 +1,119 @@ +import { name, version } from './package.json.js' +import sort_variable_declarations_default from './rules/sort-variable-declarations.js' +import sort_intersection_types_default from './rules/sort-intersection-types.js' +import sort_import_attributes_default from './rules/sort-import-attributes.js' +import sort_export_attributes_default from './rules/sort-export-attributes.js' +import sort_heritage_clauses_default from './rules/sort-heritage-clauses.js' +import sort_array_includes_default from './rules/sort-array-includes.js' +import sort_named_imports_default from './rules/sort-named-imports.js' +import sort_named_exports_default from './rules/sort-named-exports.js' +import sort_object_types_default from './rules/sort-object-types.js' +import sort_switch_case_default from './rules/sort-switch-case.js' +import sort_union_types_default from './rules/sort-union-types.js' +import sort_interfaces_default from './rules/sort-interfaces.js' +import sort_decorators_default from './rules/sort-decorators.js' +import sort_jsx_props_default from './rules/sort-jsx-props.js' +import sort_classes_default from './rules/sort-classes.js' +import sort_imports_default from './rules/sort-imports.js' +import sort_exports_default from './rules/sort-exports.js' +import sort_objects_default from './rules/sort-objects.js' +import sort_modules_default from './rules/sort-modules.js' +import sort_arrays_default from './rules/sort-arrays.js' +import sort_enums_default from './rules/sort-enums.js' +import sort_maps_default from './rules/sort-maps.js' +import sort_sets_default from './rules/sort-sets.js' +var pluginName = 'perfectionist' +var recommendedRules = { + 'sort-variable-declarations': sort_variable_declarations_default, + 'sort-intersection-types': sort_intersection_types_default, + 'sort-import-attributes': sort_import_attributes_default, + 'sort-export-attributes': sort_export_attributes_default, + 'sort-heritage-clauses': sort_heritage_clauses_default, + 'sort-array-includes': sort_array_includes_default, + 'sort-named-imports': sort_named_imports_default, + 'sort-named-exports': sort_named_exports_default, + 'sort-object-types': sort_object_types_default, + 'sort-union-types': sort_union_types_default, + 'sort-switch-case': sort_switch_case_default, + 'sort-decorators': sort_decorators_default, + 'sort-interfaces': sort_interfaces_default, + 'sort-jsx-props': sort_jsx_props_default, + 'sort-modules': sort_modules_default, + 'sort-classes': sort_classes_default, + 'sort-imports': sort_imports_default, + 'sort-exports': sort_exports_default, + 'sort-objects': sort_objects_default, + 'sort-enums': sort_enums_default, + 'sort-sets': sort_sets_default, + 'sort-maps': sort_maps_default, +} +var rules = { + ...recommendedRules, + 'sort-arrays': sort_arrays_default, +} +var plugin = { + meta: { + version, + name, + }, + rules, +} +function getRules(options) { + return Object.fromEntries( + Object.keys(recommendedRules).map(ruleName => [ + `${pluginName}/${ruleName}`, + ['error', options], + ]), + ) +} +function createConfig(options) { + return { + plugins: { [pluginName]: plugin }, + rules: getRules(options), + } +} +function createLegacyConfig(options) { + return { + rules: getRules(options), + plugins: [pluginName], + } +} +var configs = { + 'recommended-alphabetical-legacy': createLegacyConfig({ + type: 'alphabetical', + order: 'asc', + }), + 'recommended-line-length-legacy': createLegacyConfig({ + type: 'line-length', + order: 'desc', + }), + 'recommended-natural-legacy': createLegacyConfig({ + type: 'natural', + order: 'asc', + }), + 'recommended-custom-legacy': createLegacyConfig({ + type: 'custom', + order: 'asc', + }), + 'recommended-alphabetical': createConfig({ + type: 'alphabetical', + order: 'asc', + }), + 'recommended-line-length': createConfig({ + type: 'line-length', + order: 'desc', + }), + 'recommended-natural': createConfig({ + type: 'natural', + order: 'asc', + }), + 'recommended-custom': createConfig({ + type: 'custom', + order: 'asc', + }), +} +var eslint_plugin_perfectionist_default = { + ...plugin, + configs, +} +export { configs, eslint_plugin_perfectionist_default as default, rules } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/package.json.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/package.json.js new file mode 100644 index 0000000000000000000000000000000000000000..86a46cb8332b7b0c05d193106ff8ef3fc62ccf51 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/package.json.js @@ -0,0 +1,3 @@ +var name = 'eslint-plugin-perfectionist' +var version = '5.10.1' +export { name, version } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-array-includes.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-array-includes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a1d1666121d1faaf895ba60ebfd2e8886eeb2f4f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-array-includes.d.ts @@ -0,0 +1,25 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +import { Options } from './sort-array-includes/types.js' +declare const ORDER_ERROR_ID = 'unexpectedArrayIncludesOrder' +declare const GROUP_ORDER_ERROR_ID = 'unexpectedArrayIncludesGroupOrder' +declare const EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenArrayIncludesMembers' +declare const MISSED_SPACING_ERROR_ID = + 'missedSpacingBetweenArrayIncludesMembers' +type MessageId = + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +export declare let defaultOptions: Required +export declare let jsonSchema: JSONSchema4 +declare const _default: import('@typescript-eslint/utils/ts-eslint').RuleModule< + MessageId, + import('...js').SortArraysOptions, + { + recommended?: boolean + }, + import('@typescript-eslint/utils/ts-eslint').RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-array-includes.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-array-includes.js new file mode 100644 index 0000000000000000000000000000000000000000..79f4ec229c1f3511087ee9feaca8cb76d8d54aa6 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-array-includes.js @@ -0,0 +1,128 @@ +import { + buildCommonJsonSchemas, + buildUseConfigIfJsonSchema, + matchesAstSelectorJsonSchema, +} from '../utils/json-schemas/common-json-schemas.js' +import { buildCommonGroupsJsonSchemas } from '../utils/json-schemas/common-groups-json-schemas.js' +import { + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { + partitionByCommentJsonSchema, + partitionByNewlineJsonSchema, +} from '../utils/json-schemas/common-partition-json-schemas.js' +import { buildAstListeners } from '../utils/build-ast-listeners.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { additionalCustomGroupMatchOptionsJsonSchema } from './sort-arrays/types.js' +import { sortArray } from './sort-arrays/sort-array.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Cache computed groups by modifiers and selectors for performance. + */ +var cachedGroupsByModifiersAndSelectors = /* @__PURE__ */ new Map() +var ORDER_ERROR_ID = 'unexpectedArrayIncludesOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedArrayIncludesGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenArrayIncludesMembers' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenArrayIncludesMembers' +var defaultOptions = { + fallbackSort: { type: 'unsorted' }, + newlinesInside: 'newlinesBetween', + specialCharacters: 'keep', + partitionByComment: false, + partitionByNewLine: false, + newlinesBetween: 'ignore', + useConfigurationIf: {}, + type: 'alphabetical', + groups: ['literal'], + ignoreCase: true, + locales: 'en-US', + customGroups: [], + alphabet: '', + order: 'asc', +} +var jsonSchema = { + items: { + properties: { + ...buildCommonJsonSchemas(), + ...buildCommonGroupsJsonSchemas({ + additionalCustomGroupMatchProperties: + additionalCustomGroupMatchOptionsJsonSchema, + }), + useConfigurationIf: buildUseConfigIfJsonSchema({ + additionalProperties: { + matchesAstSelector: matchesAstSelectorJsonSchema, + }, + }), + partitionByComment: partitionByCommentJsonSchema, + partitionByNewLine: partitionByNewlineJsonSchema, + }, + additionalProperties: false, + type: 'object', + }, + uniqueItems: true, + type: 'array', +} +var sort_array_includes_default = createEslintRule({ + meta: { + messages: { + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + description: 'Enforce sorted arrays before include method.', + url: 'https://perfectionist.dev/rules/sort-array-includes', + recommended: true, + }, + schema: jsonSchema, + type: 'suggestion', + fixable: 'code', + }, + create: context => + buildAstListeners({ + nodeTypes: [AST_NODE_TYPES.NewExpression, AST_NODE_TYPES.ArrayExpression], + sorter: sortPotentiallyValidArray, + context, + }), + defaultOptions: [defaultOptions], + name: 'sort-array-includes', +}) +function sortPotentiallyValidArray({ matchedAstSelectors, context, node }) { + if (!isValidArray()) { + return + } + sortArray({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + mustHaveMatchedContextOptions: false, + cachedGroupsByModifiersAndSelectors, + matchedAstSelectors, + defaultOptions, + context, + node, + }) + function isValidArray() { + if (node.parent.type !== AST_NODE_TYPES.MemberExpression) { + return false + } + if (node.parent.property.type !== AST_NODE_TYPES.Identifier) { + return false + } + if (node.parent.property.name !== 'includes') { + return false + } + if (node.parent.parent.type !== AST_NODE_TYPES.CallExpression) { + return false + } + return node.parent.parent.callee === node.parent + } +} +export { sort_array_includes_default as default, defaultOptions, jsonSchema } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-array-includes/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-array-includes/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c3335c8c0cd598be851c19c33d5bffb34f1c2c8e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-array-includes/types.d.ts @@ -0,0 +1,2 @@ +import { Options as SortArraysOptions } from '../sort-arrays/types.js' +export type Options = SortArraysOptions diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0590a52e5e855ffdf8b60bd831287705997cbb0b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays.d.ts @@ -0,0 +1,21 @@ +import { Options } from './sort-arrays/types.js' +declare const ORDER_ERROR_ID = 'unexpectedArraysOrder' +declare const GROUP_ORDER_ERROR_ID = 'unexpectedArraysGroupOrder' +declare const EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenArraysMembers' +declare const MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenArraysMembers' +type MessageId = + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +declare const _default: import('@typescript-eslint/utils/ts-eslint').RuleModule< + MessageId, + Options, + { + recommended?: boolean + }, + import('@typescript-eslint/utils/ts-eslint').RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays.js new file mode 100644 index 0000000000000000000000000000000000000000..3852050c1648e39dafb48c9499248e45a5a2a233 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays.js @@ -0,0 +1,112 @@ +import { + buildCommonJsonSchemas, + buildUseConfigIfJsonSchema, + matchesAstSelectorJsonSchema, +} from '../utils/json-schemas/common-json-schemas.js' +import { buildCommonGroupsJsonSchemas } from '../utils/json-schemas/common-groups-json-schemas.js' +import { + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { + partitionByCommentJsonSchema, + partitionByNewlineJsonSchema, +} from '../utils/json-schemas/common-partition-json-schemas.js' +import { buildAstListeners } from '../utils/build-ast-listeners.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { additionalCustomGroupMatchOptionsJsonSchema } from './sort-arrays/types.js' +import { sortArray } from './sort-arrays/sort-array.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Cache computed groups by modifiers and selectors for performance. + */ +var cachedGroupsByModifiersAndSelectors = /* @__PURE__ */ new Map() +var ORDER_ERROR_ID = 'unexpectedArraysOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedArraysGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenArraysMembers' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenArraysMembers' +var defaultOptions = { + fallbackSort: { type: 'unsorted' }, + newlinesInside: 'newlinesBetween', + specialCharacters: 'keep', + partitionByComment: false, + partitionByNewLine: false, + newlinesBetween: 'ignore', + useConfigurationIf: {}, + type: 'alphabetical', + groups: ['literal'], + ignoreCase: true, + locales: 'en-US', + customGroups: [], + alphabet: '', + order: 'asc', +} +var jsonSchema = { + items: { + properties: { + ...buildCommonJsonSchemas(), + ...buildCommonGroupsJsonSchemas({ + additionalCustomGroupMatchProperties: + additionalCustomGroupMatchOptionsJsonSchema, + }), + useConfigurationIf: buildUseConfigIfJsonSchema({ + additionalProperties: { + matchesAstSelector: matchesAstSelectorJsonSchema, + }, + }), + partitionByComment: partitionByCommentJsonSchema, + partitionByNewLine: partitionByNewlineJsonSchema, + }, + required: ['useConfigurationIf'], + additionalProperties: false, + type: 'object', + }, + uniqueItems: true, + type: 'array', + minItems: 1, +} +var sort_arrays_default = createEslintRule({ + meta: { + messages: { + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-arrays', + description: 'Enforce sorted arrays.', + recommended: false, + }, + schema: jsonSchema, + type: 'suggestion', + fixable: 'code', + }, + create: context => + buildAstListeners({ + nodeTypes: [AST_NODE_TYPES.NewExpression, AST_NODE_TYPES.ArrayExpression], + context, + sorter, + }), + defaultOptions: [defaultOptions], + name: 'sort-arrays', +}) +function sorter({ matchedAstSelectors, context, node }) { + sortArray({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + cachedGroupsByModifiersAndSelectors, + mustHaveMatchedContextOptions: true, + matchedAstSelectors, + defaultOptions, + context, + node, + }) +} +export { sort_arrays_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/compute-array-elements.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/compute-array-elements.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8b0a9d5bb44e17826a5920f1681a028ede380431 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/compute-array-elements.d.ts @@ -0,0 +1,11 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Computes array elements for the given expression. + * + * @param expression - The expression to compute array elements from. + * @returns An array of elements if the expression is an array or a new + * expression, otherwise null. + */ +export declare function computeArrayElements( + expression: TSESTree.ArrayExpression | TSESTree.NewExpression, +): (TSESTree.SpreadElement | TSESTree.Expression | null)[] | null diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/compute-array-elements.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/compute-array-elements.js new file mode 100644 index 0000000000000000000000000000000000000000..9ab801256ae235e887eb8e67a185c2391685ebb1 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/compute-array-elements.js @@ -0,0 +1,27 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes array elements for the given expression. + * + * @param expression - The expression to compute array elements from. + * @returns An array of elements if the expression is an array or a new + * expression, otherwise null. + */ +function computeArrayElements(expression) { + switch (expression.type) { + case AST_NODE_TYPES.ArrayExpression: + return expression.elements + case AST_NODE_TYPES.NewExpression: + if (expression.callee.type !== AST_NODE_TYPES.Identifier) { + return null + } + if (expression.callee.name !== 'Array') { + return null + } + return expression.arguments + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(expression) + } +} +export { computeArrayElements } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/compute-matched-context-options.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/compute-matched-context-options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c88827ad199a52aa3ef6f6729166c2b1367dda20 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/compute-matched-context-options.d.ts @@ -0,0 +1,25 @@ +import { RuleContext } from '@typescript-eslint/utils/ts-eslint' +import { TSESTree } from '@typescript-eslint/types' +import { Options } from './types.js' +/** + * Computes the matched context options for a given array node. + * + * @param params - Parameters. + * @param params.matchedAstSelectors - The matched AST selectors for an array + * node. + * @param params.elements - The array elements to compute the context options + * for. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +export declare function computeMatchedContextOptions< + MessageIds extends string, +>({ + matchedAstSelectors, + elements, + context, +}: { + elements: (TSESTree.SpreadElement | TSESTree.Expression | null)[] + context: Readonly> + matchedAstSelectors: ReadonlySet +}): Options[number] | undefined diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/compute-matched-context-options.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/compute-matched-context-options.js new file mode 100644 index 0000000000000000000000000000000000000000..ddf95b2774e5dc235b4d73f9e8d9f2f3d634bcf9 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/compute-matched-context-options.js @@ -0,0 +1,51 @@ +import { passesAllNamesMatchPatternFilter } from '../../utils/context-matching/passes-all-names-match-pattern-filter.js' +import { passesAstSelectorFilter } from '../../utils/context-matching/passes-ast-selector-filter.js' +import { computeNodeName } from './compute-node-name.js' +/** + * Computes the matched context options for a given array node. + * + * @param params - Parameters. + * @param params.matchedAstSelectors - The matched AST selectors for an array + * node. + * @param params.elements - The array elements to compute the context options + * for. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +function computeMatchedContextOptions({ + matchedAstSelectors, + elements, + context, +}) { + let nodeNames = elements + .filter(element => element !== null) + .map(element => + computeNodeName({ + sourceCode: context.sourceCode, + node: element, + }), + ) + return context.options.find(options => + isContextOptionMatching({ + matchedAstSelectors, + nodeNames, + options, + }), + ) +} +function isContextOptionMatching({ matchedAstSelectors, nodeNames, options }) { + if (!options.useConfigurationIf) { + return true + } + return ( + passesAllNamesMatchPatternFilter({ + allNamesMatchPattern: options.useConfigurationIf.allNamesMatchPattern, + nodeNames, + }) && + passesAstSelectorFilter({ + matchesAstSelector: options.useConfigurationIf.matchesAstSelector, + matchedAstSelectors, + }) + ) +} +export { computeMatchedContextOptions } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/compute-node-name.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/compute-node-name.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..69fefe83bd665f57b4017859cf945c51d7bc5597 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/compute-node-name.d.ts @@ -0,0 +1,17 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +/** + * Computes the name of an array member. + * + * @param props - The parameters object. + * @param props.sourceCode - ESLint source code object for text extraction. + * @param props.node - The AST node representing an array member. + * @returns The name of the array member. + */ +export declare function computeNodeName({ + sourceCode, + node, +}: { + node: TSESTree.SpreadElement | TSESTree.Expression + sourceCode: TSESLint.SourceCode +}): string diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/compute-node-name.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/compute-node-name.js new file mode 100644 index 0000000000000000000000000000000000000000..592c8740bca9d7fe7ea9f0cdf276754367af6a8c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/compute-node-name.js @@ -0,0 +1,15 @@ +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the name of an array member. + * + * @param props - The parameters object. + * @param props.sourceCode - ESLint source code object for text extraction. + * @param props.node - The AST node representing an array member. + * @returns The name of the array member. + */ +function computeNodeName({ sourceCode, node }) { + return node.type === AST_NODE_TYPES.Literal ? + String(node.value) + : sourceCode.getText(node) +} +export { computeNodeName } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/sort-array.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/sort-array.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3de0c4d4ca09ce02e1b850cca4e60ddfc3c4c38a --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/sort-array.d.ts @@ -0,0 +1,25 @@ +import { RuleContext } from '@typescript-eslint/utils/ts-eslint' +import { TSESTree } from '@typescript-eslint/types' +import { Options } from './types.js' +export declare function sortArray({ + cachedGroupsByModifiersAndSelectors, + mustHaveMatchedContextOptions, + availableMessageIds, + matchedAstSelectors, + defaultOptions, + context, + node, +}: { + availableMessageIds: { + missedSpacingBetweenMembers: MessageIds + extraSpacingBetweenMembers: MessageIds + unexpectedGroupOrder: MessageIds + unexpectedOrder: MessageIds + } + cachedGroupsByModifiersAndSelectors: Map + node: TSESTree.ArrayExpression | TSESTree.NewExpression + context: Readonly> + defaultOptions: Required + matchedAstSelectors: ReadonlySet + mustHaveMatchedContextOptions: boolean +}): void diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/sort-array.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/sort-array.js new file mode 100644 index 0000000000000000000000000000000000000000..e063c8f44d8451538358ddfbfc346fccb523ec30 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/sort-array.js @@ -0,0 +1,138 @@ +import { defaultComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +import { validateNewlinesAndPartitionConfig } from '../../utils/validate-newlines-and-partition-config.js' +import { buildOptionsByGroupIndexComputer } from '../../utils/build-options-by-group-index-computer.js' +import { validateCustomSortConfig } from '../../utils/validate-custom-sort-config.js' +import { generatePredefinedGroups } from '../../utils/generate-predefined-groups.js' +import { getEslintDisabledLines } from '../../utils/get-eslint-disabled-lines.js' +import { doesCustomGroupMatch } from '../../utils/does-custom-group-match.js' +import { isNodeEslintDisabled } from '../../utils/is-node-eslint-disabled.js' +import { validateGroupsConfig } from '../../utils/validate-groups-config.js' +import { sortNodesByGroups } from '../../utils/sort-nodes-by-groups.js' +import { reportAllErrors } from '../../utils/report-all-errors.js' +import { shouldPartition } from '../../utils/should-partition.js' +import { computeGroup } from '../../utils/compute-group.js' +import { rangeToDiff } from '../../utils/range-to-diff.js' +import { getSettings } from '../../utils/get-settings.js' +import { isSortable } from '../../utils/is-sortable.js' +import { complete } from '../../utils/complete.js' +import { allSelectors } from './types.js' +import { computeNodeName } from './compute-node-name.js' +import { computeMatchedContextOptions } from './compute-matched-context-options.js' +import { computeArrayElements } from './compute-array-elements.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +function sortArray({ + cachedGroupsByModifiersAndSelectors, + mustHaveMatchedContextOptions, + availableMessageIds, + matchedAstSelectors, + defaultOptions, + context, + node, +}) { + let elements = computeArrayElements(node) + if (!elements) { + return + } + if (!isSortable(elements)) { + return + } + let { sourceCode, id } = context + let settings = getSettings(context.settings) + let matchedContextOptions = computeMatchedContextOptions({ + matchedAstSelectors, + elements, + context, + }) + if (mustHaveMatchedContextOptions && !matchedContextOptions) { + return + } + let options = complete(matchedContextOptions, settings, defaultOptions) + validateCustomSortConfig(options) + validateGroupsConfig({ + selectors: allSelectors, + modifiers: [], + options, + }) + validateNewlinesAndPartitionConfig(options) + let eslintDisabledLines = getEslintDisabledLines({ + ruleName: id, + sourceCode, + }) + let optionsByGroupIndexComputer = buildOptionsByGroupIndexComputer(options) + let formattedMembers = elements.reduce( + (accumulator, element) => { + if (element === null) { + return accumulator + } + if (element.type === AST_NODE_TYPES.SpreadElement) { + accumulator.push([]) + return accumulator + } + let name = computeNodeName({ + node: element, + sourceCode, + }) + let selector = 'literal' + let predefinedGroups = generatePredefinedGroups({ + cache: cachedGroupsByModifiersAndSelectors, + selectors: [selector], + modifiers: [], + }) + let group = computeGroup({ + customGroupMatcher: customGroup => + doesCustomGroupMatch({ + selectors: [selector], + elementName: name, + modifiers: [], + customGroup, + }), + predefinedGroups, + options, + }) + let sortingNode = { + isEslintDisabled: isNodeEslintDisabled(element, eslintDisabledLines), + size: rangeToDiff(element, sourceCode), + node: element, + group, + name, + } + let lastSortingNode = accumulator.at(-1)?.at(-1) + if ( + shouldPartition({ + lastSortingNode, + sortingNode, + sourceCode, + options, + }) + ) { + accumulator.push([]) + } + accumulator.at(-1).push({ + ...sortingNode, + partitionId: accumulator.length, + }) + return accumulator + }, + [[]], + ) + function sortNodesExcludingEslintDisabled(ignoreEslintDisabledNodes) { + return formattedMembers.flatMap(nodes => + sortNodesByGroups({ + comparatorByOptionsComputer: defaultComparatorByOptionsComputer, + optionsByGroupIndexComputer, + ignoreEslintDisabledNodes, + groups: options.groups, + nodes, + }), + ) + } + let nodes = formattedMembers.flat() + reportAllErrors({ + sortNodesExcludingEslintDisabled, + availableMessageIds, + options, + context, + nodes, + }) +} +export { sortArray } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5169b0e4ec1d68144edb67b31402ff0f1fba55c0 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/types.d.ts @@ -0,0 +1,74 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +import { RegexOption, TypeOption } from '../../types/common-options.js' +import { AllCommonOptions } from '../../types/all-common-options.js' +/** + * Configuration options for the sort-array-includes rule. + * + * This rule enforces the sorting of arrays passed to the `.includes()` method, + * ensuring consistent ordering of array elements for better readability and + * maintainability. + */ +export type Options = Partial< + { + /** + * Conditional configuration based on pattern matching. + */ + useConfigurationIf: { + /** + * Regular expression pattern to match against all array element names. + * The rule is only applied when all names match this pattern. + */ + allNamesMatchPattern?: RegexOption + /** + * AST selector to match against ArrayExpression nodes. + */ + matchesAstSelector?: string + } + } & AllCommonOptions< + TypeOption, + AdditionalSortOptions, + CustomGroupMatchOptions + > +>[] +/** + * Represents the type of array element selector. Note: Spread elements are not + * sorted and act as partition boundaries. + */ +export type Selector = (typeof allSelectors)[number] +/** + * Additional configuration for a single custom group. + * + * Custom groups allow fine-grained control over how array elements are grouped + * and sorted based on their names and types. + * + * @example + * + * ```ts + * { + * "selector": "literal" + * } + * ``` + */ +interface CustomGroupMatchOptions { + /** + * Specifies the type of array elements to include in this group. Only + * 'literal' is available since spread elements create partition boundaries + * and are not sorted. + */ + selector?: Selector +} +type AdditionalSortOptions = object +/** + * Complete list of available selectors for array elements. Used for validation + * and JSON schema generation. + */ +export declare let allSelectors: readonly ['literal'] +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +export declare let additionalCustomGroupMatchOptionsJsonSchema: Record< + string, + JSONSchema4 +> +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/types.js new file mode 100644 index 0000000000000000000000000000000000000000..a9830c524c6e863479c07aa677a3a314da752086 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-arrays/types.js @@ -0,0 +1,14 @@ +import { buildCustomGroupSelectorJsonSchema } from '../../utils/json-schemas/common-groups-json-schemas.js' +/** + * Complete list of available selectors for array elements. Used for validation + * and JSON schema generation. + */ +var allSelectors = ['literal'] +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +var additionalCustomGroupMatchOptionsJsonSchema = { + selector: buildCustomGroupSelectorJsonSchema(allSelectors), +} +export { additionalCustomGroupMatchOptionsJsonSchema, allSelectors } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a3d6b0d7297e348082ebc97283c0a3e05a44b6e1 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes.d.ts @@ -0,0 +1,12 @@ +import { MessageId, Options } from './sort-classes/types.js' +declare const _default: import('@typescript-eslint/utils/ts-eslint').RuleModule< + MessageId, + Options, + { + recommended?: boolean + }, + import('@typescript-eslint/utils/ts-eslint').RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes.js new file mode 100644 index 0000000000000000000000000000000000000000..831f893a16675dae3e0aa4bebb2f5a1023adf526 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes.js @@ -0,0 +1,87 @@ +import { + buildCommonJsonSchemas, + buildRegexJsonSchema, + buildUseConfigIfJsonSchema, + matchesAstSelectorJsonSchema, + useExperimentalDependencyDetectionJsonSchema, +} from '../utils/json-schemas/common-json-schemas.js' +import { + buildCommonGroupsJsonSchemas, + newlinesBetweenJsonSchema, +} from '../utils/json-schemas/common-groups-json-schemas.js' +import { + DEPENDENCY_ORDER_ERROR, + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { + partitionByCommentJsonSchema, + partitionByNewlineJsonSchema, +} from '../utils/json-schemas/common-partition-json-schemas.js' +import { buildAstListeners } from '../utils/build-ast-listeners.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { + DEPENDENCY_ORDER_ERROR_ID, + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + additionalCustomGroupMatchOptionsJsonSchema, +} from './sort-classes/types.js' +import { defaultOptions, sortClass } from './sort-classes/sort-class.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var sort_classes_default = createEslintRule({ + meta: { + schema: { + items: { + properties: { + ...buildCommonJsonSchemas(), + ...buildCommonGroupsJsonSchemas({ + additionalCustomGroupMatchProperties: + additionalCustomGroupMatchOptionsJsonSchema, + }), + useConfigurationIf: buildUseConfigIfJsonSchema({ + additionalProperties: { + matchesAstSelector: matchesAstSelectorJsonSchema, + }, + }), + useExperimentalDependencyDetection: + useExperimentalDependencyDetectionJsonSchema, + newlinesBetweenOverloadSignatures: newlinesBetweenJsonSchema, + ignoreCallbackDependenciesPatterns: buildRegexJsonSchema(), + partitionByComment: partitionByCommentJsonSchema, + partitionByNewLine: partitionByNewlineJsonSchema, + }, + additionalProperties: false, + type: 'object', + }, + uniqueItems: true, + type: 'array', + }, + messages: { + [DEPENDENCY_ORDER_ERROR_ID]: DEPENDENCY_ORDER_ERROR, + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-classes', + description: 'Enforce sorted classes.', + recommended: true, + }, + type: 'suggestion', + fixable: 'code', + }, + create: context => + buildAstListeners({ + nodeTypes: [AST_NODE_TYPES.ClassBody], + sorter: sortClass, + context, + }), + defaultOptions: [defaultOptions], + name: 'sort-classes', +}) +export { sort_classes_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-dependencies-by-sorting-node.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-dependencies-by-sorting-node.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..15213eb447dbbaaa9d272232bafd26007ac2c83e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-dependencies-by-sorting-node.d.ts @@ -0,0 +1,20 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +import { SortClassesSortingNode } from './types.js' +import { RegexOption } from '../../types/common-options.js' +type SortingNodeWithoutDependencies = Omit< + SortClassesSortingNode, + 'dependencies' +> +export declare function computeDependenciesBySortingNode({ + ignoreCallbackDependenciesPatterns, + sortingNodes, + sourceCode, + classBody, +}: { + ignoreCallbackDependenciesPatterns: RegexOption + sortingNodes: SortingNodeWithoutDependencies[] + sourceCode: TSESLint.SourceCode + classBody: TSESTree.ClassBody +}): Map +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-dependencies-by-sorting-node.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-dependencies-by-sorting-node.js new file mode 100644 index 0000000000000000000000000000000000000000..4340686505f2122a5aefdd376b54f8c79e5c53e8 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-dependencies-by-sorting-node.js @@ -0,0 +1,186 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { matches } from '../../utils/matches.js' +import { computeDependenciesBySortingNode as computeDependenciesBySortingNode$1 } from '../../utils/compute-dependencies-by-sorting-node.js' +import { computeParentNodesWithTypes } from '../../utils/compute-parent-nodes-with-types.js' +import { computeIdentifierNameDetails } from './compute-identifier-name-details.js' +import { AST_NODE_TYPES, AST_TOKEN_TYPES } from '@typescript-eslint/utils' +function computeDependenciesBySortingNode({ + ignoreCallbackDependenciesPatterns, + sortingNodes, + sourceCode, + classBody, +}) { + let staticSortingNodes = sortingNodes.filter(node => node.isStatic) + let dependenciesBySortingNode = computeDependenciesBySortingNode$1({ + additionalIdentifierDependenciesComputer: + buildAdditionalIdentifierDependenciesComputer({ + ignoreCallbackDependenciesPatterns, + staticSortingNodes, + classBody, + }), + shouldIgnoreSortingNodeComputer: sortingNode => + shouldIgnoreDependencyComputation(sortingNode.node), + sortingNodes, + sourceCode, + }) + let thisDependenciesBySortingNode = + computeThisExpressionDependenciesBySortingNode({ + ignoreCallbackDependenciesPatterns, + sortingNodes, + sourceCode, + }) + for (let [sortingNode, dependencies] of thisDependenciesBySortingNode) { + let existingDependencies = dependenciesBySortingNode.get(sortingNode) ?? [] + dependenciesBySortingNode.set(sortingNode, [ + ...existingDependencies, + ...dependencies, + ]) + } + return dependenciesBySortingNode +} +function computeIdentifierOrThisExpressionDependency({ + ignoreCallbackDependenciesPatterns, + sortingNodes, + classElement, + node, +}) { + if (shouldIgnoreCallbackDependency()) { + return null + } + let { parent } = node + /* v8 ignore if -- @preserve Unsure how we can reach that case */ + if (parent.type !== AST_NODE_TYPES.MemberExpression) { + return null + } + let dependencyName = computeDependencyNameFromMemberExpression(parent) + /* v8 ignore if -- @preserve Unsure how we can reach that case */ + if (!dependencyName) { + return null + } + return ( + sortingNodes.find( + currentSortingNode => currentSortingNode.name === dependencyName.name, + ) ?? null + ) + function computeDependencyNameFromMemberExpression(memberExpression) { + switch (memberExpression.property.type) { + case AST_NODE_TYPES.PrivateIdentifier: + case AST_NODE_TYPES.Identifier: + case AST_NODE_TYPES.Literal: + return computeIdentifierNameDetails(memberExpression.property) + /* v8 ignore next 2 -- @preserve Unhandled cases */ + default: + return null + } + } + function shouldIgnoreCallbackDependency() { + return computeParentNodesWithTypes({ + allowedTypes: [AST_NODE_TYPES.CallExpression], + maxParent: classElement, + consecutiveOnly: false, + node, + }).some(shouldIgnoreCallExpression) + function shouldIgnoreCallExpression(callExpressionParent) { + return ( + 'name' in callExpressionParent.callee && + matches( + callExpressionParent.callee.name, + ignoreCallbackDependenciesPatterns, + ) + ) + } + } +} +function computeThisExpressionDependenciesBySortingNode({ + ignoreCallbackDependenciesPatterns, + sortingNodes, + sourceCode, +}) { + let dependenciesBySortingNode = /* @__PURE__ */ new Map() + let staticSortingNodes = sortingNodes.filter(node => node.isStatic) + let nonStaticSortingNodes = sortingNodes.filter(node => !node.isStatic) + let relevantSortingNodes = sortingNodes.filter( + sortingNode => !shouldIgnoreDependencyComputation(sortingNode.node), + ) + for (let sortingNode of relevantSortingNodes) { + let dependencies = computeThisExpressionsInsideClassElement({ + classElement: sortingNode.node, + sourceCode, + }) + .map(thisExpression => + computeIdentifierOrThisExpressionDependency({ + sortingNodes: + sortingNode.isStatic ? staticSortingNodes : nonStaticSortingNodes, + ignoreCallbackDependenciesPatterns, + classElement: sortingNode.node, + node: thisExpression, + }), + ) + .filter(dependency => dependency !== null) + if (dependencies.length === 0) { + continue + } + dependenciesBySortingNode.set(sortingNode, dependencies) + } + return dependenciesBySortingNode +} +function buildAdditionalIdentifierDependenciesComputer({ + ignoreCallbackDependenciesPatterns, + staticSortingNodes, + classBody, +}) { + return ({ referencingSortingNode, reference }) => { + if (!reference.resolved?.identifiers[0]) { + return [] + } + let classIdentifier = classBody.parent.id + if (reference.resolved?.identifiers[0] !== classIdentifier) { + return [] + } + let dependency = computeIdentifierOrThisExpressionDependency({ + classElement: referencingSortingNode.node, + ignoreCallbackDependenciesPatterns, + sortingNodes: staticSortingNodes, + node: reference.identifier, + }) + return dependency ? [dependency] : [] + } +} +function shouldIgnoreDependencyComputation(node) { + switch (node.type) { + case AST_NODE_TYPES.TSAbstractPropertyDefinition: + case AST_NODE_TYPES.TSAbstractMethodDefinition: + case AST_NODE_TYPES.StaticBlock: + return false + case AST_NODE_TYPES.TSAbstractAccessorProperty: + case AST_NODE_TYPES.PropertyDefinition: + case AST_NODE_TYPES.AccessorProperty: + return ( + node.value?.type === AST_NODE_TYPES.ArrowFunctionExpression || + node.value?.type === AST_NODE_TYPES.FunctionExpression + ) + case AST_NODE_TYPES.MethodDefinition: + case AST_NODE_TYPES.TSIndexSignature: + return true + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(node) + } +} +function computeThisExpressionsInsideClassElement({ + classElement, + sourceCode, +}) { + return sourceCode + .getTokens(classElement) + .filter(isThisToken) + .map(computeTokenNode) + .filter(node => node?.type === AST_NODE_TYPES.ThisExpression) + function computeTokenNode(token) { + return sourceCode.getNodeByRangeIndex(token.range[0]) + } + function isThisToken(token) { + return token.type === AST_TOKEN_TYPES.Keyword && token.value === 'this' + } +} +export { computeDependenciesBySortingNode } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-dependencies.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-dependencies.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e21d1db475b21e790218d8938008837faf874df7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-dependencies.d.ts @@ -0,0 +1,29 @@ +import { TSESTree } from '@typescript-eslint/types' +import { RegexOption } from '../../types/common-options.js' +/** + * Computes the dependencies of a class member AST node. + * + * @deprecated - To remove when experimental dependency detection is the only. + * @param params - Parameters object. + * @param params.ignoreCallbackDependenciesPatterns - Patterns to ignore + * callback dependencies. + * @param params.useExperimentalDependencyDetection - Whether to use + * experimental dependency detection. + * @param params.isMemberStatic - Indicates if the member is static. + * @param params.expression - The AST node expression to analyze. + * @param params.className - The name of the class, if available. + * @returns The names of the dependencies. + */ +export declare function computeDependencies({ + ignoreCallbackDependenciesPatterns, + useExperimentalDependencyDetection, + isMemberStatic, + expression, + className, +}: { + expression: TSESTree.StaticBlock | TSESTree.Expression + ignoreCallbackDependenciesPatterns: RegexOption + useExperimentalDependencyDetection: boolean + className: undefined | string + isMemberStatic: boolean +}): string[] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-dependencies.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-dependencies.js new file mode 100644 index 0000000000000000000000000000000000000000..3e000595fb670e1fbbf89eb8bd3dd7b34bb4ff8b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-dependencies.js @@ -0,0 +1,163 @@ +import { matches } from '../../utils/matches.js' +import { computeIdentifierNameDetails } from './compute-identifier-name-details.js' +import { computeDependencyName } from './compute-dependency-name.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the dependencies of a class member AST node. + * + * @deprecated - To remove when experimental dependency detection is the only. + * @param params - Parameters object. + * @param params.ignoreCallbackDependenciesPatterns - Patterns to ignore + * callback dependencies. + * @param params.useExperimentalDependencyDetection - Whether to use + * experimental dependency detection. + * @param params.isMemberStatic - Indicates if the member is static. + * @param params.expression - The AST node expression to analyze. + * @param params.className - The name of the class, if available. + * @returns The names of the dependencies. + */ +function computeDependencies({ + ignoreCallbackDependenciesPatterns, + useExperimentalDependencyDetection, + isMemberStatic, + expression, + className, +}) { + if (useExperimentalDependencyDetection) { + return [] + } + let dependencies = [] + traverseNode(expression) + return dependencies + function checkNode(nodeValue) { + switch (nodeValue.type) { + case AST_NODE_TYPES.ConditionalExpression: + traverseNode(nodeValue.test) + traverseNode(nodeValue.consequent) + traverseNode(nodeValue.alternate) + break + case AST_NODE_TYPES.MemberExpression: + dependencies.push( + ...computeMemberExpressionDependencies({ + memberExpression: nodeValue, + isMemberStatic, + className, + }), + ) + break + case AST_NODE_TYPES.CallExpression: + if (!('name' in nodeValue.callee)) { + traverseNode(nodeValue.arguments) + break + } + if ( + matches(nodeValue.callee.name, ignoreCallbackDependenciesPatterns) + ) { + break + } + traverseNode(nodeValue.arguments) + break + case AST_NODE_TYPES.NewExpression: + traverseNode(nodeValue.arguments) + break + case AST_NODE_TYPES.Property: + traverseNode(nodeValue.key) + traverseNode(nodeValue.value) + } + if ('argument' in nodeValue && nodeValue.argument) { + traverseNode(nodeValue.argument) + } + if ('body' in nodeValue && nodeValue.body) { + traverseNode(nodeValue.body) + } + if ('callee' in nodeValue) { + traverseNode(nodeValue.callee) + } + if ('declarations' in nodeValue) { + traverseNode(nodeValue.declarations) + } + if ('elements' in nodeValue) { + traverseNode( + nodeValue.elements.filter(currentNode => currentNode !== null), + ) + } + if ( + 'expression' in nodeValue && + typeof nodeValue.expression !== 'boolean' + ) { + traverseNode(nodeValue.expression) + } + if ('expressions' in nodeValue) { + traverseNode(nodeValue.expressions) + } + if ('init' in nodeValue && nodeValue.init) { + traverseNode(nodeValue.init) + } + if ('left' in nodeValue) { + traverseNode(nodeValue.left) + } + if ('object' in nodeValue) { + traverseNode(nodeValue.object) + } + if ('properties' in nodeValue) { + traverseNode(nodeValue.properties) + } + if ('right' in nodeValue) { + traverseNode(nodeValue.right) + } + } + function traverseNode(nodeValue) { + if (Array.isArray(nodeValue)) { + for (let nodeItem of nodeValue) { + traverseNode(nodeItem) + } + } else { + checkNode(nodeValue) + } + } +} +function computeMemberExpressionDependencies({ + memberExpression, + isMemberStatic, + className, +}) { + switch (memberExpression.object.type) { + case AST_NODE_TYPES.ThisExpression: + return computeIdentifierOrThisExpressionDependencies() + case AST_NODE_TYPES.Identifier: + return memberExpression.object.name === className ? + computeIdentifierOrThisExpressionDependencies() + : [] + default: + return [] + } + function computeIdentifierOrThisExpressionDependencies() { + let dependency = computeDependencyFromProperty() + /* v8 ignore next 2 -- @preserve Unhandled cases */ + if (!dependency) { + return [] + } + return [dependency] + } + function computeDependencyFromProperty() { + switch (memberExpression.property.type) { + case AST_NODE_TYPES.PrivateIdentifier: + case AST_NODE_TYPES.Identifier: + case AST_NODE_TYPES.Literal: { + let { nameWithoutStartingHash, hasPrivateHash } = + computeIdentifierNameDetails(memberExpression.property) + return computeDependencyName({ + isStatic: + isMemberStatic || + memberExpression.object.type === AST_NODE_TYPES.Identifier, + nodeNameWithoutStartingHash: nameWithoutStartingHash, + hasPrivateHash, + }) + } + /* v8 ignore next 2 -- @preserve Unhandled cases */ + default: + return null + } + } +} +export { computeDependencies } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-dependency-name.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-dependency-name.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fb9f72896a376fff416fbff73b51eac98f021157 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-dependency-name.d.ts @@ -0,0 +1,9 @@ +export declare function computeDependencyName({ + nodeNameWithoutStartingHash, + hasPrivateHash, + isStatic, +}: { + nodeNameWithoutStartingHash: string + hasPrivateHash: boolean + isStatic: boolean +}): string diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-dependency-name.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-dependency-name.js new file mode 100644 index 0000000000000000000000000000000000000000..8d5685d1ce1b22dc08fc2d230ea929123adebe6e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-dependency-name.js @@ -0,0 +1,8 @@ +function computeDependencyName({ + nodeNameWithoutStartingHash, + hasPrivateHash, + isStatic, +}) { + return `${isStatic ? 'static ' : ''}${hasPrivateHash ? '#' : ''}${nodeNameWithoutStartingHash}` +} +export { computeDependencyName } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-identifier-name-details.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-identifier-name-details.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b2b10b63256ecec3f3aa44718cfc57c10f04d2f1 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-identifier-name-details.d.ts @@ -0,0 +1,12 @@ +import { TSESTree } from '@typescript-eslint/types' +import { NodeNameDetails } from './types.js' +/** + * Computes the name details of an identifier. + * + * @param node - The node to compute the name details for. + * @returns An object containing the name, whether it has a private hash, and + * the name without the starting hash. + */ +export declare function computeIdentifierNameDetails( + node: TSESTree.PrivateIdentifier | TSESTree.Identifier | TSESTree.Literal, +): NodeNameDetails diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-identifier-name-details.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-identifier-name-details.js new file mode 100644 index 0000000000000000000000000000000000000000..91b71a1476b6bf8b4521bf6a6ed634ecd4c20898 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-identifier-name-details.js @@ -0,0 +1,34 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the name details of an identifier. + * + * @param node - The node to compute the name details for. + * @returns An object containing the name, whether it has a private hash, and + * the name without the starting hash. + */ +function computeIdentifierNameDetails(node) { + switch (node.type) { + case AST_NODE_TYPES.PrivateIdentifier: + return { + nameWithoutStartingHash: node.name, + name: `#${node.name}`, + hasPrivateHash: true, + } + case AST_NODE_TYPES.Identifier: + return buildNonPrivateHashDetails(node.name) + case AST_NODE_TYPES.Literal: + return buildNonPrivateHashDetails(String(node.value)) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(node) + } +} +function buildNonPrivateHashDetails(name) { + return { + nameWithoutStartingHash: name, + hasPrivateHash: false, + name, + } +} +export { computeIdentifierNameDetails } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-matched-context-options.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-matched-context-options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6e1ae8fe2baab3cd8412e5d7e50521e9160eab11 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-matched-context-options.d.ts @@ -0,0 +1,21 @@ +import { RuleContext } from '@typescript-eslint/utils/ts-eslint' +import { TSESTree } from '@typescript-eslint/types' +import { MessageId, Options } from './types.js' +/** + * Computes the matched context options for a given class node. + * + * @param params - Parameters. + * @param params.matchedAstSelectors - The matched AST selectors for a class + * node. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +export declare function computeMatchedContextOptions({ + matchedAstSelectors, + classElements, + context, +}: { + context: Readonly> + matchedAstSelectors: ReadonlySet + classElements: TSESTree.ClassElement[] +}): Options[number] | undefined diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-matched-context-options.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-matched-context-options.js new file mode 100644 index 0000000000000000000000000000000000000000..64e9f7ee251e7e46ddba9943648bba3ee1323235 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-matched-context-options.js @@ -0,0 +1,52 @@ +import { passesAllNamesMatchPatternFilter } from '../../utils/context-matching/passes-all-names-match-pattern-filter.js' +import { passesAstSelectorFilter } from '../../utils/context-matching/passes-ast-selector-filter.js' +import { computeMethodOrPropertyNameDetails } from './node-info/compute-method-or-property-name-details.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the matched context options for a given class node. + * + * @param params - Parameters. + * @param params.matchedAstSelectors - The matched AST selectors for a class + * node. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +function computeMatchedContextOptions({ + matchedAstSelectors, + classElements, + context, +}) { + let nodeNames = classElements + .filter( + element => + element.type !== AST_NODE_TYPES.StaticBlock && + element.type !== AST_NODE_TYPES.TSIndexSignature, + ) + .map( + element => + computeMethodOrPropertyNameDetails(element, context.sourceCode).name, + ) + return context.options.find(options => + isContextOptionMatching({ + matchedAstSelectors, + nodeNames, + options, + }), + ) +} +function isContextOptionMatching({ matchedAstSelectors, nodeNames, options }) { + if (!options.useConfigurationIf) { + return true + } + return ( + passesAllNamesMatchPatternFilter({ + allNamesMatchPattern: options.useConfigurationIf.allNamesMatchPattern, + nodeNames, + }) && + passesAstSelectorFilter({ + matchesAstSelector: options.useConfigurationIf.matchesAstSelector, + matchedAstSelectors, + }) + ) +} +export { computeMatchedContextOptions } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-overload-signature-groups.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-overload-signature-groups.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b6cf2794fb1d21b3db7418a224d5918e0778cf1e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-overload-signature-groups.d.ts @@ -0,0 +1,13 @@ +import { TSESTree } from '@typescript-eslint/utils' +import { OverloadSignatureGroup } from '../../utils/overload-signature/overload-signature-group.js' +type Method = TSESTree.TSAbstractMethodDefinition | TSESTree.MethodDefinition +/** + * Returns a list of groups of overload signatures. + * + * @param classElements - The class elements to process. + * @returns A list of overload signature groups. + */ +export declare function computeOverloadSignatureGroups( + classElements: TSESTree.ClassElement[], +): OverloadSignatureGroup[] +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-overload-signature-groups.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-overload-signature-groups.js new file mode 100644 index 0000000000000000000000000000000000000000..8824b0a12f70f3afcdd1fc2285ef56a88d56b641 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/compute-overload-signature-groups.js @@ -0,0 +1,63 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { isSortable } from '../../utils/is-sortable.js' +import { OverloadSignatureGroup } from '../../utils/overload-signature/overload-signature-group.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Returns a list of groups of overload signatures. + * + * @param classElements - The class elements to process. + * @returns A list of overload signature groups. + */ +function computeOverloadSignatureGroups(classElements) { + let methods = classElements + .filter( + classElement => + classElement.type === AST_NODE_TYPES.MethodDefinition || + classElement.type === AST_NODE_TYPES.TSAbstractMethodDefinition, + ) + .filter(classElement => classElement.kind === 'method') + let staticOverloadSignaturesByName = /* @__PURE__ */ new Map() + let overloadSignaturesByName = /* @__PURE__ */ new Map() + for (let method of methods) { + if (method.key.type !== AST_NODE_TYPES.Identifier) { + continue + } + let { name } = method.key + let mapToUse = + method.static ? staticOverloadSignaturesByName : overloadSignaturesByName + let overloadSignaturesArray = mapToUse.get(name) + if (!overloadSignaturesArray) { + overloadSignaturesArray = [] + mapToUse.set(name, overloadSignaturesArray) + } + overloadSignaturesArray.push(method) + } + return [ + ...overloadSignaturesByName.values(), + ...staticOverloadSignaturesByName.values(), + ] + .filter(isSortable) + .map(buildOverloadSignatureGroup) +} +function buildOverloadSignatureGroup(methods) { + let implementation = methods.find(isMethodImplementation) ?? methods.at(-1) + let overloadSignatures = methods.filter( + method => !isMethodImplementation(method), + ) + return new OverloadSignatureGroup({ + overloadSignatures, + implementation, + }) + function isMethodImplementation(method) { + switch (method.value.type) { + case AST_NODE_TYPES.TSEmptyBodyFunctionExpression: + return false + case AST_NODE_TYPES.FunctionExpression: + return true + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(method.value) + } + } +} +export { computeOverloadSignatureGroups } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/is-known-class-element.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/is-known-class-element.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd9c9a6e3a64a87b1e9886d137b4196ff1a910c6 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/is-known-class-element.d.ts @@ -0,0 +1,13 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Checks whether a class element is supported by the sort-classes rule. + * + * Unknown elements should be ignored to avoid crashes with non-standard parsers + * while letting known elements keep their ordering behavior. + * + * @param member - The class element to check. + * @returns True when the element is a known, supported class member. + */ +export declare function isKnownClassElement( + member: TSESTree.ClassElement, +): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/is-known-class-element.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/is-known-class-element.js new file mode 100644 index 0000000000000000000000000000000000000000..8105ef40fe2ef15de1dc59a24cd192434d86a8d4 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/is-known-class-element.js @@ -0,0 +1,27 @@ +import '../../utils/assert-is-never.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Checks whether a class element is supported by the sort-classes rule. + * + * Unknown elements should be ignored to avoid crashes with non-standard parsers + * while letting known elements keep their ordering behavior. + * + * @param member - The class element to check. + * @returns True when the element is a known, supported class member. + */ +function isKnownClassElement(member) { + switch (member.type) { + case AST_NODE_TYPES.TSAbstractPropertyDefinition: + case AST_NODE_TYPES.TSAbstractMethodDefinition: + case AST_NODE_TYPES.TSAbstractAccessorProperty: + case AST_NODE_TYPES.PropertyDefinition: + case AST_NODE_TYPES.MethodDefinition: + case AST_NODE_TYPES.AccessorProperty: + case AST_NODE_TYPES.TSIndexSignature: + case AST_NODE_TYPES.StaticBlock: + return true + default: + return false + } +} +export { isKnownClassElement } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/common-modifiers.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/common-modifiers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..37f06af72ee67944674fb7ef496403170b8806c8 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/common-modifiers.d.ts @@ -0,0 +1,38 @@ +import { TSESTree } from '@typescript-eslint/types' +import { Modifier } from '../types.js' +type Property = + TSESTree.TSAbstractPropertyDefinition | TSESTree.PropertyDefinition +type Accessor = TSESTree.TSAbstractAccessorProperty | TSESTree.AccessorProperty +type Method = TSESTree.TSAbstractMethodDefinition | TSESTree.MethodDefinition +export declare function computeAccessibilityModifier({ + hasPrivateHash, + node, +}: { + node: Accessor | Property | Method + hasPrivateHash: boolean +}): Modifier[] +export declare function computeAbstractModifier( + node: Accessor | Property | Method, +): Modifier[] +export declare function computeAsyncModifier( + node: + | TSESTree.TSEmptyBodyFunctionExpression + | TSESTree.ArrowFunctionExpression + | TSESTree.FunctionExpression, +): Modifier[] +export declare function computeStaticModifier( + node: TSESTree.TSIndexSignature | Accessor | Property | Method, +): Modifier[] +export declare function computeReadonlyModifier( + node: TSESTree.TSIndexSignature | Property, +): Modifier[] +export declare function computeOverrideModifier( + node: Accessor | Property | Method, +): Modifier[] +export declare function computeOptionalModifier( + node: Property | Method, +): Modifier[] +export declare function computeDecoratedModifier( + isDecorated: boolean, +): Modifier[] +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/common-modifiers.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/common-modifiers.js new file mode 100644 index 0000000000000000000000000000000000000000..c5504f4ebd4a164cb1f0705ace82517f30985927 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/common-modifiers.js @@ -0,0 +1,71 @@ +import { UnreachableCaseError } from '../../../utils/unreachable-case-error.js' +import '../../../utils/assert-is-never.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +function computeAccessibilityModifier({ hasPrivateHash, node }) { + if (hasPrivateHash) { + return ['private'] + } + switch (node.accessibility) { + case 'protected': + return ['protected'] + case 'private': + return ['private'] + case void 0: + case 'public': + return ['public'] + default: + node.accessibility + return computeUnhandledAccessibilityModifier(node.accessibility) + } + function computeUnhandledAccessibilityModifier(modifier) { + /* v8 ignore else -- @preserve Unhandled case */ + if (modifier === null) { + return ['public'] + } + /* v8 ignore next -- @preserve Unhandled case */ + throw new Error('Unhandled accessibility modifier') + } +} +function computeAbstractModifier(node) { + switch (node.type) { + case AST_NODE_TYPES.TSAbstractPropertyDefinition: + case AST_NODE_TYPES.TSAbstractMethodDefinition: + case AST_NODE_TYPES.TSAbstractAccessorProperty: + return ['abstract'] + case AST_NODE_TYPES.PropertyDefinition: + case AST_NODE_TYPES.MethodDefinition: + case AST_NODE_TYPES.AccessorProperty: + return [] + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(node) + } +} +function computeAsyncModifier(node) { + return node.async ? ['async'] : [] +} +function computeStaticModifier(node) { + return node.static ? ['static'] : [] +} +function computeReadonlyModifier(node) { + return node.readonly ? ['readonly'] : [] +} +function computeOverrideModifier(node) { + return node.override ? ['override'] : [] +} +function computeOptionalModifier(node) { + return node.optional ? ['optional'] : [] +} +function computeDecoratedModifier(isDecorated) { + return isDecorated ? ['decorated'] : [] +} +export { + computeAbstractModifier, + computeAccessibilityModifier, + computeAsyncModifier, + computeDecoratedModifier, + computeOptionalModifier, + computeOverrideModifier, + computeReadonlyModifier, + computeStaticModifier, +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-accessor-details.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-accessor-details.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dcd6f2218fd3dd01ca69fd7bc2c0ec9ff7ddfbf3 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-accessor-details.d.ts @@ -0,0 +1,40 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +import { NodeNameDetails, Modifier, Selector } from '../types.js' +import { RegexOption } from '../../../types/common-options.js' +/** + * Computes details related to an accessor property. + * + * @param params - Parameters object. + * @param params.isDecorated - Whether the accessor is decorated. + * @param params.ignoreCallbackDependenciesPatterns - Patterns to ignore when + * computing dependencies. + * @param params.useExperimentalDependencyDetection - Whether to use + * experimental dependency detection. + * @param params.sourceCode - The source code object. + * @param params.className - The name of the class containing the accessor. + * @param params.accessor - The accessor node to compute information for. + * @returns An object containing various details about the accessor. + */ +export declare function computeAccessorDetails({ + ignoreCallbackDependenciesPatterns, + useExperimentalDependencyDetection, + isDecorated, + sourceCode, + className, + accessor, +}: { + accessor: TSESTree.TSAbstractAccessorProperty | TSESTree.AccessorProperty + ignoreCallbackDependenciesPatterns: RegexOption + useExperimentalDependencyDetection: boolean + sourceCode: TSESLint.SourceCode + className: undefined | string + isDecorated: boolean +}): { + nameDetails: NodeNameDetails + dependencyNames: string[] + dependencies: string[] + modifiers: Modifier[] + selectors: Selector[] + isStatic: boolean +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-accessor-details.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-accessor-details.js new file mode 100644 index 0000000000000000000000000000000000000000..1fe01c43def3b562efb7478dbf4270b81adac2b1 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-accessor-details.js @@ -0,0 +1,92 @@ +import { + computeAbstractModifier, + computeAccessibilityModifier, + computeDecoratedModifier, + computeOverrideModifier, + computeStaticModifier, +} from './common-modifiers.js' +import { computeDependencyName } from '../compute-dependency-name.js' +import { computeDependencies } from '../compute-dependencies.js' +import { computeMethodOrPropertyNameDetails } from './compute-method-or-property-name-details.js' +import { isFunctionExpression } from './is-function-expression.js' +/** + * Computes details related to an accessor property. + * + * @param params - Parameters object. + * @param params.isDecorated - Whether the accessor is decorated. + * @param params.ignoreCallbackDependenciesPatterns - Patterns to ignore when + * computing dependencies. + * @param params.useExperimentalDependencyDetection - Whether to use + * experimental dependency detection. + * @param params.sourceCode - The source code object. + * @param params.className - The name of the class containing the accessor. + * @param params.accessor - The accessor node to compute information for. + * @returns An object containing various details about the accessor. + */ +function computeAccessorDetails({ + ignoreCallbackDependenciesPatterns, + useExperimentalDependencyDetection, + isDecorated, + sourceCode, + className, + accessor, +}) { + let nameDetails = computeMethodOrPropertyNameDetails(accessor, sourceCode) + let modifiers = computeModifiers({ + hasPrivateHash: nameDetails.hasPrivateHash, + isDecorated, + accessor, + }) + return { + dependencyNames: [ + computeDependencyName({ + nodeNameWithoutStartingHash: nameDetails.nameWithoutStartingHash, + hasPrivateHash: nameDetails.hasPrivateHash, + isStatic: modifiers.includes('static'), + }), + ], + dependencies: computeAccessorDependencies({ + ignoreCallbackDependenciesPatterns, + useExperimentalDependencyDetection, + className, + accessor, + }), + selectors: ['accessor-property'], + isStatic: accessor.static, + nameDetails, + modifiers, + } +} +function computeAccessorDependencies({ + ignoreCallbackDependenciesPatterns, + useExperimentalDependencyDetection, + className, + accessor, +}) { + if (isFunctionExpression(accessor.value)) { + return [] + } + if (!accessor.value) { + return [] + } + return computeDependencies({ + ignoreCallbackDependenciesPatterns, + useExperimentalDependencyDetection, + isMemberStatic: accessor.static, + expression: accessor.value, + className, + }) +} +function computeModifiers({ hasPrivateHash, isDecorated, accessor }) { + return [ + ...computeStaticModifier(accessor), + ...computeAbstractModifier(accessor), + ...computeDecoratedModifier(isDecorated), + ...computeOverrideModifier(accessor), + ...computeAccessibilityModifier({ + hasPrivateHash, + node: accessor, + }), + ] +} +export { computeAccessorDetails } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-index-signature-details.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-index-signature-details.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4846cf307eac5abf265b96dc82bb6a5a4e3c7824 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-index-signature-details.d.ts @@ -0,0 +1,23 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +import { Modifier, Selector } from '../types.js' +/** + * Computes details related to an index-signature. + * + * @param params - Parameters object. + * @param params.indexSignature - The index signature node to compute + * information for. + * @param params.sourceCode - The source code object. + * @returns An object containing various details about the index-signature. + */ +export declare function computeIndexSignatureDetails({ + indexSignature, + sourceCode, +}: { + indexSignature: TSESTree.TSIndexSignature + sourceCode: TSESLint.SourceCode +}): { + modifiers: Modifier[] + selectors: Selector[] + name: string +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-index-signature-details.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-index-signature-details.js new file mode 100644 index 0000000000000000000000000000000000000000..771ceb878ca953726ea59a6c121524ea17f90ea8 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-index-signature-details.js @@ -0,0 +1,30 @@ +import { + computeReadonlyModifier, + computeStaticModifier, +} from './common-modifiers.js' +/** + * Computes details related to an index-signature. + * + * @param params - Parameters object. + * @param params.indexSignature - The index signature node to compute + * information for. + * @param params.sourceCode - The source code object. + * @returns An object containing various details about the index-signature. + */ +function computeIndexSignatureDetails({ indexSignature, sourceCode }) { + return { + name: sourceCode.text.slice( + indexSignature.range.at(0), + indexSignature.typeAnnotation?.range.at(0) ?? indexSignature.range.at(1), + ), + modifiers: computeModifiers(indexSignature), + selectors: ['index-signature'], + } +} +function computeModifiers(indexSignature) { + return [ + ...computeStaticModifier(indexSignature), + ...computeReadonlyModifier(indexSignature), + ] +} +export { computeIndexSignatureDetails } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-method-details.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-method-details.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd23fe558c65981ac7a66406925a5520c363ed8b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-method-details.d.ts @@ -0,0 +1,30 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +import { NodeNameDetails, Modifier, Selector } from '../types.js' +/** + * Computes details related to a method. + * + * @param params - Parameters object. + * @param params.isDecorated - Whether the accessor is decorated. + * @param params.method - The method node to compute information for. + * @param params.sourceCode - The source code object. + * @param params.hasParentDeclare - Whether the parent class is a declare class. + * @returns An object containing various details about the method. + */ +export declare function computeMethodDetails({ + hasParentDeclare, + isDecorated, + sourceCode, + method, +}: { + method: TSESTree.TSAbstractMethodDefinition | TSESTree.MethodDefinition + sourceCode: TSESLint.SourceCode + hasParentDeclare: boolean + isDecorated: boolean +}): { + addSafetySemicolonWhenInline: boolean + nameDetails: NodeNameDetails + modifiers: Modifier[] + selectors: Selector[] + isStatic: boolean +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-method-details.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-method-details.js new file mode 100644 index 0000000000000000000000000000000000000000..af38f82777c3e1eed0e5a2ca1bb46b21566cc169 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-method-details.js @@ -0,0 +1,88 @@ +import { UnreachableCaseError } from '../../../utils/unreachable-case-error.js' +import { + computeAbstractModifier, + computeAccessibilityModifier, + computeAsyncModifier, + computeDecoratedModifier, + computeOptionalModifier, + computeOverrideModifier, + computeStaticModifier, +} from './common-modifiers.js' +import { computeMethodOrPropertyNameDetails } from './compute-method-or-property-name-details.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes details related to a method. + * + * @param params - Parameters object. + * @param params.isDecorated - Whether the accessor is decorated. + * @param params.method - The method node to compute information for. + * @param params.sourceCode - The source code object. + * @param params.hasParentDeclare - Whether the parent class is a declare class. + * @returns An object containing various details about the method. + */ +function computeMethodDetails({ + hasParentDeclare, + isDecorated, + sourceCode, + method, +}) { + let nameDetails = computeMethodOrPropertyNameDetails(method, sourceCode) + return { + modifiers: computeModifiers({ + hasPrivateHash: nameDetails.hasPrivateHash, + isDecorated, + method, + }), + addSafetySemicolonWhenInline: shouldAddSafetySemicolonWhenInline({ + hasParentDeclare, + method, + }), + selectors: computeSelectors(method), + isStatic: method.static, + nameDetails, + } +} +function computeSelectors(method) { + return [...computeSetterOrConstructorSelector(), 'method'] + function computeSetterOrConstructorSelector() { + switch (method.kind) { + case 'constructor': + return ['constructor'] + case 'method': + return [] + case 'set': + return ['set-method'] + case 'get': + return ['get-method'] + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(method.kind) + } + } +} +function computeModifiers({ hasPrivateHash, isDecorated, method }) { + return [ + ...computeStaticModifier(method), + ...computeAbstractModifier(method), + ...computeDecoratedModifier(isDecorated), + ...computeOverrideModifier(method), + ...computeAccessibilityModifier({ + hasPrivateHash, + node: method, + }), + ...computeOptionalModifier(method), + ...computeAsyncModifier(method.value), + ] +} +function shouldAddSafetySemicolonWhenInline({ hasParentDeclare, method }) { + switch (method.type) { + case AST_NODE_TYPES.TSAbstractMethodDefinition: + return true + case AST_NODE_TYPES.MethodDefinition: + return hasParentDeclare + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(method) + } +} +export { computeMethodDetails } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-method-or-property-name-details.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-method-or-property-name-details.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7ada59d913f73935005f65efc7e3c10df41ebadc --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-method-or-property-name-details.d.ts @@ -0,0 +1,21 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +import { NodeNameDetails } from '../types.js' +/** + * Computes the name details of a method or property node. + * + * @param node - The method or property node to compute the name for. + * @param sourceCode - The ESLint source code object. + * @returns An object containing the name, whether it has a private hash, and + * the name without the starting hash. + */ +export declare function computeMethodOrPropertyNameDetails( + node: + | TSESTree.TSAbstractPropertyDefinition + | TSESTree.TSAbstractMethodDefinition + | TSESTree.TSAbstractAccessorProperty + | TSESTree.PropertyDefinition + | TSESTree.MethodDefinition + | TSESTree.AccessorProperty, + sourceCode: TSESLint.SourceCode, +): NodeNameDetails diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-method-or-property-name-details.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-method-or-property-name-details.js new file mode 100644 index 0000000000000000000000000000000000000000..599c80cd2539576c09b8f1ce4f672692d169c1db --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-method-or-property-name-details.js @@ -0,0 +1,25 @@ +import { computeIdentifierNameDetails } from '../compute-identifier-name-details.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the name details of a method or property node. + * + * @param node - The method or property node to compute the name for. + * @param sourceCode - The ESLint source code object. + * @returns An object containing the name, whether it has a private hash, and + * the name without the starting hash. + */ +function computeMethodOrPropertyNameDetails(node, sourceCode) { + switch (node.key.type) { + case AST_NODE_TYPES.PrivateIdentifier: + case AST_NODE_TYPES.Identifier: + case AST_NODE_TYPES.Literal: + return computeIdentifierNameDetails(node.key) + default: + return { + nameWithoutStartingHash: sourceCode.getText(node.key), + name: sourceCode.getText(node.key), + hasPrivateHash: false, + } + } +} +export { computeMethodOrPropertyNameDetails } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-property-details.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-property-details.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a42c5dd424328665d4400228f73626ace68dffb --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-property-details.d.ts @@ -0,0 +1,41 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +import { NodeNameDetails, Modifier, Selector } from '../types.js' +import { RegexOption } from '../../../types/common-options.js' +/** + * Computes details related to a property. + * + * @param params - Parameters object. + * @param params.isDecorated - Whether the accessor is decorated. + * @param params.property - The property node to compute information for. + * @param params.ignoreCallbackDependenciesPatterns - Patterns to ignore when + * computing dependencies. + * @param params.useExperimentalDependencyDetection - Whether to use + * experimental dependency detection. + * @param params.sourceCode - The source code object. + * @param params.className - The name of the class containing the property. + * @returns An object containing various details about the property. + */ +export declare function computePropertyDetails({ + ignoreCallbackDependenciesPatterns, + useExperimentalDependencyDetection, + isDecorated, + sourceCode, + className, + property, +}: { + property: TSESTree.TSAbstractPropertyDefinition | TSESTree.PropertyDefinition + ignoreCallbackDependenciesPatterns: RegexOption + useExperimentalDependencyDetection: boolean + sourceCode: TSESLint.SourceCode + className: undefined | string + isDecorated: boolean +}): { + memberValue: undefined | string + nameDetails: NodeNameDetails + dependencyNames: string[] + dependencies: string[] + modifiers: Modifier[] + selectors: Selector[] + isStatic: boolean +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-property-details.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-property-details.js new file mode 100644 index 0000000000000000000000000000000000000000..405e1f080b7eaec184aad8861e442bdc75b82550 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-property-details.js @@ -0,0 +1,118 @@ +import { + computeAbstractModifier, + computeAccessibilityModifier, + computeAsyncModifier, + computeDecoratedModifier, + computeOptionalModifier, + computeOverrideModifier, + computeReadonlyModifier, + computeStaticModifier, +} from './common-modifiers.js' +import { computeDependencyName } from '../compute-dependency-name.js' +import { computeDependencies } from '../compute-dependencies.js' +import { computeMethodOrPropertyNameDetails } from './compute-method-or-property-name-details.js' +import { isFunctionExpression } from './is-function-expression.js' +/** + * Computes details related to a property. + * + * @param params - Parameters object. + * @param params.isDecorated - Whether the accessor is decorated. + * @param params.property - The property node to compute information for. + * @param params.ignoreCallbackDependenciesPatterns - Patterns to ignore when + * computing dependencies. + * @param params.useExperimentalDependencyDetection - Whether to use + * experimental dependency detection. + * @param params.sourceCode - The source code object. + * @param params.className - The name of the class containing the property. + * @returns An object containing various details about the property. + */ +function computePropertyDetails({ + ignoreCallbackDependenciesPatterns, + useExperimentalDependencyDetection, + isDecorated, + sourceCode, + className, + property, +}) { + let nameDetails = computeMethodOrPropertyNameDetails(property, sourceCode) + let modifiers = computeModifiers({ + hasPrivateHash: nameDetails.hasPrivateHash, + isDecorated, + property, + }) + return { + dependencyNames: [ + computeDependencyName({ + nodeNameWithoutStartingHash: nameDetails.nameWithoutStartingHash, + hasPrivateHash: nameDetails.hasPrivateHash, + isStatic: modifiers.includes('static'), + }), + ], + dependencies: computePropertyDependencies({ + ignoreCallbackDependenciesPatterns, + useExperimentalDependencyDetection, + className, + property, + }), + memberValue: + !isFunctionExpression(property.value) && property.value ? + sourceCode.getText(property.value) + : void 0, + selectors: computeSelectors(property), + isStatic: property.static, + nameDetails, + modifiers, + } +} +function computeModifiers({ hasPrivateHash, isDecorated, property }) { + return [ + ...computeStaticModifier(property), + ...computeDeclareModifier(), + ...computeAbstractModifier(property), + ...computeDecoratedModifier(isDecorated), + ...computeOverrideModifier(property), + ...computeReadonlyModifier(property), + ...computeAccessibilityModifier({ + hasPrivateHash, + node: property, + }), + ...computeOptionalModifier(property), + ...computeAsyncModifierIfFunctionProperty(), + ] + function computeDeclareModifier() { + return property.declare ? ['declare'] : [] + } + function computeAsyncModifierIfFunctionProperty() { + if (!isFunctionExpression(property.value)) { + return [] + } + return computeAsyncModifier(property.value) + } +} +function computePropertyDependencies({ + ignoreCallbackDependenciesPatterns, + useExperimentalDependencyDetection, + className, + property, +}) { + if (isFunctionExpression(property.value)) { + return [] + } + if (!property.value) { + return [] + } + return computeDependencies({ + ignoreCallbackDependenciesPatterns, + useExperimentalDependencyDetection, + isMemberStatic: property.static, + expression: property.value, + className, + }) +} +function computeSelectors(property) { + return [...computeFunctionPropertySelector(), 'property'] + function computeFunctionPropertySelector() { + return isFunctionExpression(property.value) ? ['function-property'] : [] + } +} +export { computePropertyDetails } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-static-block-details.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-static-block-details.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..51f192ae4910df73faac39abe752c8493db602d3 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-static-block-details.d.ts @@ -0,0 +1,30 @@ +import { TSESTree } from '@typescript-eslint/types' +import { RegexOption } from '../../../types/common-options.js' +import { Modifier, Selector } from '../types.js' +/** + * Computes details related to a static block. + * + * @param params - Parameters object. + * @param params.staticBlock - The static block node to compute information for. + * @param params.ignoreCallbackDependenciesPatterns - Patterns to ignore when + * computing dependencies. + * @param params.useExperimentalDependencyDetection - Whether to use + * experimental dependency detection. + * @param params.className - The name of the class containing the property. + * @returns An object containing various details about the static block. + */ +export declare function computeStaticBlockDetails({ + ignoreCallbackDependenciesPatterns, + useExperimentalDependencyDetection, + staticBlock, + className, +}: { + ignoreCallbackDependenciesPatterns: RegexOption + useExperimentalDependencyDetection: boolean + staticBlock: TSESTree.StaticBlock + className: undefined | string +}): { + dependencies: string[] + selectors: Selector[] + modifiers: Modifier[] +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-static-block-details.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-static-block-details.js new file mode 100644 index 0000000000000000000000000000000000000000..a4aea38d74b789a2258c15cce21e9273a9a62d49 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/compute-static-block-details.js @@ -0,0 +1,32 @@ +import { computeDependencies } from '../compute-dependencies.js' +/** + * Computes details related to a static block. + * + * @param params - Parameters object. + * @param params.staticBlock - The static block node to compute information for. + * @param params.ignoreCallbackDependenciesPatterns - Patterns to ignore when + * computing dependencies. + * @param params.useExperimentalDependencyDetection - Whether to use + * experimental dependency detection. + * @param params.className - The name of the class containing the property. + * @returns An object containing various details about the static block. + */ +function computeStaticBlockDetails({ + ignoreCallbackDependenciesPatterns, + useExperimentalDependencyDetection, + staticBlock, + className, +}) { + return { + dependencies: computeDependencies({ + ignoreCallbackDependenciesPatterns, + useExperimentalDependencyDetection, + expression: staticBlock, + isMemberStatic: true, + className, + }), + selectors: ['static-block'], + modifiers: [], + } +} +export { computeStaticBlockDetails } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/is-function-expression.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/is-function-expression.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..42a141ce43d87861efcf496393dea826253756f0 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/is-function-expression.d.ts @@ -0,0 +1,11 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Checks whether a node is a function expression or an arrow function + * expression. + * + * @param node - The AST node to check. + * @returns Whether the node is a function expression. + */ +export declare function isFunctionExpression( + node: TSESTree.Node | null, +): node is TSESTree.ArrowFunctionExpression | TSESTree.FunctionExpression diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/is-function-expression.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/is-function-expression.js new file mode 100644 index 0000000000000000000000000000000000000000..c8eb4f405e2f166bc9fb0d809935b65d5f8ce20d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/node-info/is-function-expression.js @@ -0,0 +1,18 @@ +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Checks whether a node is a function expression or an arrow function + * expression. + * + * @param node - The AST node to check. + * @returns Whether the node is a function expression. + */ +function isFunctionExpression(node) { + if (!node) { + return false + } + return ( + node.type === AST_NODE_TYPES.ArrowFunctionExpression || + node.type === AST_NODE_TYPES.FunctionExpression + ) +} +export { isFunctionExpression } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/sort-class.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/sort-class.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a27b226e92280084fb7655296aed737f35e70166 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/sort-class.d.ts @@ -0,0 +1,13 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +import { MessageId, Options } from './types.js' +export declare let defaultOptions: Required +export declare function sortClass({ + matchedAstSelectors, + context, + node, +}: { + context: Readonly> + matchedAstSelectors: ReadonlySet + node: TSESTree.ClassBody +}): void diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/sort-class.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/sort-class.js new file mode 100644 index 0000000000000000000000000000000000000000..ab75d2090785fcb65178f52b632290d04b6b3d77 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/sort-class.js @@ -0,0 +1,333 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { getGroupIndex } from '../../utils/get-group-index.js' +import { populateSortingNodeGroupsWithDependencies } from '../../utils/populate-sorting-node-groups-with-dependencies.js' +import { defaultComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +import { validateNewlinesAndPartitionConfig } from '../../utils/validate-newlines-and-partition-config.js' +import { buildOptionsByGroupIndexComputer } from '../../utils/build-options-by-group-index-computer.js' +import { validateCustomSortConfig } from '../../utils/validate-custom-sort-config.js' +import { generatePredefinedGroups } from '../../utils/generate-predefined-groups.js' +import { sortNodesByDependencies } from '../../utils/sort-nodes-by-dependencies.js' +import { getEslintDisabledLines } from '../../utils/get-eslint-disabled-lines.js' +import { doesCustomGroupMatch } from '../../utils/does-custom-group-match.js' +import { isNodeEslintDisabled } from '../../utils/is-node-eslint-disabled.js' +import { validateGroupsConfig } from '../../utils/validate-groups-config.js' +import { sortNodesByGroups } from '../../utils/sort-nodes-by-groups.js' +import { reportAllErrors } from '../../utils/report-all-errors.js' +import { shouldPartition } from '../../utils/should-partition.js' +import { computeGroup } from '../../utils/compute-group.js' +import { rangeToDiff } from '../../utils/range-to-diff.js' +import { getSettings } from '../../utils/get-settings.js' +import { isSortable } from '../../utils/is-sortable.js' +import { complete } from '../../utils/complete.js' +import { getNodeDecorators } from '../../utils/get-node-decorators.js' +import { getDecoratorName } from '../../utils/get-decorator-name.js' +import { + DEPENDENCY_ORDER_ERROR_ID, + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + allModifiers, + allSelectors, +} from './types.js' +import { buildOverloadSignatureNewlinesBetweenValueGetter } from '../../utils/overload-signature/build-overload-signature-newlines-between-value-getter.js' +import { populateSortingNodeGroupsWithOverloadSignature } from '../../utils/overload-signature/populate-sorting-node-groups-with-overload-signature.js' +import { computeIndexSignatureDetails } from './node-info/compute-index-signature-details.js' +import { computeDependenciesBySortingNode } from './compute-dependencies-by-sorting-node.js' +import { computeStaticBlockDetails } from './node-info/compute-static-block-details.js' +import { computeOverloadSignatureGroups } from './compute-overload-signature-groups.js' +import { computeMatchedContextOptions } from './compute-matched-context-options.js' +import { computePropertyDetails } from './node-info/compute-property-details.js' +import { computeAccessorDetails } from './node-info/compute-accessor-details.js' +import { computeMethodDetails } from './node-info/compute-method-details.js' +import { isKnownClassElement } from './is-known-class-element.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Cache computed groups by modifiers and selectors for performance. + */ +var cachedGroupsByModifiersAndSelectors = /* @__PURE__ */ new Map() +var defaultOptions = { + groups: [ + 'index-signature', + ['static-property', 'static-accessor-property'], + ['static-get-method', 'static-set-method'], + ['protected-static-property', 'protected-static-accessor-property'], + ['protected-static-get-method', 'protected-static-set-method'], + ['private-static-property', 'private-static-accessor-property'], + ['private-static-get-method', 'private-static-set-method'], + 'static-block', + ['property', 'accessor-property'], + ['get-method', 'set-method'], + ['protected-property', 'protected-accessor-property'], + ['protected-get-method', 'protected-set-method'], + ['private-property', 'private-accessor-property'], + ['private-get-method', 'private-set-method'], + 'constructor', + ['static-method', 'static-function-property'], + ['protected-static-method', 'protected-static-function-property'], + ['private-static-method', 'private-static-function-property'], + ['method', 'function-property'], + ['protected-method', 'protected-function-property'], + ['private-method', 'private-function-property'], + 'unknown', + ], + useExperimentalDependencyDetection: true, + ignoreCallbackDependenciesPatterns: [], + newlinesBetweenOverloadSignatures: 0, + fallbackSort: { type: 'unsorted' }, + newlinesInside: 'newlinesBetween', + partitionByComment: false, + partitionByNewLine: false, + newlinesBetween: 'ignore', + specialCharacters: 'keep', + useConfigurationIf: {}, + type: 'alphabetical', + ignoreCase: true, + customGroups: [], + locales: 'en-US', + alphabet: '', + order: 'asc', +} +function sortClass({ matchedAstSelectors, context, node }) { + let classElements = node.body.filter(isKnownClassElement) + if (!isSortable(classElements)) { + return + } + let settings = getSettings(context.settings) + let matchedContextOptions = computeMatchedContextOptions({ + matchedAstSelectors, + classElements, + context, + }) + let options = complete(matchedContextOptions, settings, defaultOptions) + validateCustomSortConfig(options) + validateGroupsConfig({ + modifiers: allModifiers, + selectors: allSelectors, + options, + }) + validateNewlinesAndPartitionConfig(options) + let { sourceCode, id } = context + let eslintDisabledLines = getEslintDisabledLines({ + ruleName: id, + sourceCode, + }) + let optionsByGroupIndexComputer = buildOptionsByGroupIndexComputer(options) + let overloadSignatureNewlinesBetweenValueGetter = + buildOverloadSignatureNewlinesBetweenValueGetter( + options.newlinesBetweenOverloadSignatures, + ) + let className = node.parent.id?.name + let sortingNodeGroupsWithoutOverloadSignature = classElements.reduce( + (accumulator, member) => { + let dependencies = [] + let isDecorated = false + let decoratorNames = [] + if ('decorators' in member) { + decoratorNames = getNodeDecorators(member).map(decorator => + getDecoratorName({ + sourceCode, + decorator, + }), + ) + isDecorated = decoratorNames.length > 0 + } + let addSafetySemicolonWhenInline + let dependencyNames + let name + let nameDetails + let memberValue + let isStatic + let modifiers + let selectors + switch (member.type) { + case AST_NODE_TYPES.TSAbstractPropertyDefinition: + case AST_NODE_TYPES.PropertyDefinition: + addSafetySemicolonWhenInline = true + ;({ + dependencyNames, + dependencies, + memberValue, + nameDetails, + modifiers, + selectors, + isStatic, + } = computePropertyDetails({ + ignoreCallbackDependenciesPatterns: + options.ignoreCallbackDependenciesPatterns, + useExperimentalDependencyDetection: + options.useExperimentalDependencyDetection, + property: member, + isDecorated, + sourceCode, + className, + })) + ;({ name } = nameDetails) + break + case AST_NODE_TYPES.TSAbstractMethodDefinition: + case AST_NODE_TYPES.MethodDefinition: + dependencyNames = [] + ;({ + addSafetySemicolonWhenInline, + nameDetails, + selectors, + modifiers, + isStatic, + } = computeMethodDetails({ + hasParentDeclare: node.parent.declare, + method: member, + isDecorated, + sourceCode, + })) + ;({ name } = nameDetails) + break + case AST_NODE_TYPES.TSAbstractAccessorProperty: + case AST_NODE_TYPES.AccessorProperty: + addSafetySemicolonWhenInline = true + ;({ + dependencyNames, + dependencies, + nameDetails, + modifiers, + selectors, + isStatic, + } = computeAccessorDetails({ + ignoreCallbackDependenciesPatterns: + options.ignoreCallbackDependenciesPatterns, + useExperimentalDependencyDetection: + options.useExperimentalDependencyDetection, + accessor: member, + isDecorated, + sourceCode, + className, + })) + ;({ name } = nameDetails) + break + case AST_NODE_TYPES.TSIndexSignature: + addSafetySemicolonWhenInline = true + dependencyNames = [] + nameDetails = null + isStatic = false + ;({ modifiers, selectors, name } = computeIndexSignatureDetails({ + indexSignature: member, + sourceCode, + })) + break + case AST_NODE_TYPES.StaticBlock: + addSafetySemicolonWhenInline = false + dependencyNames = [] + name = 'static' + nameDetails = null + isStatic = true + ;({ dependencies, selectors, modifiers } = computeStaticBlockDetails({ + useExperimentalDependencyDetection: + options.useExperimentalDependencyDetection, + ignoreCallbackDependenciesPatterns: + options.ignoreCallbackDependenciesPatterns, + staticBlock: member, + className, + })) + break + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(member) + } + let predefinedGroups = generatePredefinedGroups({ + cache: cachedGroupsByModifiersAndSelectors, + selectors, + modifiers, + }) + let group = computeGroup({ + customGroupMatcher: customGroup => + doesCustomGroupMatch({ + elementValue: memberValue, + elementName: name, + decoratorNames, + customGroup, + modifiers, + selectors, + }), + predefinedGroups, + options, + }) + let sortingNode = { + isEslintDisabled: isNodeEslintDisabled(member, eslintDisabledLines), + size: rangeToDiff(member, sourceCode), + addSafetySemicolonWhenInline, + dependencyNames, + node: member, + dependencies, + nameDetails, + isStatic, + group, + name, + } + let lastSortingNode = accumulator.at(-1)?.at(-1) + if ( + shouldPartition({ + lastSortingNode, + sortingNode, + sourceCode, + options, + }) + ) { + accumulator.push([]) + } + accumulator.at(-1).push({ + ...sortingNode, + partitionId: accumulator.length, + }) + return accumulator + }, + [[]], + ) + let sortingNodeGroups = populateSortingNodeGroupsWithOverloadSignature({ + overloadSignatureGroups: computeOverloadSignatureGroups(classElements), + sortingNodeGroups: sortingNodeGroupsWithoutOverloadSignature, + }) + if (options.useExperimentalDependencyDetection) { + let dependenciesBySortingNode = computeDependenciesBySortingNode({ + ignoreCallbackDependenciesPatterns: + options.ignoreCallbackDependenciesPatterns, + sortingNodes: sortingNodeGroups.flat(), + classBody: node, + sourceCode, + }) + sortingNodeGroups = populateSortingNodeGroupsWithDependencies({ + dependenciesBySortingNode, + sortingNodeGroups, + }) + } + let sortingNodes = sortingNodeGroups.flat() + reportAllErrors({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + unexpectedDependencyOrder: DEPENDENCY_ORDER_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + newlinesBetweenValueGetter: overloadSignatureNewlinesBetweenValueGetter, + sortNodesExcludingEslintDisabled, + nodes: sortingNodes, + options, + context, + }) + function sortNodesExcludingEslintDisabled(ignoreEslintDisabledNodes) { + let nodesSortedByGroups = sortingNodeGroups.flatMap(sortingNodeGroup => + sortNodesByGroups({ + isNodeIgnored: sortingNode => + getGroupIndex(options.groups, sortingNode) === options.groups.length, + comparatorByOptionsComputer: defaultComparatorByOptionsComputer, + optionsByGroupIndexComputer, + ignoreEslintDisabledNodes, + nodes: sortingNodeGroup, + groups: options.groups, + }), + ) + return sortNodesByDependencies(nodesSortedByGroups, { + ignoreEslintDisabledNodes, + }) + } +} +export { defaultOptions, sortClass } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c4014168a339b61deabfbc5c9c03787ac6ef05d7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/types.d.ts @@ -0,0 +1,153 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +import { TSESTree } from '@typescript-eslint/types' +import { SortingNodeWithDependencies } from '../../utils/sort-nodes-by-dependencies.js' +import { NewlinesBetweenOption } from '../../types/common-groups-options.js' +import { RegexOption, TypeOption } from '../../types/common-options.js' +import { AllCommonOptions } from '../../types/all-common-options.js' +export type MessageId = + | typeof DEPENDENCY_ORDER_ERROR_ID + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +export declare const ORDER_ERROR_ID = 'unexpectedClassesOrder' +export declare const GROUP_ORDER_ERROR_ID = 'unexpectedClassesGroupOrder' +export declare const EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenClassMembers' +export declare const MISSED_SPACING_ERROR_ID = + 'missedSpacingBetweenClassMembers' +export declare const DEPENDENCY_ORDER_ERROR_ID = + 'unexpectedClassesDependencyOrder' +/** + * Configuration options for the sort-classes rule. + * + * This rule enforces consistent ordering of class members (properties, methods, + * constructors, etc.) to improve code readability and maintainability. + */ +export type Options = Partial< + { + /** + * Conditional configuration based on pattern matching. + */ + useConfigurationIf: { + /** + * Regular expression pattern to match against all class element names. + */ + allNamesMatchPattern?: RegexOption + /** + * AST selector to match against ClassBody nodes. + */ + matchesAstSelector?: string + } + /** + * Determines how many newlines should be placed between overload signatures + * of the same method. + */ + newlinesBetweenOverloadSignatures: NewlinesBetweenOption + /** + * Regex patterns for function names whose callback argument dependencies + * are ignored during class-member sorting. Dependencies inside these + * callbacks won't influence the ordering. + */ + ignoreCallbackDependenciesPatterns: RegexOption + /** + * Enables experimental dependency detection. + */ + useExperimentalDependencyDetection: boolean + } & AllCommonOptions< + TypeOption, + AdditionalSortOptions, + CustomGroupMatchOptions + > +>[] +export interface SortClassesSortingNode extends SortingNodeWithDependencies { + overloadSignatureImplementation: + TSESTree.TSAbstractMethodDefinition | TSESTree.MethodDefinition | null + nameDetails: NodeNameDetails | null + isStatic: boolean +} +export interface NodeNameDetails { + nameWithoutStartingHash: string + hasPrivateHash: boolean + name: string +} +/** + * Union type of all available class member selectors. Used to identify and + * categorize different types of class members. + */ +export type Selector = (typeof allSelectors)[number] +/** + * Union type of all available class member modifiers. Includes access + * modifiers, async, static, abstract, and other TypeScript modifiers. + */ +export type Modifier = (typeof allModifiers)[number] +/** + * Defines a custom group configuration for class members. + * + * Allows categorizing class members based on their selector type (method, + * property, etc.) and various patterns matching their names, values, or + * decorators. + */ +interface CustomGroupMatchOptions { + /** + * Pattern to match decorator names (e.g., '@Component'). + */ + decoratorNamePattern?: RegexOption + /** + * Pattern to match the value of the member (for properties with + * initializers). + */ + elementValuePattern?: RegexOption + /** + * List of modifiers that members must have to be included in this group. + */ + modifiers?: Modifier[] + /** + * The type of class member this group applies to. + */ + selector?: Selector +} +type AdditionalSortOptions = object +/** + * Complete list of available class member selectors. Used for validation and + * JSON schema generation. + */ +export declare let allSelectors: readonly [ + 'accessor-property', + 'index-signature', + 'constructor', + 'static-block', + 'get-method', + 'set-method', + 'function-property', + 'property', + 'method', +] +/** + * Complete list of available class member modifiers. Used for validation and + * JSON schema generation. + */ +export declare let allModifiers: readonly [ + 'async', + 'protected', + 'private', + 'public', + 'static', + 'abstract', + 'override', + 'readonly', + 'decorated', + 'declare', + 'optional', +] +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + * + * Note: Ideally, we should generate as many schemas as there are selectors, and + * ensure that users do not enter invalid modifiers for a given selector. + */ +export declare let additionalCustomGroupMatchOptionsJsonSchema: Record< + string, + JSONSchema4 +> +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/types.js new file mode 100644 index 0000000000000000000000000000000000000000..48b9f50b35980f883f3f18f240f104c7de16da81 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-classes/types.js @@ -0,0 +1,65 @@ +import { buildRegexJsonSchema } from '../../utils/json-schemas/common-json-schemas.js' +import { + buildCustomGroupModifiersJsonSchema, + buildCustomGroupSelectorJsonSchema, +} from '../../utils/json-schemas/common-groups-json-schemas.js' +var ORDER_ERROR_ID = 'unexpectedClassesOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedClassesGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenClassMembers' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenClassMembers' +var DEPENDENCY_ORDER_ERROR_ID = 'unexpectedClassesDependencyOrder' +/** + * Complete list of available class member selectors. Used for validation and + * JSON schema generation. + */ +var allSelectors = [ + 'accessor-property', + 'index-signature', + 'constructor', + 'static-block', + 'get-method', + 'set-method', + 'function-property', + 'property', + 'method', +] +/** + * Complete list of available class member modifiers. Used for validation and + * JSON schema generation. + */ +var allModifiers = [ + 'async', + 'protected', + 'private', + 'public', + 'static', + 'abstract', + 'override', + 'readonly', + 'decorated', + 'declare', + 'optional', +] +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + * + * Note: Ideally, we should generate as many schemas as there are selectors, and + * ensure that users do not enter invalid modifiers for a given selector. + */ +var additionalCustomGroupMatchOptionsJsonSchema = { + modifiers: buildCustomGroupModifiersJsonSchema(allModifiers), + selector: buildCustomGroupSelectorJsonSchema(allSelectors), + decoratorNamePattern: buildRegexJsonSchema(), + elementValuePattern: buildRegexJsonSchema(), +} +export { + DEPENDENCY_ORDER_ERROR_ID, + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + additionalCustomGroupMatchOptionsJsonSchema, + allModifiers, + allSelectors, +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-decorators.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-decorators.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7053c46cf23a5e6d534c4657637c1c0021ff014d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-decorators.d.ts @@ -0,0 +1,21 @@ +import { Options } from './sort-decorators/types.js' +declare const ORDER_ERROR_ID = 'unexpectedDecoratorsOrder' +declare const GROUP_ORDER_ERROR_ID = 'unexpectedDecoratorsGroupOrder' +declare const EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenDecorators' +declare const MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenDecorators' +type MessageId = + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +declare const _default: import('@typescript-eslint/utils/ts-eslint').RuleModule< + MessageId, + Options, + { + recommended?: boolean + }, + import('@typescript-eslint/utils/ts-eslint').RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-decorators.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-decorators.js new file mode 100644 index 0000000000000000000000000000000000000000..dfcd8e5d3953ce6e1e65320c030f371ee6029ce3 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-decorators.js @@ -0,0 +1,261 @@ +import { buildCommonJsonSchemas } from '../utils/json-schemas/common-json-schemas.js' +import { buildCommonGroupsJsonSchemas } from '../utils/json-schemas/common-groups-json-schemas.js' +import { + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { + partitionByCommentJsonSchema, + partitionByNewlineJsonSchema, +} from '../utils/json-schemas/common-partition-json-schemas.js' +import { defaultComparatorByOptionsComputer } from '../utils/compare/default-comparator-by-options-computer.js' +import { validateNewlinesAndPartitionConfig } from '../utils/validate-newlines-and-partition-config.js' +import { buildOptionsByGroupIndexComputer } from '../utils/build-options-by-group-index-computer.js' +import { validateCustomSortConfig } from '../utils/validate-custom-sort-config.js' +import { getEslintDisabledLines } from '../utils/get-eslint-disabled-lines.js' +import { doesCustomGroupMatch } from '../utils/does-custom-group-match.js' +import { isNodeEslintDisabled } from '../utils/is-node-eslint-disabled.js' +import { validateGroupsConfig } from '../utils/validate-groups-config.js' +import { sortNodesByGroups } from '../utils/sort-nodes-by-groups.js' +import { reportAllErrors } from '../utils/report-all-errors.js' +import { shouldPartition } from '../utils/should-partition.js' +import { computeGroup } from '../utils/compute-group.js' +import { rangeToDiff } from '../utils/range-to-diff.js' +import { getSettings } from '../utils/get-settings.js' +import { isSortable } from '../utils/is-sortable.js' +import { complete } from '../utils/complete.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { getNodeDecorators } from '../utils/get-node-decorators.js' +import { getDecoratorName } from '../utils/get-decorator-name.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var ORDER_ERROR_ID = 'unexpectedDecoratorsOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedDecoratorsGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenDecorators' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenDecorators' +var defaultOptions = { + fallbackSort: { type: 'unsorted' }, + newlinesInside: 'newlinesBetween', + specialCharacters: 'keep', + partitionByComment: false, + partitionByNewLine: false, + newlinesBetween: 'ignore', + sortOnProperties: true, + sortOnParameters: true, + sortOnAccessors: true, + type: 'alphabetical', + sortOnClasses: true, + sortOnMethods: true, + ignoreCase: true, + customGroups: [], + locales: 'en-US', + alphabet: '', + order: 'asc', + groups: [], +} +var sort_decorators_default = createEslintRule({ + meta: { + schema: { + items: { + properties: { + ...buildCommonJsonSchemas(), + ...buildCommonGroupsJsonSchemas(), + sortOnParameters: { + description: + 'Controls whether sorting should be enabled for method parameter decorators.', + type: 'boolean', + }, + sortOnProperties: { + description: + 'Controls whether sorting should be enabled for class property decorators.', + type: 'boolean', + }, + sortOnAccessors: { + description: + 'Controls whether sorting should be enabled for class accessor decorators.', + type: 'boolean', + }, + sortOnMethods: { + description: + 'Controls whether sorting should be enabled for class method decorators.', + type: 'boolean', + }, + sortOnClasses: { + description: + 'Controls whether sorting should be enabled for class decorators.', + type: 'boolean', + }, + partitionByComment: partitionByCommentJsonSchema, + partitionByNewLine: partitionByNewlineJsonSchema, + }, + additionalProperties: false, + type: 'object', + }, + uniqueItems: true, + type: 'array', + }, + messages: { + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-decorators', + description: 'Enforce sorted decorators.', + recommended: true, + }, + type: 'suggestion', + fixable: 'code', + }, + create: context => { + let settings = getSettings(context.settings) + let options = complete(context.options.at(0), settings, defaultOptions) + validateCustomSortConfig(options) + validateGroupsConfig({ + modifiers: [], + selectors: [], + options, + }) + validateNewlinesAndPartitionConfig(options) + return { + Decorator: decorator => { + if (!options.sortOnParameters) { + return + } + if ( + 'decorators' in decorator.parent && + decorator.parent.type === AST_NODE_TYPES.Identifier && + decorator.parent.parent.type === AST_NODE_TYPES.FunctionExpression + ) { + let { decorators } = decorator.parent + if (decorator !== decorators[0]) { + return + } + sortDecorators(context, options, decorators) + } + }, + PropertyDefinition: propertyDefinition => { + if (options.sortOnProperties) { + sortDecorators( + context, + options, + getNodeDecorators(propertyDefinition), + ) + } + }, + AccessorProperty: accessorDefinition => { + if (options.sortOnAccessors) { + sortDecorators( + context, + options, + getNodeDecorators(accessorDefinition), + ) + } + }, + MethodDefinition: methodDefinition => { + if (options.sortOnMethods) { + sortDecorators(context, options, getNodeDecorators(methodDefinition)) + } + }, + ClassDeclaration: declaration => { + if (options.sortOnClasses) { + sortDecorators(context, options, getNodeDecorators(declaration)) + } + }, + } + }, + defaultOptions: [defaultOptions], + name: 'sort-decorators', +}) +/** + * Sorts decorators attached to a class, method, or property. + * + * Processes the decorators, groups them according to options, and reports any + * ordering errors found. Handles partitioning by comments and newlines. + * + * @param context - The ESLint rule context. + * @param options - The sorting options for decorators. + * @param decorators - Array of decorator nodes to sort. + */ +function sortDecorators(context, options, decorators) { + if (!isSortable(decorators)) { + return + } + let { sourceCode, id } = context + let eslintDisabledLines = getEslintDisabledLines({ + ruleName: id, + sourceCode, + }) + let optionsByGroupIndexComputer = buildOptionsByGroupIndexComputer(options) + let formattedMembers = decorators.reduce( + (accumulator, decorator) => { + let name = getDecoratorName({ + sourceCode, + decorator, + }) + let group = computeGroup({ + customGroupMatcher: customGroup => + doesCustomGroupMatch({ + elementName: name, + selectors: [], + modifiers: [], + customGroup, + }), + predefinedGroups: [], + options, + }) + let sortingNode = { + isEslintDisabled: isNodeEslintDisabled(decorator, eslintDisabledLines), + size: rangeToDiff(decorator, sourceCode), + node: decorator, + group, + name, + } + let lastSortingNode = accumulator.at(-1)?.at(-1) + if ( + shouldPartition({ + lastSortingNode, + sortingNode, + sourceCode, + options, + }) + ) { + accumulator.push([]) + } + accumulator.at(-1).push({ + ...sortingNode, + partitionId: accumulator.length, + }) + return accumulator + }, + [[]], + ) + function sortNodesExcludingEslintDisabled(ignoreEslintDisabledNodes) { + return formattedMembers.flatMap(nodes => + sortNodesByGroups({ + comparatorByOptionsComputer: defaultComparatorByOptionsComputer, + optionsByGroupIndexComputer, + ignoreEslintDisabledNodes, + groups: options.groups, + nodes, + }), + ) + } + let nodes = formattedMembers.flat() + reportAllErrors({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + ignoreFirstNodeHighestBlockComment: true, + sortNodesExcludingEslintDisabled, + options, + context, + nodes, + }) +} +export { sort_decorators_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-decorators/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-decorators/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e543645dbd880a369fbc5a8c5ea1dbd810c90fe --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-decorators/types.d.ts @@ -0,0 +1,24 @@ +import { TSESTree } from '@typescript-eslint/types' +import { AllCommonOptions } from '../../types/all-common-options.js' +import { TypeOption } from '../../types/common-options.js' +import { SortingNode } from '../../types/sorting-node.js' +export type Options = Partial< + { + sortOnParameters: boolean + sortOnProperties: boolean + sortOnAccessors: boolean + sortOnMethods: boolean + sortOnClasses: boolean + } & AllCommonOptions< + TypeOption, + AdditionalSortOptions, + CustomGroupMatchOptions + > +>[] +export type SortDecoratorsSortingNode = SortingNode +/** + * Match options for a custom group. + */ +type CustomGroupMatchOptions = object +type AdditionalSortOptions = object +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e22fd62ed845dd6fed80a4bce67728f948ffc23 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums.d.ts @@ -0,0 +1,12 @@ +import { MessageId, Options } from './sort-enums/types.js' +declare const _default: import('@typescript-eslint/utils/ts-eslint').RuleModule< + MessageId, + Options, + { + recommended?: boolean + }, + import('@typescript-eslint/utils/ts-eslint').RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums.js new file mode 100644 index 0000000000000000000000000000000000000000..17bdf9993800d988182921cacc2d9305c309f0ea --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums.js @@ -0,0 +1,86 @@ +import { + buildCommonJsonSchemas, + buildUseConfigIfJsonSchema, + matchesAstSelectorJsonSchema, + useExperimentalDependencyDetectionJsonSchema, +} from '../utils/json-schemas/common-json-schemas.js' +import { buildCommonGroupsJsonSchemas } from '../utils/json-schemas/common-groups-json-schemas.js' +import { + DEPENDENCY_ORDER_ERROR, + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { + partitionByCommentJsonSchema, + partitionByNewlineJsonSchema, +} from '../utils/json-schemas/common-partition-json-schemas.js' +import { buildAstListeners } from '../utils/build-ast-listeners.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { + DEPENDENCY_ORDER_ERROR_ID, + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + additionalCustomGroupMatchOptionsJsonSchema, +} from './sort-enums/types.js' +import { defaultOptions, sortEnum } from './sort-enums/sort-enum.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var sort_enums_default = createEslintRule({ + meta: { + schema: { + items: { + properties: { + ...buildCommonJsonSchemas(), + ...buildCommonGroupsJsonSchemas({ + additionalCustomGroupMatchProperties: + additionalCustomGroupMatchOptionsJsonSchema, + }), + sortByValue: { + description: 'Specifies whether to sort enums by value.', + enum: ['always', 'ifNumericEnum', 'never'], + type: 'string', + }, + useConfigurationIf: buildUseConfigIfJsonSchema({ + additionalProperties: { + matchesAstSelector: matchesAstSelectorJsonSchema, + }, + }), + useExperimentalDependencyDetection: + useExperimentalDependencyDetectionJsonSchema, + partitionByComment: partitionByCommentJsonSchema, + partitionByNewLine: partitionByNewlineJsonSchema, + }, + additionalProperties: false, + type: 'object', + }, + uniqueItems: true, + type: 'array', + }, + messages: { + [DEPENDENCY_ORDER_ERROR_ID]: DEPENDENCY_ORDER_ERROR, + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-enums', + description: 'Enforce sorted TypeScript enums.', + recommended: true, + }, + type: 'suggestion', + fixable: 'code', + }, + create: context => + buildAstListeners({ + nodeTypes: [AST_NODE_TYPES.TSEnumDeclaration], + sorter: sortEnum, + context, + }), + defaultOptions: [defaultOptions], + name: 'sort-enums', +}) +export { sort_enums_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/build-comparator-by-options-computer.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/build-comparator-by-options-computer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..45ed58fddb928b69217ee2eaf96b34dea11bc9bd --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/build-comparator-by-options-computer.d.ts @@ -0,0 +1,16 @@ +import { ComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +import { SortEnumsSortingNode, Options } from './types.js' +/** + * Builds a comparator computer function for sorting enum members. + * + * Creates a function that returns the appropriate comparator based on the + * sorting options and whether the enum is numeric. Handles sorting by name or + * by value depending on the `sortByValue` option. + * + * @param isNumericEnum - Whether the enum contains only numeric values. + * @returns A comparator computer function that creates comparators from + * options. + */ +export declare function buildComparatorByOptionsComputer( + isNumericEnum: boolean, +): ComparatorByOptionsComputer, SortEnumsSortingNode> diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/build-comparator-by-options-computer.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/build-comparator-by-options-computer.js new file mode 100644 index 0000000000000000000000000000000000000000..276646d9b5f4ad908a98df197f7eff20a2a7bd51 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/build-comparator-by-options-computer.js @@ -0,0 +1,84 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { buildLineLengthComparator } from '../../utils/compare/build-line-length-comparator.js' +import { compareAlphabetically } from '../../utils/compare/compare-alphabetically.js' +import { compareByCustomSort } from '../../utils/compare/compare-by-custom-sort.js' +import { unsortedComparator } from '../../utils/compare/unsorted-comparator.js' +import { compareNaturally } from '../../utils/compare/compare-naturally.js' +import { defaultComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +/** + * Builds a comparator computer function for sorting enum members. + * + * Creates a function that returns the appropriate comparator based on the + * sorting options and whether the enum is numeric. Handles sorting by name or + * by value depending on the `sortByValue` option. + * + * @param isNumericEnum - Whether the enum contains only numeric values. + * @returns A comparator computer function that creates comparators from + * options. + */ +function buildComparatorByOptionsComputer(isNumericEnum) { + return options => { + switch (options.sortByValue) { + case 'ifNumericEnum': + if (isNumericEnum) { + return byNumericValueComparatorComputer(options) + } + return defaultComparatorByOptionsComputer(options) + case 'always': + if (isNumericEnum) { + return byNumericValueComparatorComputer(options) + } + return byNonNumericValueComparatorComputer(options) + case 'never': + return defaultComparatorByOptionsComputer(options) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(options.sortByValue) + } + } +} +var byNonNumericValueComparatorComputer = options => { + switch (options.type) { + /* v8 ignore next 2 -- @preserve Untested for now as not a relevant sort for this rule. */ + case 'subgroup-order': + return defaultComparatorByOptionsComputer(options) + case 'alphabetical': + return (a, b) => + compareAlphabetically(a.value ?? '', b.value ?? '', options) + case 'line-length': + return buildLineLengthComparator(options) + case 'unsorted': + return unsortedComparator + case 'natural': + return (a, b) => compareNaturally(a.value ?? '', b.value ?? '', options) + case 'custom': + return (a, b) => + compareByCustomSort(a.value ?? '', b.value ?? '', options) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(options.type) + } +} +var byNumericValueComparatorComputer = options => { + switch (options.type) { + /* v8 ignore next 2 -- @preserve Untested for now as not a relevant sort for this rule. */ + case 'subgroup-order': + return defaultComparatorByOptionsComputer(options) + case 'alphabetical': + case 'line-length': + case 'natural': + case 'custom': + return (a, b) => + compareNaturally( + a.numericValue.toString(), + b.numericValue.toString(), + options, + ) + case 'unsorted': + return unsortedComparator + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(options.type) + } +} +export { buildComparatorByOptionsComputer } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-dependencies-by-sorting-node.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-dependencies-by-sorting-node.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..781103c5febf15760e9b2cca3a1fd83f9feeab39 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-dependencies-by-sorting-node.d.ts @@ -0,0 +1,13 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { SortEnumsSortingNode } from './types.js' +type SortingNodeWithoutDependencies = Omit +export declare function computeDependenciesBySortingNode({ + sortingNodes, + sourceCode, + enumName, +}: { + sortingNodes: SortingNodeWithoutDependencies[] + sourceCode: TSESLint.SourceCode + enumName: string +}): Map +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-dependencies-by-sorting-node.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-dependencies-by-sorting-node.js new file mode 100644 index 0000000000000000000000000000000000000000..6210ed9f7b624daa78b7b4496bd4fb967e06b425 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-dependencies-by-sorting-node.js @@ -0,0 +1,62 @@ +import { computeDependenciesBySortingNode as computeDependenciesBySortingNode$1 } from '../../utils/compute-dependencies-by-sorting-node.js' +import { computeParentNodesWithTypes } from '../../utils/compute-parent-nodes-with-types.js' +import { doesSortingNodeHaveOneOfDependencyNames } from '../../utils/does-sorting-node-have-one-of-dependency-names.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +function computeDependenciesBySortingNode({ + sortingNodes, + sourceCode, + enumName, +}) { + return computeDependenciesBySortingNode$1({ + additionalIdentifierDependenciesComputer: + buildAdditionalIdentifierDependenciesComputer({ + sortingNodes, + enumName, + }), + sortingNodes, + sourceCode, + }) +} +function buildAdditionalIdentifierDependenciesComputer({ + sortingNodes, + enumName, +}) { + return ({ referencingSortingNode, reference }) => { + if (reference.identifier.name !== enumName) { + return [] + } + let relatedIdentifiers = computeMemberExpressionIdentifiers( + reference.identifier, + referencingSortingNode, + ) + return sortingNodes.filter(sortingNode => + doesSortingNodeHaveOneOfDependencyNames(sortingNode, relatedIdentifiers), + ) + } +} +function computeMemberExpressionIdentifiers( + identifier, + referencingSortingNode, +) { + return computeParentNodesWithTypes({ + allowedTypes: [AST_NODE_TYPES.MemberExpression], + maxParent: referencingSortingNode.node, + consecutiveOnly: true, + node: identifier, + }) + .map(node => computeMemberExpressionPropertyName(node.property)) + .filter(name => name !== null) +} +function computeMemberExpressionPropertyName(property) { + if (property.type === AST_NODE_TYPES.Identifier) { + return property.name + } + if ( + property.type === AST_NODE_TYPES.Literal && + typeof property.value === 'string' + ) { + return property.value + } + return null +} +export { computeDependenciesBySortingNode } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-dependencies.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-dependencies.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7250084613807b65c20592c65e6efa73078fb28d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-dependencies.d.ts @@ -0,0 +1,14 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Extract dependencies from an enum. + * + * @deprecated - To remove when experimental dependency detection is the only + * option. + * @param expression - The enum or class declaration node. + * @param enumName - The name of the enum being processed. + * @returns The list of dependencies. + */ +export declare function computeDependencies( + expression: TSESTree.Expression, + enumName: string, +): string[] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-dependencies.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-dependencies.js new file mode 100644 index 0000000000000000000000000000000000000000..ba822be2d779b3fb04d4cdcecd2c48a798b29c14 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-dependencies.js @@ -0,0 +1,91 @@ +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Extract dependencies from an enum. + * + * @deprecated - To remove when experimental dependency detection is the only + * option. + * @param expression - The enum or class declaration node. + * @param enumName - The name of the enum being processed. + * @returns The list of dependencies. + */ +function computeDependencies(expression, enumName) { + let dependencies = [] + let stack = [expression] + while (stack.length > 0) { + let node = stack.pop() + switch (node.type) { + case AST_NODE_TYPES.MemberExpression: + if ( + node.object.type === AST_NODE_TYPES.Identifier && + node.object.name === enumName + ) { + if (node.property.type === AST_NODE_TYPES.Identifier) { + dependencies.push(node.property.name) + } else if ( + node.property.type === AST_NODE_TYPES.Literal && + typeof node.property.value === 'string' + ) { + dependencies.push(node.property.value) + } + } + break + case AST_NODE_TYPES.Identifier: + dependencies.push(node.name) + } + if ('alternate' in node && node.alternate) { + stack.push(node.alternate) + } + if ('argument' in node && node.argument) { + stack.push(node.argument) + } + if ('arguments' in node) { + stack.push(...node.arguments) + } + if ('callee' in node) { + stack.push(node.callee) + } + if ('consequent' in node) { + /* v8 ignore if -- @preserve Unsure if we can reach it. */ + if (Array.isArray(node.consequent)) { + stack.push(...node.consequent) + } else { + stack.push(node.consequent) + } + } + if ('elements' in node) { + let elements = node.elements.filter(currentNode => currentNode !== null) + stack.push(...elements) + } + if ('expressions' in node) { + stack.push(...node.expressions) + } + if ('key' in node) { + stack.push(node.key) + } + if ('left' in node) { + stack.push(node.left) + } + if ('object' in node) { + stack.push(node.object) + } + if ('properties' in node) { + stack.push(...node.properties) + } + if ('right' in node) { + stack.push(node.right) + } + if ('test' in node && node.test) { + stack.push(node.test) + } + if ( + 'value' in node && + node.value && + typeof node.value === 'object' && + 'type' in node.value + ) { + stack.push(node.value) + } + } + return dependencies +} +export { computeDependencies } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-expression-number-value.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-expression-number-value.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..27a0557761825209a03b61d23ba083b065425f02 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-expression-number-value.d.ts @@ -0,0 +1,13 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Extracts a numeric value from an AST expression node. + * + * Handles literal numbers, binary expressions, and unary expressions + * recursively to compute the final numeric value. + * + * @param expression - The AST node to evaluate. + * @returns The numeric value of the expression, or null if not evaluable. + */ +export declare function computeExpressionNumberValue( + expression: TSESTree.Node, +): number | null diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-expression-number-value.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-expression-number-value.js new file mode 100644 index 0000000000000000000000000000000000000000..99cb641d3d9379df4a7b1ad8317f8ba6388313b6 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-expression-number-value.js @@ -0,0 +1,105 @@ +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Extracts a numeric value from an AST expression node. + * + * Handles literal numbers, binary expressions, and unary expressions + * recursively to compute the final numeric value. + * + * @param expression - The AST node to evaluate. + * @returns The numeric value of the expression, or null if not evaluable. + */ +function computeExpressionNumberValue(expression) { + switch (expression.type) { + case AST_NODE_TYPES.BinaryExpression: + return computeBinaryExpressionNumberValue( + expression.left, + expression.right, + expression.operator, + ) + case AST_NODE_TYPES.UnaryExpression: + return computeUnaryExpressionNumberValue( + expression.argument, + expression.operator, + ) + case AST_NODE_TYPES.Literal: + return typeof expression.value === 'number' ? expression.value : null + default: + return null + } +} +/** + * Evaluates a binary expression to compute its numeric value. + * + * Supports arithmetic operators (+, -, *, /, %, **), bitwise operators (|, &, + * ^, <<, >>), and returns null for unsupported expressions. + * + * @param leftExpression - The left operand of the binary expression. + * @param rightExpression - The right operand of the binary expression. + * @param operator - The operator string (e.g., '+', '-', '*', '|'). + * @returns The computed numeric value, or null if it cannot be evaluated. + */ +function computeBinaryExpressionNumberValue( + leftExpression, + rightExpression, + operator, +) { + let left = computeExpressionNumberValue(leftExpression) + let right = computeExpressionNumberValue(rightExpression) + if (left === null || right === null) { + return null + } + switch (operator) { + case '**': + return left ** right + case '>>': + return left >> right + case '<<': + return left << right + case '+': + return left + right + case '-': + return left - right + case '*': + return left * right + case '/': + return left / right + case '%': + return left % right + case '|': + return left | right + case '&': + return left & right + case '^': + return left ^ right + /* v8 ignore next 2 -- @preserve Unsure if we can reach it. */ + default: + return null + } +} +/** + * Evaluates a unary expression to compute its numeric value. + * + * Supports unary plus (+), minus (-), and bitwise NOT (~) operators. + * + * @param argumentExpression - The operand of the unary expression. + * @param operator - The operator string (e.g., '+', '-', '~'). + * @returns The computed numeric value, or null if it cannot be evaluated. + */ +function computeUnaryExpressionNumberValue(argumentExpression, operator) { + let argument = computeExpressionNumberValue(argumentExpression) + if (argument === null) { + return null + } + switch (operator) { + case '+': + return argument + case '-': + return -argument + case '~': + return ~argument + /* v8 ignore next 2 -- @preserve Unsure if we can reach it. */ + default: + return null + } +} +export { computeExpressionNumberValue } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-matched-context-options.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-matched-context-options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d8c79d2789b8210c37c0e9371618d77c34713b74 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-matched-context-options.d.ts @@ -0,0 +1,22 @@ +import { RuleContext } from '@typescript-eslint/utils/ts-eslint' +import { TSESTree } from '@typescript-eslint/types' +import { MessageId, Options } from './types.js' +/** + * Computes the matched context options for a given enum node. + * + * @param params - Parameters. + * @param params.enumMembers - The enum members of the enum declaration node. + * @param params.matchedAstSelectors - The matched AST selectors for an enum + * node. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +export declare function computeMatchedContextOptions({ + matchedAstSelectors, + enumMembers, + context, +}: { + context: Readonly> + matchedAstSelectors: ReadonlySet + enumMembers: TSESTree.TSEnumMember[] +}): Options[number] | undefined diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-matched-context-options.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-matched-context-options.js new file mode 100644 index 0000000000000000000000000000000000000000..5bfc0f0e1198138b333036b5f7f3628306d4f61a --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-matched-context-options.js @@ -0,0 +1,48 @@ +import { passesAllNamesMatchPatternFilter } from '../../utils/context-matching/passes-all-names-match-pattern-filter.js' +import { passesAstSelectorFilter } from '../../utils/context-matching/passes-ast-selector-filter.js' +import { computeNodeName } from './compute-node-name.js' +/** + * Computes the matched context options for a given enum node. + * + * @param params - Parameters. + * @param params.enumMembers - The enum members of the enum declaration node. + * @param params.matchedAstSelectors - The matched AST selectors for an enum + * node. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +function computeMatchedContextOptions({ + matchedAstSelectors, + enumMembers, + context, +}) { + let nodeNames = enumMembers.map(enumMember => + computeNodeName({ + sourceCode: context.sourceCode, + node: enumMember, + }), + ) + return context.options.find(options => + isContextOptionMatching({ + matchedAstSelectors, + nodeNames, + options, + }), + ) +} +function isContextOptionMatching({ matchedAstSelectors, nodeNames, options }) { + if (!options.useConfigurationIf) { + return true + } + return ( + passesAllNamesMatchPatternFilter({ + allNamesMatchPattern: options.useConfigurationIf.allNamesMatchPattern, + nodeNames, + }) && + passesAstSelectorFilter({ + matchesAstSelector: options.useConfigurationIf.matchesAstSelector, + matchedAstSelectors, + }) + ) +} +export { computeMatchedContextOptions } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-node-name.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-node-name.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ee95df909e9fc19d4ed9eaacb61d1ca5c661290 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-node-name.d.ts @@ -0,0 +1,17 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +/** + * Computes the name of an enum member node. + * + * @param params - Parameters for group-based sorting. + * @param params.node - The enum member node. + * @param params.sourceCode - The source code object. + * @returns The computed name of the enum member node. + */ +export declare function computeNodeName({ + sourceCode, + node, +}: { + sourceCode: TSESLint.SourceCode + node: TSESTree.TSEnumMember +}): string diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-node-name.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-node-name.js new file mode 100644 index 0000000000000000000000000000000000000000..9b3fc7c0d8b35af1237d1e26ab200c2801c23e0c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/compute-node-name.js @@ -0,0 +1,15 @@ +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the name of an enum member node. + * + * @param params - Parameters for group-based sorting. + * @param params.node - The enum member node. + * @param params.sourceCode - The source code object. + * @returns The computed name of the enum member node. + */ +function computeNodeName({ sourceCode, node }) { + return node.id.type === AST_NODE_TYPES.Literal ? + node.id.value + : sourceCode.getText(node.id) +} +export { computeNodeName } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/sort-enum.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/sort-enum.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..89dca276bf9297f202677f7939638d661719a4e7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/sort-enum.d.ts @@ -0,0 +1,13 @@ +import { RuleContext } from '@typescript-eslint/utils/ts-eslint' +import { TSESTree } from '@typescript-eslint/types' +import { MessageId, Options } from './types.js' +export declare let defaultOptions: Required +export declare function sortEnum({ + matchedAstSelectors, + context, + node, +}: { + context: Readonly> + matchedAstSelectors: ReadonlySet + node: TSESTree.TSEnumDeclaration +}): void diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/sort-enum.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/sort-enum.js new file mode 100644 index 0000000000000000000000000000000000000000..5f67268981cd430b9f94391bd8d3757d470ea3a0 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/sort-enum.js @@ -0,0 +1,174 @@ +import { populateSortingNodeGroupsWithDependencies } from '../../utils/populate-sorting-node-groups-with-dependencies.js' +import { validateNewlinesAndPartitionConfig } from '../../utils/validate-newlines-and-partition-config.js' +import { buildOptionsByGroupIndexComputer } from '../../utils/build-options-by-group-index-computer.js' +import { validateCustomSortConfig } from '../../utils/validate-custom-sort-config.js' +import { sortNodesByDependencies } from '../../utils/sort-nodes-by-dependencies.js' +import { getEslintDisabledLines } from '../../utils/get-eslint-disabled-lines.js' +import { doesCustomGroupMatch } from '../../utils/does-custom-group-match.js' +import { isNodeEslintDisabled } from '../../utils/is-node-eslint-disabled.js' +import { validateGroupsConfig } from '../../utils/validate-groups-config.js' +import { sortNodesByGroups } from '../../utils/sort-nodes-by-groups.js' +import { reportAllErrors } from '../../utils/report-all-errors.js' +import { shouldPartition } from '../../utils/should-partition.js' +import { computeGroup } from '../../utils/compute-group.js' +import { rangeToDiff } from '../../utils/range-to-diff.js' +import { getSettings } from '../../utils/get-settings.js' +import { isSortable } from '../../utils/is-sortable.js' +import { complete } from '../../utils/complete.js' +import { getEnumMembers } from '../../utils/get-enum-members.js' +import { + DEPENDENCY_ORDER_ERROR_ID, + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, +} from './types.js' +import { computeDependenciesBySortingNode } from './compute-dependencies-by-sorting-node.js' +import { buildComparatorByOptionsComputer } from './build-comparator-by-options-computer.js' +import { computeExpressionNumberValue } from './compute-expression-number-value.js' +import { computeNodeName } from './compute-node-name.js' +import { computeMatchedContextOptions } from './compute-matched-context-options.js' +import { computeDependencies } from './compute-dependencies.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var defaultOptions = { + useExperimentalDependencyDetection: true, + fallbackSort: { type: 'unsorted' }, + newlinesInside: 'newlinesBetween', + sortByValue: 'ifNumericEnum', + partitionByComment: false, + partitionByNewLine: false, + specialCharacters: 'keep', + newlinesBetween: 'ignore', + useConfigurationIf: {}, + type: 'alphabetical', + ignoreCase: true, + locales: 'en-US', + customGroups: [], + alphabet: '', + order: 'asc', + groups: [], +} +function sortEnum({ matchedAstSelectors, context, node }) { + let members = getEnumMembers(node) + if (!isSortable(members) || members.some(({ initializer }) => !initializer)) { + return + } + let settings = getSettings(context.settings) + let matchedContextOptions = computeMatchedContextOptions({ + enumMembers: members, + matchedAstSelectors, + context, + }) + let options = complete(matchedContextOptions, settings, defaultOptions) + validateCustomSortConfig(options) + validateGroupsConfig({ + selectors: [], + modifiers: [], + options, + }) + validateNewlinesAndPartitionConfig(options) + let { sourceCode, id } = context + let eslintDisabledLines = getEslintDisabledLines({ + ruleName: id, + sourceCode, + }) + let optionsByGroupIndexComputer = buildOptionsByGroupIndexComputer(options) + let sortingNodeGroups = members.reduce( + (accumulator, member) => { + let name = computeNodeName({ + node: member, + sourceCode, + }) + let group = computeGroup({ + customGroupMatcher: customGroup => + doesCustomGroupMatch({ + elementValue: sourceCode.getText(member.initializer), + elementName: name, + selectors: [], + modifiers: [], + customGroup, + }), + predefinedGroups: [], + options, + }) + let lastSortingNode = accumulator.at(-1)?.at(-1) + let sortingNode = { + dependencies: + options.useExperimentalDependencyDetection ? + [] + : computeDependencies(member.initializer, node.id.name), + value: + member.initializer?.type === AST_NODE_TYPES.Literal ? + (member.initializer.value?.toString() ?? null) + : null, + isEslintDisabled: isNodeEslintDisabled(member, eslintDisabledLines), + numericValue: computeExpressionNumberValue(member.initializer), + size: rangeToDiff(member, sourceCode), + dependencyNames: [name], + node: member, + group, + name, + } + if ( + shouldPartition({ + lastSortingNode, + sortingNode, + sourceCode, + options, + }) + ) { + accumulator.push([]) + } + accumulator.at(-1).push({ + ...sortingNode, + partitionId: accumulator.length, + }) + return accumulator + }, + [[]], + ) + if (options.useExperimentalDependencyDetection) { + let dependenciesBySortingNode = computeDependenciesBySortingNode({ + sortingNodes: sortingNodeGroups.flat(), + enumName: node.id.name, + sourceCode, + }) + sortingNodeGroups = populateSortingNodeGroupsWithDependencies({ + dependenciesBySortingNode, + sortingNodeGroups, + }) + } + let sortingNodes = sortingNodeGroups.flat() + let isNumericEnum = sortingNodes.every( + sortingNode => sortingNode.numericValue !== null, + ) + reportAllErrors({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + unexpectedDependencyOrder: DEPENDENCY_ORDER_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + sortNodesExcludingEslintDisabled, + nodes: sortingNodes, + options, + context, + }) + function sortNodesExcludingEslintDisabled(ignoreEslintDisabledNodes) { + let nodesSortedByGroups = sortingNodeGroups.flatMap(sortingNodeGroup => + sortNodesByGroups({ + comparatorByOptionsComputer: + buildComparatorByOptionsComputer(isNumericEnum), + optionsByGroupIndexComputer, + ignoreEslintDisabledNodes, + nodes: sortingNodeGroup, + groups: options.groups, + }), + ) + return sortNodesByDependencies(nodesSortedByGroups, { + ignoreEslintDisabledNodes, + }) + } +} +export { defaultOptions, sortEnum } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2a2d17839ecc9947d0e8accc4750f6e1b0cfdb94 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/types.d.ts @@ -0,0 +1,82 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +import { TSESTree } from '@typescript-eslint/types' +import { SortingNodeWithDependencies } from '../../utils/sort-nodes-by-dependencies.js' +import { RegexOption, TypeOption } from '../../types/common-options.js' +import { AllCommonOptions } from '../../types/all-common-options.js' +export type MessageId = + | typeof DEPENDENCY_ORDER_ERROR_ID + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +export declare const ORDER_ERROR_ID = 'unexpectedEnumsOrder' +export declare const GROUP_ORDER_ERROR_ID = 'unexpectedEnumsGroupOrder' +export declare const EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenEnumsMembers' +export declare const MISSED_SPACING_ERROR_ID = + 'missedSpacingBetweenEnumsMembers' +export declare const DEPENDENCY_ORDER_ERROR_ID = + 'unexpectedEnumsDependencyOrder' +/** + * Configuration options for the sort-enums rule. + * + * This rule enforces consistent ordering of TypeScript enum members to improve + * code readability and maintainability. + */ +export type Options = Partial< + { + /** + * Conditional configuration based on pattern matching. + */ + useConfigurationIf: { + /** + * Regular expression pattern to match against all enum element names. + * The rule is only applied when all names match this pattern. + */ + allNamesMatchPattern?: RegexOption + /** + * AST selector to match against TSEnumDeclaration nodes. + */ + matchesAstSelector?: string + } + /** + * Whether to sort enum members by their values instead of names. When + * "always", compares enum values; when "never", compares enum member + * names. + * + * @default ifNumericEnum + */ + sortByValue: 'ifNumericEnum' | 'always' | 'never' + /** + * Enables experimental dependency detection. + */ + useExperimentalDependencyDetection: boolean + } & AllCommonOptions< + TypeOption, + AdditionalSortOptions, + CustomGroupMatchOptions + > +>[] +export interface SortEnumsSortingNode extends SortingNodeWithDependencies { + numericValue: number | null + value: string | null +} +/** + * Match options for a custom group. + */ +interface CustomGroupMatchOptions { + /** + * Regular expression pattern to match enum member values. Members with + * values matching this pattern will be included in this custom group. + */ + elementValuePattern?: RegexOption +} +type AdditionalSortOptions = object +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +export declare let additionalCustomGroupMatchOptionsJsonSchema: Record< + string, + JSONSchema4 +> +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/types.js new file mode 100644 index 0000000000000000000000000000000000000000..42ca924b599bdfb7a365f57832a3ff6f4b1d07f3 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-enums/types.js @@ -0,0 +1,21 @@ +import { buildRegexJsonSchema } from '../../utils/json-schemas/common-json-schemas.js' +var ORDER_ERROR_ID = 'unexpectedEnumsOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedEnumsGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenEnumsMembers' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenEnumsMembers' +var DEPENDENCY_ORDER_ERROR_ID = 'unexpectedEnumsDependencyOrder' +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +var additionalCustomGroupMatchOptionsJsonSchema = { + elementValuePattern: buildRegexJsonSchema(), +} +export { + DEPENDENCY_ORDER_ERROR_ID, + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + additionalCustomGroupMatchOptionsJsonSchema, +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-export-attributes.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-export-attributes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b9f5df976ba07b70b03190f662a15b5c075ff78 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-export-attributes.d.ts @@ -0,0 +1,20 @@ +declare const ORDER_ERROR_ID = 'unexpectedExportAttributesOrder' +declare const GROUP_ORDER_ERROR_ID = 'unexpectedExportAttributesGroupOrder' +declare const EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenExportAttributes' +declare const MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenExportAttributes' +type MessageId = + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +declare const _default: import('@typescript-eslint/utils/ts-eslint').RuleModule< + MessageId, + import('...js').SortImportAttributesOptions, + { + recommended?: boolean + }, + import('@typescript-eslint/utils/ts-eslint').RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-export-attributes.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-export-attributes.js new file mode 100644 index 0000000000000000000000000000000000000000..b39aedf042e4a3ed08de32d99b54d75b8a68b9a5 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-export-attributes.js @@ -0,0 +1,72 @@ +import { + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { buildAstListeners } from '../utils/build-ast-listeners.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { sortImportOrExportAttributes } from './sort-import-attributes/sort-import-or-export-attributes.js' +import { jsonSchema } from './sort-import-attributes.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var ORDER_ERROR_ID = 'unexpectedExportAttributesOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedExportAttributesGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenExportAttributes' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenExportAttributes' +var defaultOptions = { + fallbackSort: { type: 'unsorted' }, + newlinesInside: 'newlinesBetween', + specialCharacters: 'keep', + partitionByComment: false, + partitionByNewLine: false, + newlinesBetween: 'ignore', + useConfigurationIf: {}, + type: 'alphabetical', + ignoreCase: true, + customGroups: [], + locales: 'en-US', + alphabet: '', + order: 'asc', + groups: [], +} +var sort_export_attributes_default = createEslintRule({ + meta: { + messages: { + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-export-attributes', + description: 'Enforce sorted export attributes.', + recommended: true, + }, + schema: jsonSchema, + type: 'suggestion', + fixable: 'code', + }, + create: context => + buildAstListeners({ + nodeTypes: [AST_NODE_TYPES.ExportNamedDeclaration], + sorter: sortExportAttributes, + context, + }), + defaultOptions: [defaultOptions], + name: 'sort-export-attributes', +}) +function sortExportAttributes({ matchedAstSelectors, context, node }) { + sortImportOrExportAttributes({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + matchedAstSelectors, + defaultOptions, + context, + node, + }) +} +export { sort_export_attributes_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-export-attributes/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-export-attributes/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd0af33ebae01fbd14136a8884a94fb9fba3033c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-export-attributes/types.d.ts @@ -0,0 +1,2 @@ +import { Options as SortImportAttributesOptions } from '../sort-import-attributes/types.js' +export type Options = SortImportAttributesOptions diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-exports.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-exports.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a06986d86504ee59a41ea7befe3010844780f88a --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-exports.d.ts @@ -0,0 +1,24 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { Options } from './sort-exports/types.js' +declare const ORDER_ERROR_ID = 'unexpectedExportsOrder' +declare const GROUP_ORDER_ERROR_ID = 'unexpectedExportsGroupOrder' +declare const EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenExports' +declare const MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenExports' +declare const MISSED_COMMENT_ABOVE_ERROR_ID = 'missedCommentAboveExport' +type MessageId = + | typeof MISSED_COMMENT_ABOVE_ERROR_ID + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +declare const _default: TSESLint.RuleModule< + MessageId, + Options, + { + recommended?: boolean + }, + TSESLint.RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-exports.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-exports.js new file mode 100644 index 0000000000000000000000000000000000000000..10485817eb813111b26e570864d061eb7ad058b9 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-exports.js @@ -0,0 +1,237 @@ +import { buildCommonJsonSchemas } from '../utils/json-schemas/common-json-schemas.js' +import { buildCommonGroupsJsonSchemas } from '../utils/json-schemas/common-groups-json-schemas.js' +import { UnreachableCaseError } from '../utils/unreachable-case-error.js' +import { + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_COMMENT_ABOVE_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { + partitionByCommentJsonSchema, + partitionByNewlineJsonSchema, +} from '../utils/json-schemas/common-partition-json-schemas.js' +import { defaultComparatorByOptionsComputer } from '../utils/compare/default-comparator-by-options-computer.js' +import { validateNewlinesAndPartitionConfig } from '../utils/validate-newlines-and-partition-config.js' +import { buildOptionsByGroupIndexComputer } from '../utils/build-options-by-group-index-computer.js' +import { validateCustomSortConfig } from '../utils/validate-custom-sort-config.js' +import { generatePredefinedGroups } from '../utils/generate-predefined-groups.js' +import { getEslintDisabledLines } from '../utils/get-eslint-disabled-lines.js' +import { doesCustomGroupMatch } from '../utils/does-custom-group-match.js' +import { isNodeEslintDisabled } from '../utils/is-node-eslint-disabled.js' +import { validateGroupsConfig } from '../utils/validate-groups-config.js' +import { sortNodesByGroups } from '../utils/sort-nodes-by-groups.js' +import { reportAllErrors } from '../utils/report-all-errors.js' +import { shouldPartition } from '../utils/should-partition.js' +import { computeGroup } from '../utils/compute-group.js' +import { rangeToDiff } from '../utils/range-to-diff.js' +import { getSettings } from '../utils/get-settings.js' +import { complete } from '../utils/complete.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { isNodeOnSingleLine } from '../utils/is-node-on-single-line.js' +import { + additionalCustomGroupMatchOptionsJsonSchema, + allModifiers, + allSelectors, +} from './sort-exports/types.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Cache computed groups by modifiers and selectors for performance. + */ +var cachedGroupsByModifiersAndSelectors = /* @__PURE__ */ new Map() +var ORDER_ERROR_ID = 'unexpectedExportsOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedExportsGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenExports' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenExports' +var MISSED_COMMENT_ABOVE_ERROR_ID = 'missedCommentAboveExport' +var defaultOptions = { + fallbackSort: { type: 'unsorted' }, + newlinesInside: 'newlinesBetween', + specialCharacters: 'keep', + partitionByComment: false, + newlinesBetween: 'ignore', + partitionByNewLine: false, + type: 'alphabetical', + customGroups: [], + ignoreCase: true, + locales: 'en-US', + alphabet: '', + order: 'asc', + groups: [], +} +var sort_exports_default = createEslintRule({ + create: context => { + let settings = getSettings(context.settings) + let options = complete(context.options.at(0), settings, defaultOptions) + validateCustomSortConfig(options) + validateGroupsConfig({ + modifiers: allModifiers, + selectors: allSelectors, + options, + }) + validateNewlinesAndPartitionConfig(options) + let { sourceCode, id } = context + let eslintDisabledLines = getEslintDisabledLines({ + ruleName: id, + sourceCode, + }) + let formattedMembers = [[]] + function registerNode(node) { + if (!node.source) { + return + } + let selector = 'export' + let modifiers = [ + computeExportKindModifier(node), + computeExportTypeModifier(node), + computeLineCountModifier(node), + ] + let name = node.source.value + let predefinedGroups = generatePredefinedGroups({ + cache: cachedGroupsByModifiersAndSelectors, + selectors: [selector], + modifiers, + }) + let group = computeGroup({ + customGroupMatcher: customGroup => + doesCustomGroupMatch({ + selectors: [selector], + elementName: name, + customGroup, + modifiers, + }), + predefinedGroups, + options, + }) + let sortingNode = { + isEslintDisabled: isNodeEslintDisabled(node, eslintDisabledLines), + size: rangeToDiff(node, sourceCode), + addSafetySemicolonWhenInline: true, + group, + name, + node, + } + let lastSortingNode = formattedMembers.at(-1)?.at(-1) + if ( + shouldPartition({ + lastSortingNode, + sortingNode, + sourceCode, + options, + }) + ) { + formattedMembers.push([]) + } + formattedMembers.at(-1).push({ + ...sortingNode, + partitionId: formattedMembers.length, + }) + } + return { + 'Program:exit': () => { + sortExportNodes({ + formattedMembers, + context, + options, + }) + }, + ExportNamedDeclaration: registerNode, + ExportAllDeclaration: registerNode, + } + }, + meta: { + schema: { + items: { + properties: { + ...buildCommonJsonSchemas(), + ...buildCommonGroupsJsonSchemas({ + additionalCustomGroupMatchProperties: + additionalCustomGroupMatchOptionsJsonSchema, + }), + partitionByComment: partitionByCommentJsonSchema, + partitionByNewLine: partitionByNewlineJsonSchema, + }, + additionalProperties: false, + type: 'object', + }, + uniqueItems: true, + type: 'array', + }, + messages: { + [MISSED_COMMENT_ABOVE_ERROR_ID]: MISSED_COMMENT_ABOVE_ERROR, + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-exports', + description: 'Enforce sorted exports.', + recommended: true, + }, + type: 'suggestion', + fixable: 'code', + }, + defaultOptions: [defaultOptions], + name: 'sort-exports', +}) +function sortExportNodes({ formattedMembers, context, options }) { + let optionsByGroupIndexComputer = buildOptionsByGroupIndexComputer(options) + let nodes = formattedMembers.flat() + reportAllErrors({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + missedCommentAbove: MISSED_COMMENT_ABOVE_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + sortNodesExcludingEslintDisabled, + options, + context, + nodes, + }) + function sortNodesExcludingEslintDisabled(ignoreEslintDisabledNodes) { + return formattedMembers.flatMap(groupedNodes => + sortNodesByGroups({ + comparatorByOptionsComputer: defaultComparatorByOptionsComputer, + optionsByGroupIndexComputer, + ignoreEslintDisabledNodes, + groups: options.groups, + nodes: groupedNodes, + }), + ) + } +} +function computeExportKindModifier(node) { + let exportKind = 'exportKind' in node ? node.exportKind : void 0 + switch (exportKind) { + case void 0: + case 'value': + return 'value' + case 'type': + return 'type' + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(exportKind) + } +} +function computeExportTypeModifier(node) { + switch (node.type) { + case AST_NODE_TYPES.ExportNamedDeclaration: + return 'named' + case AST_NODE_TYPES.ExportAllDeclaration: + return 'wildcard' + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(node) + } +} +function computeLineCountModifier(node) { + if (isNodeOnSingleLine(node)) { + return 'singleline' + } + return 'multiline' +} +export { sort_exports_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-exports/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-exports/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..71e93d3b562f085d32f79a618d35b2658e501e37 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-exports/types.d.ts @@ -0,0 +1,76 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +import { AllCommonOptions } from '../../types/all-common-options.js' +import { TypeOption } from '../../types/common-options.js' +/** + * Configuration options for the sort-exports rule. + * + * This rule enforces consistent ordering of re-export statements (`export ... + * From '...'`) to improve code organization and maintainability. + */ +export type Options = Partial< + AllCommonOptions +>[] +/** + * Union type of available export modifiers. Distinguishes between value exports + * and type-only exports. + */ +export type Modifier = (typeof allModifiers)[number] +/** + * Type of selector for export statements. Currently represents re-export + * statements. + */ +export type Selector = (typeof allSelectors)[number] +/** + * Additional configuration for a single custom group. + * + * Custom groups allow fine-grained control over how export statements are + * grouped and sorted based on their module names, selectors, and modifiers. + * + * @example + * + * ```ts + * { + * "modifiers": ["type"], + * "selector": "export" + * } + * ``` + */ +interface CustomGroupMatchOptions { + /** + * List of modifiers that exports must have to be included in this group. + * Can include 'value' for value exports or 'type' for type exports. + */ + modifiers?: Modifier[] + /** + * The selector type for this group. Currently only 'export' is supported + * for re-export statements. + */ + selector?: Selector +} +type AdditionalSortOptions = object +/** + * Complete list of available export selectors. Used for validation and JSON + * schema generation. + */ +export declare let allSelectors: readonly ['export'] +/** + * Complete list of available export modifiers. Used for validation and JSON + * schema generation. + */ +export declare let allModifiers: readonly [ + 'value', + 'type', + 'named', + 'wildcard', + 'multiline', + 'singleline', +] +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +export declare let additionalCustomGroupMatchOptionsJsonSchema: Record< + string, + JSONSchema4 +> +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-exports/types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-exports/types.js new file mode 100644 index 0000000000000000000000000000000000000000..6ad0517c390426fd6688415db531e089539ce3a5 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-exports/types.js @@ -0,0 +1,34 @@ +import { + buildCustomGroupModifiersJsonSchema, + buildCustomGroupSelectorJsonSchema, +} from '../../utils/json-schemas/common-groups-json-schemas.js' +/** + * Complete list of available export selectors. Used for validation and JSON + * schema generation. + */ +var allSelectors = ['export'] +/** + * Complete list of available export modifiers. Used for validation and JSON + * schema generation. + */ +var allModifiers = [ + 'value', + 'type', + 'named', + 'wildcard', + 'multiline', + 'singleline', +] +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +var additionalCustomGroupMatchOptionsJsonSchema = { + modifiers: buildCustomGroupModifiersJsonSchema(allModifiers), + selector: buildCustomGroupSelectorJsonSchema(allSelectors), +} +export { + additionalCustomGroupMatchOptionsJsonSchema, + allModifiers, + allSelectors, +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..14d472e945cdcae201a09e71eeaa5513396847b6 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses.d.ts @@ -0,0 +1,12 @@ +import { MessageId, Options } from './sort-heritage-clauses/types.js' +declare const _default: import('@typescript-eslint/utils/ts-eslint').RuleModule< + MessageId, + Options, + { + recommended?: boolean + }, + import('@typescript-eslint/utils/ts-eslint').RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses.js new file mode 100644 index 0000000000000000000000000000000000000000..255ac05bdedc989a8986d538df7ca83db960a540 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses.js @@ -0,0 +1,77 @@ +import { + buildCommonJsonSchemas, + buildUseConfigIfJsonSchema, + matchesAstSelectorJsonSchema, +} from '../utils/json-schemas/common-json-schemas.js' +import { buildCommonGroupsJsonSchemas } from '../utils/json-schemas/common-groups-json-schemas.js' +import { + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { + partitionByCommentJsonSchema, + partitionByNewlineJsonSchema, +} from '../utils/json-schemas/common-partition-json-schemas.js' +import { buildAstListeners } from '../utils/build-ast-listeners.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, +} from './sort-heritage-clauses/types.js' +import { + defaultOptions, + sortHeritageClause, +} from './sort-heritage-clauses/sort-heritage-clause.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var sort_heritage_clauses_default = createEslintRule({ + meta: { + schema: { + items: { + properties: { + ...buildCommonJsonSchemas(), + ...buildCommonGroupsJsonSchemas(), + useConfigurationIf: buildUseConfigIfJsonSchema({ + additionalProperties: { + matchesAstSelector: matchesAstSelectorJsonSchema, + }, + }), + partitionByNewLine: partitionByNewlineJsonSchema, + partitionByComment: partitionByCommentJsonSchema, + }, + additionalProperties: false, + type: 'object', + }, + uniqueItems: true, + type: 'array', + }, + messages: { + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-heritage-clauses', + description: 'Enforce sorted heritage clauses.', + recommended: true, + }, + type: 'suggestion', + fixable: 'code', + }, + create: context => + buildAstListeners({ + nodeTypes: [ + AST_NODE_TYPES.TSInterfaceDeclaration, + AST_NODE_TYPES.ClassDeclaration, + ], + sorter: sortHeritageClause, + context, + }), + defaultOptions: [defaultOptions], + name: 'sort-heritage-clauses', +}) +export { sort_heritage_clauses_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/compute-matched-context-options.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/compute-matched-context-options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..acdaf8e0feadf8ebb238e582c02a58f1e86fc479 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/compute-matched-context-options.d.ts @@ -0,0 +1,22 @@ +import { RuleContext } from '@typescript-eslint/utils/ts-eslint' +import { TSESTree } from '@typescript-eslint/types' +import { MessageId, Options } from './types.js' +/** + * Computes the matched context options for a given heritage clause parent node. + * + * @param params - Parameters. + * @param params.heritageClauses - The heritage clauses of the parent node. + * @param params.matchedAstSelectors - The matched AST selectors for an object + * node. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +export declare function computeMatchedContextOptions({ + matchedAstSelectors, + heritageClauses, + context, +}: { + heritageClauses: TSESTree.TSInterfaceHeritage[] | TSESTree.TSClassImplements[] + context: Readonly> + matchedAstSelectors: ReadonlySet +}): Options[number] | undefined diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/compute-matched-context-options.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/compute-matched-context-options.js new file mode 100644 index 0000000000000000000000000000000000000000..7441bf2b3c4d29f36252ae39a218cebfc65c1ac9 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/compute-matched-context-options.js @@ -0,0 +1,45 @@ +import { passesAllNamesMatchPatternFilter } from '../../utils/context-matching/passes-all-names-match-pattern-filter.js' +import { passesAstSelectorFilter } from '../../utils/context-matching/passes-ast-selector-filter.js' +import { computeNodeName } from './compute-node-name.js' +/** + * Computes the matched context options for a given heritage clause parent node. + * + * @param params - Parameters. + * @param params.heritageClauses - The heritage clauses of the parent node. + * @param params.matchedAstSelectors - The matched AST selectors for an object + * node. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +function computeMatchedContextOptions({ + matchedAstSelectors, + heritageClauses, + context, +}) { + let nodeNames = heritageClauses.map(clause => + computeNodeName(clause.expression), + ) + return context.options.find(options => + isContextOptionMatching({ + matchedAstSelectors, + nodeNames, + options, + }), + ) +} +function isContextOptionMatching({ matchedAstSelectors, nodeNames, options }) { + if (!options.useConfigurationIf) { + return true + } + return ( + passesAllNamesMatchPatternFilter({ + allNamesMatchPattern: options.useConfigurationIf.allNamesMatchPattern, + nodeNames, + }) && + passesAstSelectorFilter({ + matchesAstSelector: options.useConfigurationIf.matchesAstSelector, + matchedAstSelectors, + }) + ) +} +export { computeMatchedContextOptions } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/compute-node-name.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/compute-node-name.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd3a5d2ddf38bb7840a3f741f7e80357b7f9eb7b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/compute-node-name.d.ts @@ -0,0 +1,13 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Extracts the name from a heritage clause expression. + * + * For simple identifiers, returns the name directly. For member expressions + * (like `Namespace.Class`), extracts the innermost property name. + * + * @param expression - The heritage clause expression AST node. + * @returns The extracted name string from the expression. + */ +export declare function computeNodeName( + expression: TSESTree.PrivateIdentifier | TSESTree.Expression, +): string diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/compute-node-name.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/compute-node-name.js new file mode 100644 index 0000000000000000000000000000000000000000..d67bd3abe350daa2accf3f8a909dce1e5ed1b3d2 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/compute-node-name.js @@ -0,0 +1,25 @@ +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Extracts the name from a heritage clause expression. + * + * For simple identifiers, returns the name directly. For member expressions + * (like `Namespace.Class`), extracts the innermost property name. + * + * @param expression - The heritage clause expression AST node. + * @returns The extracted name string from the expression. + */ +function computeNodeName(expression) { + let currentExpression = expression + while ('property' in currentExpression) { + currentExpression = currentExpression.property + } + /* v8 ignore else -- @preserve Exhaustive guard for unsupported expressions. */ + if (currentExpression.type === AST_NODE_TYPES.Identifier) { + return currentExpression.name + } + /* v8 ignore next -- @preserve Should never throw. */ + throw new Error( + 'Unexpected heritage clause expression. Please report this issue here: https://github.com/azat-io/eslint-plugin-perfectionist/issues', + ) +} +export { computeNodeName } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/sort-heritage-clause.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/sort-heritage-clause.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..16a21e48b002e9539e4e020b7da1fb869378f84e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/sort-heritage-clause.d.ts @@ -0,0 +1,13 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { TSESTree } from '@typescript-eslint/types' +import { MessageId, Options } from './types.js' +export declare let defaultOptions: Required +export declare function sortHeritageClause({ + matchedAstSelectors, + context, + node, +}: { + node: TSESTree.TSInterfaceDeclaration | TSESTree.ClassDeclaration + context: TSESLint.RuleContext + matchedAstSelectors: ReadonlySet +}): void diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/sort-heritage-clause.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/sort-heritage-clause.js new file mode 100644 index 0000000000000000000000000000000000000000..137849c1ba86283be404029fe4e857cd3a73542d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/sort-heritage-clause.js @@ -0,0 +1,135 @@ +import { defaultComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +import { validateNewlinesAndPartitionConfig } from '../../utils/validate-newlines-and-partition-config.js' +import { buildOptionsByGroupIndexComputer } from '../../utils/build-options-by-group-index-computer.js' +import { validateCustomSortConfig } from '../../utils/validate-custom-sort-config.js' +import { getEslintDisabledLines } from '../../utils/get-eslint-disabled-lines.js' +import { doesCustomGroupMatch } from '../../utils/does-custom-group-match.js' +import { isNodeEslintDisabled } from '../../utils/is-node-eslint-disabled.js' +import { validateGroupsConfig } from '../../utils/validate-groups-config.js' +import { sortNodesByGroups } from '../../utils/sort-nodes-by-groups.js' +import { reportAllErrors } from '../../utils/report-all-errors.js' +import { shouldPartition } from '../../utils/should-partition.js' +import { computeGroup } from '../../utils/compute-group.js' +import { rangeToDiff } from '../../utils/range-to-diff.js' +import { getSettings } from '../../utils/get-settings.js' +import { isSortable } from '../../utils/is-sortable.js' +import { complete } from '../../utils/complete.js' +import { + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, +} from './types.js' +import { computeNodeName } from './compute-node-name.js' +import { computeMatchedContextOptions } from './compute-matched-context-options.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var defaultOptions = { + fallbackSort: { type: 'unsorted' }, + newlinesInside: 'newlinesBetween', + specialCharacters: 'keep', + newlinesBetween: 'ignore', + partitionByNewLine: false, + partitionByComment: false, + useConfigurationIf: {}, + type: 'alphabetical', + ignoreCase: true, + customGroups: [], + locales: 'en-US', + alphabet: '', + order: 'asc', + groups: [], +} +function sortHeritageClause({ matchedAstSelectors, context, node }) { + let heritageClauses = + node.type === AST_NODE_TYPES.TSInterfaceDeclaration ? + node.extends + : node.implements + if (!isSortable(heritageClauses)) { + return + } + let settings = getSettings(context.settings) + let matchedContextOptions = computeMatchedContextOptions({ + matchedAstSelectors, + heritageClauses, + context, + }) + let options = complete(matchedContextOptions, settings, defaultOptions) + validateCustomSortConfig(options) + validateGroupsConfig({ + modifiers: [], + selectors: [], + options, + }) + validateNewlinesAndPartitionConfig(options) + let { sourceCode, id } = context + let eslintDisabledLines = getEslintDisabledLines({ + ruleName: id, + sourceCode, + }) + let optionsByGroupIndexComputer = buildOptionsByGroupIndexComputer(options) + let formattedMembers = [[]] + for (let heritageClause of heritageClauses) { + let name = computeNodeName(heritageClause.expression) + let group = computeGroup({ + customGroupMatcher: customGroup => + doesCustomGroupMatch({ + elementName: name, + selectors: [], + modifiers: [], + customGroup, + }), + predefinedGroups: [], + options, + }) + let sortingNode = { + isEslintDisabled: isNodeEslintDisabled( + heritageClause, + eslintDisabledLines, + ), + size: rangeToDiff(heritageClause, sourceCode), + node: heritageClause, + partitionId: 0, + group, + name, + } + let lastSortingNode = formattedMembers.at(-1)?.at(-1) + if ( + shouldPartition({ + lastSortingNode, + sortingNode, + sourceCode, + options, + }) + ) { + formattedMembers.push([]) + } + formattedMembers.at(-1).push(sortingNode) + } + for (let nodes of formattedMembers) { + function createSortNodesExcludingEslintDisabled(sortingNodes) { + return function (ignoreEslintDisabledNodes) { + return sortNodesByGroups({ + comparatorByOptionsComputer: defaultComparatorByOptionsComputer, + optionsByGroupIndexComputer, + ignoreEslintDisabledNodes, + groups: options.groups, + nodes: sortingNodes, + }) + } + } + reportAllErrors({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + sortNodesExcludingEslintDisabled: + createSortNodesExcludingEslintDisabled(nodes), + options, + context, + nodes, + }) + } +} +export { defaultOptions, sortHeritageClause } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dc4bac52f60cf90d0ec7ca66e49f415a1f08a07f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/types.d.ts @@ -0,0 +1,43 @@ +import { RegexOption, TypeOption } from '../../types/common-options.js' +import { AllCommonOptions } from '../../types/all-common-options.js' +export type MessageId = + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +export declare const ORDER_ERROR_ID = 'unexpectedHeritageClausesOrder' +export declare const GROUP_ORDER_ERROR_ID = + 'unexpectedHeritageClausesGroupOrder' +export declare const EXTRA_SPACING_ERROR_ID = + 'extraSpacingBetweenHeritageClauses' +export declare const MISSED_SPACING_ERROR_ID = + 'missedSpacingBetweenHeritageClauses' +export type Options = Partial< + { + /** + * Conditional configuration based on pattern matching. + */ + useConfigurationIf: { + /** + * Regular expression pattern to match against all heritage clause + * names. The rule is only applied when all names match this pattern. + */ + allNamesMatchPattern?: RegexOption + /** + * AST selector to match against ClassDeclaration or + * TSInterfaceDeclaration nodes. + */ + matchesAstSelector?: string + } + } & AllCommonOptions< + TypeOption, + AdditionalSortOptions, + CustomGroupMatchOptions + > +>[] +/** + * Match options for a custom group. + */ +type CustomGroupMatchOptions = object +type AdditionalSortOptions = object +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/types.js new file mode 100644 index 0000000000000000000000000000000000000000..d7e429a0a73a8bcb372b79a02e2420912df442bb --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-heritage-clauses/types.js @@ -0,0 +1,10 @@ +var ORDER_ERROR_ID = 'unexpectedHeritageClausesOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedHeritageClausesGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenHeritageClauses' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenHeritageClauses' +export { + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ab9300185a833f2d73d8a5872a1725169a351b86 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes.d.ts @@ -0,0 +1,23 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +import { Options } from './sort-import-attributes/types.js' +declare const ORDER_ERROR_ID = 'unexpectedImportAttributesOrder' +declare const GROUP_ORDER_ERROR_ID = 'unexpectedImportAttributesGroupOrder' +declare const EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenImportAttributes' +declare const MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenImportAttributes' +type MessageId = + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +export declare let jsonSchema: JSONSchema4 +declare const _default: import('@typescript-eslint/utils/ts-eslint').RuleModule< + MessageId, + Options, + { + recommended?: boolean + }, + import('@typescript-eslint/utils/ts-eslint').RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes.js new file mode 100644 index 0000000000000000000000000000000000000000..c6b8959f1fb9507157f7ca905fea5e488c3666e2 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes.js @@ -0,0 +1,100 @@ +import { + buildCommonJsonSchemas, + buildUseConfigIfJsonSchema, + matchesAstSelectorJsonSchema, +} from '../utils/json-schemas/common-json-schemas.js' +import { buildCommonGroupsJsonSchemas } from '../utils/json-schemas/common-groups-json-schemas.js' +import { + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { + partitionByCommentJsonSchema, + partitionByNewlineJsonSchema, +} from '../utils/json-schemas/common-partition-json-schemas.js' +import { buildAstListeners } from '../utils/build-ast-listeners.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { sortImportOrExportAttributes } from './sort-import-attributes/sort-import-or-export-attributes.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var ORDER_ERROR_ID = 'unexpectedImportAttributesOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedImportAttributesGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenImportAttributes' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenImportAttributes' +var defaultOptions = { + fallbackSort: { type: 'unsorted' }, + newlinesInside: 'newlinesBetween', + specialCharacters: 'keep', + partitionByComment: false, + partitionByNewLine: false, + newlinesBetween: 'ignore', + useConfigurationIf: {}, + type: 'alphabetical', + ignoreCase: true, + customGroups: [], + locales: 'en-US', + alphabet: '', + order: 'asc', + groups: [], +} +var jsonSchema = { + items: { + properties: { + ...buildCommonJsonSchemas(), + ...buildCommonGroupsJsonSchemas(), + useConfigurationIf: buildUseConfigIfJsonSchema({ + additionalProperties: { + matchesAstSelector: matchesAstSelectorJsonSchema, + }, + }), + partitionByComment: partitionByCommentJsonSchema, + partitionByNewLine: partitionByNewlineJsonSchema, + }, + additionalProperties: false, + type: 'object', + }, + uniqueItems: true, + type: 'array', +} +var sort_import_attributes_default = createEslintRule({ + meta: { + messages: { + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-import-attributes', + description: 'Enforce sorted import attributes.', + recommended: true, + }, + schema: jsonSchema, + type: 'suggestion', + fixable: 'code', + }, + create: context => + buildAstListeners({ + nodeTypes: [AST_NODE_TYPES.ImportDeclaration], + sorter: sortImportAttributes, + context, + }), + defaultOptions: [defaultOptions], + name: 'sort-import-attributes', +}) +function sortImportAttributes({ matchedAstSelectors, context, node }) { + sortImportOrExportAttributes({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + matchedAstSelectors, + defaultOptions, + context, + node, + }) +} +export { sort_import_attributes_default as default, jsonSchema } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/compute-matched-context-options.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/compute-matched-context-options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..74405e8b412ff9489e6502615412a4f4b7c6fc35 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/compute-matched-context-options.d.ts @@ -0,0 +1,26 @@ +import { RuleContext } from '@typescript-eslint/utils/ts-eslint' +import { TSESTree } from '@typescript-eslint/types' +import { Options } from './types.js' +/** + * Computes the matched context options for a given import/export attributes + * node. + * + * @param params - Parameters. + * @param params.matchedAstSelectors - The matched AST selectors for an + * import/export declaration node. + * @param params.attributes - The import attributes to compute the context + * options for. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +export declare function computeMatchedContextOptions< + MessageIds extends string, +>({ + matchedAstSelectors, + attributes, + context, +}: { + context: Readonly> + matchedAstSelectors: ReadonlySet + attributes: TSESTree.ImportAttribute[] +}): Options[number] | undefined diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/compute-matched-context-options.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/compute-matched-context-options.js new file mode 100644 index 0000000000000000000000000000000000000000..d3de27ef997d6cd189022fb4db158102ade00103 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/compute-matched-context-options.js @@ -0,0 +1,47 @@ +import { passesAllNamesMatchPatternFilter } from '../../utils/context-matching/passes-all-names-match-pattern-filter.js' +import { passesAstSelectorFilter } from '../../utils/context-matching/passes-ast-selector-filter.js' +import { computeNodeName } from './compute-node-name.js' +/** + * Computes the matched context options for a given import/export attributes + * node. + * + * @param params - Parameters. + * @param params.matchedAstSelectors - The matched AST selectors for an + * import/export declaration node. + * @param params.attributes - The import attributes to compute the context + * options for. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +function computeMatchedContextOptions({ + matchedAstSelectors, + attributes, + context, +}) { + let nodeNames = attributes.map(attribute => + computeNodeName(attribute, context.sourceCode), + ) + return context.options.find(options => + isContextOptionMatching({ + matchedAstSelectors, + nodeNames, + options, + }), + ) +} +function isContextOptionMatching({ matchedAstSelectors, nodeNames, options }) { + if (!options.useConfigurationIf) { + return true + } + return ( + passesAllNamesMatchPatternFilter({ + allNamesMatchPattern: options.useConfigurationIf.allNamesMatchPattern, + nodeNames, + }) && + passesAstSelectorFilter({ + matchesAstSelector: options.useConfigurationIf.matchesAstSelector, + matchedAstSelectors, + }) + ) +} +export { computeMatchedContextOptions } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/compute-node-name.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/compute-node-name.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c6a2c58006c80788bab8be3f02872f3d1ac272a0 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/compute-node-name.d.ts @@ -0,0 +1,16 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { TSESTree } from '@typescript-eslint/types' +/** + * Extracts the name of an import attribute for sorting purposes. + * + * For identifier keys, returns the identifier name. For literal keys, returns + * the string value. Falls back to source code text if needed. + * + * @param attribute - The import attribute AST node. + * @param sourceCode - The ESLint source code object. + * @returns The attribute name to use for sorting. + */ +export declare function computeNodeName( + attribute: TSESTree.ImportAttribute, + sourceCode: TSESLint.SourceCode, +): string diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/compute-node-name.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/compute-node-name.js new file mode 100644 index 0000000000000000000000000000000000000000..9c8a989e4005378ebd815f12f4f567add29c7d88 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/compute-node-name.js @@ -0,0 +1,25 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Extracts the name of an import attribute for sorting purposes. + * + * For identifier keys, returns the identifier name. For literal keys, returns + * the string value. Falls back to source code text if needed. + * + * @param attribute - The import attribute AST node. + * @param sourceCode - The ESLint source code object. + * @returns The attribute name to use for sorting. + */ +function computeNodeName(attribute, sourceCode) { + let { key } = attribute + switch (key.type) { + case AST_NODE_TYPES.Identifier: + return key.name + case AST_NODE_TYPES.Literal: + return key.value?.toString() ?? sourceCode.getText(attribute) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(key) + } +} +export { computeNodeName } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/sort-import-or-export-attributes.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/sort-import-or-export-attributes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd48f205cfc299dc7cfc5eee61cf7a9cb26e8625 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/sort-import-or-export-attributes.d.ts @@ -0,0 +1,23 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +import { Options } from './types.js' +export declare function sortImportOrExportAttributes< + MessageIds extends string, +>({ + matchedAstSelectors, + availableMessageIds, + defaultOptions, + context, + node, +}: { + availableMessageIds: { + missedSpacingBetweenMembers: MessageIds + extraSpacingBetweenMembers: MessageIds + unexpectedGroupOrder: MessageIds + unexpectedOrder: MessageIds + } + node: TSESTree.ExportNamedDeclaration | TSESTree.ImportDeclaration + context: TSESLint.RuleContext + defaultOptions: Required + matchedAstSelectors: ReadonlySet +}): void diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/sort-import-or-export-attributes.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/sort-import-or-export-attributes.js new file mode 100644 index 0000000000000000000000000000000000000000..7ddf21448578bc5e3dcb254bdd3dc76dfe21f7a5 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/sort-import-or-export-attributes.js @@ -0,0 +1,109 @@ +import { defaultComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +import { validateNewlinesAndPartitionConfig } from '../../utils/validate-newlines-and-partition-config.js' +import { buildOptionsByGroupIndexComputer } from '../../utils/build-options-by-group-index-computer.js' +import { validateCustomSortConfig } from '../../utils/validate-custom-sort-config.js' +import { getEslintDisabledLines } from '../../utils/get-eslint-disabled-lines.js' +import { doesCustomGroupMatch } from '../../utils/does-custom-group-match.js' +import { isNodeEslintDisabled } from '../../utils/is-node-eslint-disabled.js' +import { validateGroupsConfig } from '../../utils/validate-groups-config.js' +import { sortNodesByGroups } from '../../utils/sort-nodes-by-groups.js' +import { reportAllErrors } from '../../utils/report-all-errors.js' +import { shouldPartition } from '../../utils/should-partition.js' +import { computeGroup } from '../../utils/compute-group.js' +import { rangeToDiff } from '../../utils/range-to-diff.js' +import { getSettings } from '../../utils/get-settings.js' +import { isSortable } from '../../utils/is-sortable.js' +import { complete } from '../../utils/complete.js' +import { computeNodeName } from './compute-node-name.js' +import { computeMatchedContextOptions } from './compute-matched-context-options.js' +function sortImportOrExportAttributes({ + matchedAstSelectors, + availableMessageIds, + defaultOptions, + context, + node, +}) { + let attributes = node.attributes + if (!isSortable(attributes)) { + return + } + let { sourceCode, id } = context + let settings = getSettings(context.settings) + let matchedContextOptions = computeMatchedContextOptions({ + matchedAstSelectors, + attributes, + context, + }) + let options = complete(matchedContextOptions, settings, defaultOptions) + validateCustomSortConfig(options) + validateGroupsConfig({ + selectors: [], + modifiers: [], + options, + }) + validateNewlinesAndPartitionConfig(options) + let eslintDisabledLines = getEslintDisabledLines({ + ruleName: id, + sourceCode, + }) + let optionsByGroupIndexComputer = buildOptionsByGroupIndexComputer(options) + let formattedMembers = [[]] + for (let attribute of attributes) { + let name = computeNodeName(attribute, sourceCode) + let group = computeGroup({ + customGroupMatcher: customGroup => + doesCustomGroupMatch({ + elementName: name, + selectors: [], + modifiers: [], + customGroup, + }), + predefinedGroups: [], + options, + }) + let sortingNode = { + isEslintDisabled: isNodeEslintDisabled(attribute, eslintDisabledLines), + size: rangeToDiff(attribute, sourceCode), + node: attribute, + group, + name, + } + let lastSortingNode = formattedMembers.at(-1)?.at(-1) + if ( + shouldPartition({ + lastSortingNode, + sortingNode, + sourceCode, + options, + }) + ) { + formattedMembers.push([]) + } + formattedMembers.at(-1).push({ + ...sortingNode, + partitionId: formattedMembers.length, + }) + } + for (let nodes of formattedMembers) { + function createSortNodesExcludingEslintDisabled(sortingNodes) { + return function (ignoreEslintDisabledNodes) { + return sortNodesByGroups({ + comparatorByOptionsComputer: defaultComparatorByOptionsComputer, + optionsByGroupIndexComputer, + ignoreEslintDisabledNodes, + groups: options.groups, + nodes: sortingNodes, + }) + } + } + reportAllErrors({ + sortNodesExcludingEslintDisabled: + createSortNodesExcludingEslintDisabled(nodes), + availableMessageIds, + options, + context, + nodes, + }) + } +} +export { sortImportOrExportAttributes } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..23cb9d0b58e9ac9505a503c56c26a91026fc78a7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-import-attributes/types.d.ts @@ -0,0 +1,35 @@ +import { TSESTree } from '@typescript-eslint/types' +import { RegexOption, TypeOption } from '../../types/common-options.js' +import { AllCommonOptions } from '../../types/all-common-options.js' +import { SortingNode } from '../../types/sorting-node.js' +export type Options = Partial< + { + /** + * Conditional configuration based on pattern matching. + */ + useConfigurationIf: { + /** + * Regular expression pattern to match against all attribute key names. + * The rule is only applied when all names match this pattern. + */ + allNamesMatchPattern?: RegexOption + /** + * AST selector to match against ImportDeclaration or + * ExportNamedDeclaration nodes. + */ + matchesAstSelector?: string + } + } & AllCommonOptions< + TypeOption, + AdditionalSortOptions, + CustomGroupMatchOptions + > +>[] +export type SortImportAttributesSortingNode = + SortingNode +/** + * Match options for a custom group. + */ +type CustomGroupMatchOptions = object +type AdditionalSortOptions = object +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a56387515c322d5d8b34e7fabc3ae3b94a0633ae --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports.d.ts @@ -0,0 +1,26 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { Options } from './sort-imports/types.js' +declare const ORDER_ERROR_ID = 'unexpectedImportsOrder' +declare const GROUP_ORDER_ERROR_ID = 'unexpectedImportsGroupOrder' +declare const EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenImports' +declare const MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenImports' +declare const MISSED_COMMENT_ABOVE_ERROR_ID = 'missedCommentAboveImport' +declare const DEPENDENCY_ORDER_ERROR_ID = 'unexpectedImportsDependencyOrder' +export type MessageId = + | typeof MISSED_COMMENT_ABOVE_ERROR_ID + | typeof DEPENDENCY_ORDER_ERROR_ID + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +declare const _default: TSESLint.RuleModule< + MessageId, + Options, + { + recommended?: boolean + }, + TSESLint.RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports.js new file mode 100644 index 0000000000000000000000000000000000000000..1b827e2f8876a0be9eb901edcecabd59216c592a --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports.js @@ -0,0 +1,460 @@ +import { + buildCommonJsonSchemas, + buildRegexJsonSchema, + useExperimentalDependencyDetectionJsonSchema, +} from '../utils/json-schemas/common-json-schemas.js' +import { buildCommonGroupsJsonSchemas } from '../utils/json-schemas/common-groups-json-schemas.js' +import { + DEPENDENCY_ORDER_ERROR, + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_COMMENT_ABOVE_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { + partitionByCommentJsonSchema, + partitionByNewlineJsonSchema, +} from '../utils/json-schemas/common-partition-json-schemas.js' +import { computeDependenciesBySortingNode } from '../utils/compute-dependencies-by-sorting-node.js' +import { populateSortingNodeGroupsWithDependencies } from '../utils/populate-sorting-node-groups-with-dependencies.js' +import { validateNewlinesAndPartitionConfig } from '../utils/validate-newlines-and-partition-config.js' +import { buildOptionsByGroupIndexComputer } from '../utils/build-options-by-group-index-computer.js' +import { validateCustomSortConfig } from '../utils/validate-custom-sort-config.js' +import { generatePredefinedGroups } from '../utils/generate-predefined-groups.js' +import { sortNodesByDependencies } from '../utils/sort-nodes-by-dependencies.js' +import { getEslintDisabledLines } from '../utils/get-eslint-disabled-lines.js' +import { doesCustomGroupMatch } from '../utils/does-custom-group-match.js' +import { isNodeEslintDisabled } from '../utils/is-node-eslint-disabled.js' +import { validateGroupsConfig } from '../utils/validate-groups-config.js' +import { sortNodesByGroups } from '../utils/sort-nodes-by-groups.js' +import { reportAllErrors } from '../utils/report-all-errors.js' +import { shouldPartition } from '../utils/should-partition.js' +import { computeGroup } from '../utils/compute-group.js' +import { rangeToDiff } from '../utils/range-to-diff.js' +import { getSettings } from '../utils/get-settings.js' +import { isSortable } from '../utils/is-sortable.js' +import { complete } from '../utils/complete.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { isNodeOnSingleLine } from '../utils/is-node-on-single-line.js' +import { + TYPE_IMPORT_FIRST_TYPE_OPTION, + additionalCustomGroupMatchOptionsJsonSchema, + additionalSortOptionsJsonSchema, + allModifiers, + allSelectors, +} from './sort-imports/types.js' +import { isNonExternalReferenceTsImportEquals } from './sort-imports/is-non-external-reference-ts-import-equals.js' +import { comparatorByOptionsComputer } from './sort-imports/comparator-by-options-computer.js' +import { readClosestTsConfigByPath } from './sort-imports/read-closest-ts-config-by-path.js' +import { isSideEffectOnlyGroup } from './sort-imports/is-side-effect-only-group.js' +import { validateSideEffectsConfig } from './sort-imports/validate-side-effects-config.js' +import { computeSpecifierModifiers } from './sort-imports/compute-specifier-modifiers.js' +import { getOptionsWithCleanGroups } from '../utils/get-options-with-clean-groups.js' +import { computeCommonSelectors } from './sort-imports/compute-common-selectors.js' +import { computeDependencyNames } from './sort-imports/compute-dependency-names.js' +import { computeSpecifierName } from './sort-imports/compute-specifier-name.js' +import { computeDependencies } from './sort-imports/compute-dependencies.js' +import { isSideEffectImport } from './sort-imports/is-side-effect-import.js' +import { computeNodeName } from './sort-imports/compute-node-name.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Cache computed groups by modifiers and selectors for performance. + */ +var cachedGroupsByModifiersAndSelectors = /* @__PURE__ */ new Map() +var ORDER_ERROR_ID = 'unexpectedImportsOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedImportsGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenImports' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenImports' +var MISSED_COMMENT_ABOVE_ERROR_ID = 'missedCommentAboveImport' +var DEPENDENCY_ORDER_ERROR_ID = 'unexpectedImportsDependencyOrder' +var defaultOptions = { + groups: [ + 'type-import', + ['value-builtin', 'value-external'], + 'type-internal', + 'value-internal', + ['type-parent', 'type-sibling', 'type-index'], + ['value-parent', 'value-sibling', 'value-index'], + 'ts-equals-import', + 'unknown', + ], + internalPattern: ['^~/.+', '^@/.+', '^#.+'], + useExperimentalDependencyDetection: true, + fallbackSort: { type: 'unsorted' }, + partitionByComment: false, + partitionByNewLine: false, + specialCharacters: 'keep', + tsconfig: { rootDir: '' }, + maxLineLength: Infinity, + sortSideEffects: false, + type: 'alphabetical', + environment: 'node', + newlinesBetween: 1, + newlinesInside: 0, + customGroups: [], + ignoreCase: true, + locales: 'en-US', + sortBy: 'path', + alphabet: '', + order: 'asc', +} +var sort_imports_default = createEslintRule({ + create: context => { + let settings = getSettings(context.settings) + let userOptions = context.options.at(0) + let options = getOptionsWithCleanGroups( + complete(userOptions, settings, defaultOptions), + ) + validateGroupsConfig({ + selectors: allSelectors, + modifiers: allModifiers, + options, + }) + validateCustomSortConfig(options) + validateNewlinesAndPartitionConfig(options) + validateSideEffectsConfig(options) + let tsconfigRootDirectory = options.tsconfig.rootDir + let tsConfigOutput = + tsconfigRootDirectory ? + readClosestTsConfigByPath({ + tsconfigFilename: options.tsconfig.filename ?? 'tsconfig.json', + tsconfigRootDir: tsconfigRootDirectory, + filePath: context.physicalFilename, + contextCwd: context.cwd, + }) + : null + let { sourceCode, filename, id } = context + let eslintDisabledLines = getEslintDisabledLines({ + ruleName: id, + sourceCode, + }) + let sortingNodesWithoutPartitionId = [] + let flatGroups = new Set(options.groups.flat()) + let shouldRegroupSideEffectNodes = flatGroups.has('side-effect') + let shouldRegroupSideEffectStyleNodes = flatGroups.has('side-effect-style') + function registerNode(node) { + let name = computeNodeName({ + sourceCode, + node, + }) + let commonSelectors = computeCommonSelectors({ + tsConfigOutput, + filename, + options, + name, + }) + let selectors = [] + let modifiers = [] + let group = null + if ( + node.type !== AST_NODE_TYPES.VariableDeclaration && + node.importKind === 'type' + ) { + selectors.push('type') + modifiers.push('type') + } + let isSideEffect = isSideEffectImport({ + sourceCode, + node, + }) + let isStyleValue = isStyle(name) + let isStyleSideEffect = isSideEffect && isStyleValue + if (!isNonExternalReferenceTsImportEquals(node)) { + if (isStyleSideEffect) { + selectors.push('side-effect-style') + } + if (isSideEffect) { + selectors.push('side-effect') + modifiers.push('side-effect') + } + if (isStyleValue) { + selectors.push('style') + } + for (let selector of commonSelectors) { + selectors.push(selector) + } + } + selectors.push('import') + if (!modifiers.includes('type')) { + modifiers.push('value') + } + if (node.type === AST_NODE_TYPES.TSImportEqualsDeclaration) { + modifiers.push('ts-equals') + } + if (node.type === AST_NODE_TYPES.VariableDeclaration) { + modifiers.push('require') + } + modifiers.push(...computeSpecifierModifiers(node)) + if (isNodeOnSingleLine(node)) { + modifiers.push('singleline') + } else { + modifiers.push('multiline') + } + group ??= + computeGroupExceptUnknown({ + selectors, + modifiers, + options, + name, + }) ?? 'unknown' + let hasMultipleImportDeclarations = + node.type === AST_NODE_TYPES.ImportDeclaration && + isSortable(node.specifiers) + let size = rangeToDiff(node, sourceCode) + if (hasMultipleImportDeclarations && size > options.maxLineLength) { + size = name.length + 10 + } + sortingNodesWithoutPartitionId.push({ + isIgnored: + !options.sortSideEffects && + isSideEffect && + !shouldRegroupSideEffectNodes && + (!isStyleSideEffect || !shouldRegroupSideEffectStyleNodes), + dependencies: + options.useExperimentalDependencyDetection ? + [] + : computeDependencies(node), + isEslintDisabled: isNodeEslintDisabled(node, eslintDisabledLines), + dependencyNames: computeDependencyNames({ + sourceCode, + node, + }), + specifierName: computeSpecifierName({ + sourceCode, + node, + }), + isTypeImport: modifiers.includes('type'), + addSafetySemicolonWhenInline: true, + group, + size, + name, + node, + }) + } + return { + VariableDeclaration: node => { + if ( + node.declarations[0].init?.type === AST_NODE_TYPES.CallExpression && + node.declarations[0].init.callee.type === AST_NODE_TYPES.Identifier && + node.declarations[0].init.callee.name === 'require' && + node.declarations[0].init.arguments[0]?.type === + AST_NODE_TYPES.Literal + ) { + registerNode(node) + } + }, + 'Program:exit': () => { + sortImportNodes({ + sortingNodesWithoutPartitionId, + context, + options, + }) + }, + TSImportEqualsDeclaration: registerNode, + ImportDeclaration: registerNode, + } + }, + meta: { + schema: { + items: { + properties: { + ...buildCommonJsonSchemas({ + allowedAdditionalTypeValues: [TYPE_IMPORT_FIRST_TYPE_OPTION], + additionalSortProperties: additionalSortOptionsJsonSchema, + }), + ...buildCommonGroupsJsonSchemas({ + additionalCustomGroupMatchProperties: + additionalCustomGroupMatchOptionsJsonSchema, + allowedAdditionalTypeValues: [TYPE_IMPORT_FIRST_TYPE_OPTION], + additionalSortProperties: additionalSortOptionsJsonSchema, + }), + tsconfig: { + properties: { + rootDir: { + description: 'Specifies the tsConfig root directory.', + type: 'string', + }, + filename: { + description: 'Specifies the tsConfig filename.', + type: 'string', + }, + }, + additionalProperties: false, + required: ['rootDir'], + type: 'object', + }, + maxLineLength: { + description: 'Specifies the maximum line length.', + exclusiveMinimum: true, + type: 'integer', + minimum: 0, + }, + sortSideEffects: { + description: + 'Controls whether side-effect imports should be sorted.', + type: 'boolean', + }, + environment: { + description: 'Specifies the environment.', + enum: ['node', 'bun'], + type: 'string', + }, + useExperimentalDependencyDetection: + useExperimentalDependencyDetectionJsonSchema, + partitionByComment: partitionByCommentJsonSchema, + partitionByNewLine: partitionByNewlineJsonSchema, + internalPattern: buildRegexJsonSchema(), + }, + additionalProperties: false, + type: 'object', + }, + uniqueItems: true, + type: 'array', + }, + messages: { + [MISSED_COMMENT_ABOVE_ERROR_ID]: MISSED_COMMENT_ABOVE_ERROR, + [DEPENDENCY_ORDER_ERROR_ID]: DEPENDENCY_ORDER_ERROR, + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-imports', + description: 'Enforce sorted imports.', + recommended: true, + }, + type: 'suggestion', + fixable: 'code', + }, + defaultOptions: [defaultOptions], + name: 'sort-imports', +}) +function sortImportNodes({ sortingNodesWithoutPartitionId, options, context }) { + let { sourceCode } = context + let optionsByGroupIndexComputer = buildOptionsByGroupIndexComputer(options) + let contentSeparatedSortingNodeGroups = [[[]]] + for (let sortingNodeWithoutPartitionId of sortingNodesWithoutPartitionId) { + let lastGroupWithNoContentBetween = contentSeparatedSortingNodeGroups.at(-1) + let lastGroup = lastGroupWithNoContentBetween.at(-1) + let lastSortingNode = lastGroup.at(-1) + if ( + lastSortingNode && + hasContentBetweenNodes(lastSortingNode, sortingNodeWithoutPartitionId) + ) { + lastGroup = [] + lastGroupWithNoContentBetween = [lastGroup] + contentSeparatedSortingNodeGroups.push(lastGroupWithNoContentBetween) + } else if ( + shouldPartition({ + sortingNode: sortingNodeWithoutPartitionId, + lastSortingNode, + sourceCode, + options, + }) + ) { + lastGroup = [] + lastGroupWithNoContentBetween.push(lastGroup) + } + lastGroup.push({ + ...sortingNodeWithoutPartitionId, + partitionId: lastGroupWithNoContentBetween.length, + }) + } + for (let contentSeparatedSortingNodeGroup of contentSeparatedSortingNodeGroups) { + let sortingNodeGroups = [...contentSeparatedSortingNodeGroup] + if (options.useExperimentalDependencyDetection) { + let dependenciesBySortingNode = computeDependenciesBySortingNode({ + sortingNodes: sortingNodeGroups.flat(), + sourceCode, + }) + sortingNodeGroups = populateSortingNodeGroupsWithDependencies({ + dependenciesBySortingNode, + sortingNodeGroups, + }) + } + let sortingNodes = sortingNodeGroups.flat() + reportAllErrors({ + availableMessageIds: { + unexpectedDependencyOrder: DEPENDENCY_ORDER_ERROR_ID, + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + missedCommentAbove: MISSED_COMMENT_ABOVE_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + sortNodesExcludingEslintDisabled: + createSortNodesExcludingEslintDisabled(sortingNodeGroups), + nodes: sortingNodes, + options, + context, + }) + } + function createSortNodesExcludingEslintDisabled(nodeGroups) { + return function (ignoreEslintDisabledNodes) { + let nodesSortedByGroups = nodeGroups.flatMap(nodes => + sortNodesByGroups({ + isNodeIgnoredForGroup: ({ groupIndex }) => { + if (options.sortSideEffects) { + return false + } + return isSideEffectOnlyGroup(options.groups[groupIndex]) + }, + isNodeIgnored: node => node.isIgnored, + optionsByGroupIndexComputer, + comparatorByOptionsComputer, + ignoreEslintDisabledNodes, + groups: options.groups, + nodes, + }), + ) + return sortNodesByDependencies(nodesSortedByGroups, { + ignoreEslintDisabledNodes, + }) + } + } + function hasContentBetweenNodes(left, right) { + return ( + sourceCode.getTokensBetween(left.node, right.node, { + includeComments: false, + }).length > 0 + ) + } +} +function computeGroupExceptUnknown({ selectors, modifiers, options, name }) { + let predefinedGroups = generatePredefinedGroups({ + cache: cachedGroupsByModifiersAndSelectors, + selectors, + modifiers, + }) + let computedCustomGroup = computeGroup({ + customGroupMatcher: customGroup => + doesCustomGroupMatch({ + elementName: name, + customGroup, + modifiers, + selectors, + }), + predefinedGroups, + options, + }) + if (computedCustomGroup === 'unknown') { + return null + } + return computedCustomGroup +} +var styleExtensions = [ + '.less', + '.scss', + '.sass', + '.styl', + '.pcss', + '.css', + '.sss', +] +function isStyle(value) { + let [cleanedValue] = value.split('?', 1) + return styleExtensions.some(extension => cleanedValue?.endsWith(extension)) +} +export { sort_imports_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/comparator-by-options-computer.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/comparator-by-options-computer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a7a84958fa291689f03c77ef162dc656e166b56c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/comparator-by-options-computer.d.ts @@ -0,0 +1,6 @@ +import { ComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +import { SortImportsSortingNode, Options } from './types.js' +export declare let comparatorByOptionsComputer: ComparatorByOptionsComputer< + Required, + SortImportsSortingNode +> diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/comparator-by-options-computer.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/comparator-by-options-computer.js new file mode 100644 index 0000000000000000000000000000000000000000..368f3296a5f6b8a9ce44d78a4cc482ff17fa595f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/comparator-by-options-computer.js @@ -0,0 +1,90 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { computeOrderedValue } from '../../utils/compare/compute-ordered-value.js' +import { buildLineLengthComparator } from '../../utils/compare/build-line-length-comparator.js' +import { compareAlphabetically } from '../../utils/compare/compare-alphabetically.js' +import { compareByCustomSort } from '../../utils/compare/compare-by-custom-sort.js' +import { unsortedComparator } from '../../utils/compare/unsorted-comparator.js' +import { compareNaturally } from '../../utils/compare/compare-naturally.js' +import { defaultComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +var comparatorByOptionsComputer = options => { + switch (options.type) { + case 'type-import-first': + return (a, b) => compareTypeImportFirst(a, b, options) + case 'subgroup-order': + case 'alphabetical': + case 'line-length': + case 'unsorted': + case 'natural': + case 'custom': + switch (options.sortBy) { + case 'specifier': + return bySpecifierComparatorByOptionsComputer({ + ...options, + type: options.type, + }) + case 'path': + return defaultComparatorByOptionsComputer({ + ...options, + type: options.type, + }) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(options.sortBy) + } + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(options.type) + } +} +/** + * Compares two import nodes to sort type imports before regular imports. + * + * When both nodes are type imports or both are regular imports, returns 0 + * (equal). Otherwise, sorts type imports first based on the order option. + * + * @param a - The first import sorting node. + * @param b - The second import sorting node. + * @param options - Options containing the sort order. + * @returns A negative number if a should come first, positive if b should. + */ +function compareTypeImportFirst(a, b, options) { + if (a.isTypeImport && b.isTypeImport) { + return 0 + } + if (!a.isTypeImport && !b.isTypeImport) { + return 0 + } + return computeOrderedValue(a.isTypeImport ? -1 : 1, options.order) +} +var bySpecifierComparatorByOptionsComputer = options => { + switch (options.type) { + /* v8 ignore next 2 -- @preserve Untested for now as not a relevant sort for this rule. */ + case 'subgroup-order': + return defaultComparatorByOptionsComputer(options) + case 'alphabetical': + return (a, b) => + compareAlphabetically( + a.specifierName ?? '', + b.specifierName ?? '', + options, + ) + case 'line-length': + return buildLineLengthComparator(options) + case 'unsorted': + return unsortedComparator + case 'natural': + return (a, b) => + compareNaturally(a.specifierName ?? '', b.specifierName ?? '', options) + case 'custom': + return (a, b) => + compareByCustomSort( + a.specifierName ?? '', + b.specifierName ?? '', + options, + ) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(options.type) + } +} +export { comparatorByOptionsComputer } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-common-selectors.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-common-selectors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..77d1911b61d71e1731fdf4a717d36054166dc171 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-common-selectors.d.ts @@ -0,0 +1,52 @@ +import { ReadClosestTsConfigByPathValue } from './read-closest-ts-config-by-path.js' +import { RegexOption } from '../../types/common-options.js' +import { Selector } from './types.js' +/** + * Common import selector types that categorize imports by their + * characteristics. + * + * These selectors are used to identify and group imports based on their module + * path patterns and resolution characteristics. + */ +type CommonSelector = Extract< + Selector, + | 'tsconfig-path' + | 'internal' + | 'external' + | 'sibling' + | 'builtin' + | 'subpath' + | 'parent' + | 'index' +> +/** + * Computes all applicable selectors for an import based on its module path. + * + * Analyzes an import's module specifier to determine which categories it + * belongs to, such as external package, internal module, relative import, or + * Node.js builtin. These selectors are used for grouping and sorting imports + * according to user configuration. + * + * @param options - Configuration options. + * @param options.tsConfigOutput - TypeScript configuration for path resolution. + * @param options.filename - Current file path for relative import resolution. + * @param options.options - Rule options including internal patterns and + * environment. + * @param options.name - Import module specifier to analyze. + * @returns Array of matching selectors for the import. + */ +export declare function computeCommonSelectors({ + tsConfigOutput, + filename, + options, + name, +}: { + options: { + internalPattern: RegexOption[] + environment: 'node' | 'bun' + } + tsConfigOutput: ReadClosestTsConfigByPathValue | null + filename: string + name: string +}): CommonSelector[] +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-common-selectors.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-common-selectors.js new file mode 100644 index 0000000000000000000000000000000000000000..d83b3b04809652b31e9a6bdfc016cda0b95b47be --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-common-selectors.js @@ -0,0 +1,200 @@ +import { matches } from '../../utils/matches.js' +import { getTypescriptImport } from './get-typescript-import.js' +import { matchesTsconfigPaths } from './matches-tsconfig-paths.js' +import { builtinModules } from 'node:module' +/** + * Computes all applicable selectors for an import based on its module path. + * + * Analyzes an import's module specifier to determine which categories it + * belongs to, such as external package, internal module, relative import, or + * Node.js builtin. These selectors are used for grouping and sorting imports + * according to user configuration. + * + * @param options - Configuration options. + * @param options.tsConfigOutput - TypeScript configuration for path resolution. + * @param options.filename - Current file path for relative import resolution. + * @param options.options - Rule options including internal patterns and + * environment. + * @param options.name - Import module specifier to analyze. + * @returns Array of matching selectors for the import. + */ +function computeCommonSelectors({ tsConfigOutput, filename, options, name }) { + function matchesInternalPattern(value) { + return options.internalPattern.some(pattern => matches(value, pattern)) + } + let internalExternalGroup = + matchesInternalPattern(name) ? 'internal' : ( + getInternalOrExternalGroup({ + tsConfigOutput, + filename, + name, + }) + ) + let commonSelectors = [] + if ( + tsConfigOutput && + matchesTsconfigPaths({ + tsConfigOutput, + name, + }) + ) { + commonSelectors.push('tsconfig-path') + } + if (isIndex(name)) { + commonSelectors.push('index') + } + if (isSibling(name)) { + commonSelectors.push('sibling') + } + if (isParent(name)) { + commonSelectors.push('parent') + } + if (isSubpath(name)) { + commonSelectors.push('subpath') + } + if (internalExternalGroup === 'internal') { + commonSelectors.push('internal') + } + if (isCoreModule(name, options.environment)) { + commonSelectors.push('builtin') + } + if (internalExternalGroup === 'external') { + commonSelectors.push('external') + } + return commonSelectors +} +var bunModules = /* @__PURE__ */ new Set([ + 'detect-libc', + 'bun:sqlite', + 'bun:test', + 'bun:wrap', + 'bun:ffi', + 'bun:jsc', + 'undici', + 'bun', + 'ws', +]) +var nodeBuiltinModules = new Set(builtinModules) +var builtinPrefixOnlyModules = /* @__PURE__ */ new Set([ + 'node:sqlite', + 'node:test', + 'node:sea', +]) +/** + * Determines whether an import is internal or external to the project. + * + * Uses TypeScript's module resolution to accurately classify imports based on + * whether they resolve to external libraries (node_modules) or internal project + * files. Falls back to path-based heuristics when TypeScript is unavailable. + * + * @param options - Options for determining the group. + * @param options.tsConfigOutput - TypeScript configuration for module + * resolution. + * @param options.filename - Current file path for resolution context. + * @param options.name - Import module specifier to classify. + * @returns 'internal' for project modules, 'external' for dependencies, null + * for relative imports. + */ +function getInternalOrExternalGroup({ tsConfigOutput, filename, name }) { + let typescriptImport = getTypescriptImport() + if (!typescriptImport) { + return !name.startsWith('.') && !name.startsWith('/') ? 'external' : null + } + if (typescriptImport.isExternalModuleNameRelative(name)) { + return null + } + if (!tsConfigOutput) { + return 'external' + } + let resolution = typescriptImport.resolveModuleName( + name, + filename, + tsConfigOutput.compilerOptions, + typescriptImport.sys, + tsConfigOutput.cache, + ) + if (typeof resolution.resolvedModule?.isExternalLibraryImport !== 'boolean') { + return 'external' + } + return resolution.resolvedModule.isExternalLibraryImport ? + 'external' + : 'internal' +} +/** + * Checks if a module is a Node.js or Bun builtin module. + * + * Handles various formats including 'node:' prefixed modules and subpath + * imports (e.g., 'fs/promises'). Also supports Bun-specific modules when in Bun + * environment. + * + * @param value - Module specifier to check. + * @param environment - Runtime environment ('node' or 'bun'). + * @returns True if the module is a builtin module. + */ +function isCoreModule(value, environment) { + function clean(string_) { + return string_.replace(/^(?:node:){1,2}/u, '') + } + let [basePath] = value.split('/', 1) + let cleanValue = clean(value) + let cleanBase = clean(basePath) + if (nodeBuiltinModules.has(cleanValue) || nodeBuiltinModules.has(cleanBase)) { + return true + } + if ( + builtinPrefixOnlyModules.has(value) || + builtinPrefixOnlyModules.has(`node:${cleanValue}`) || + builtinPrefixOnlyModules.has(basePath) || + builtinPrefixOnlyModules.has(`node:${cleanBase}`) + ) { + return true + } + return environment === 'bun' && bunModules.has(value) +} +/** + * Checks if an import is an index file import. + * + * @param value - Import path to check. + * @returns True if importing an index file. + */ +function isIndex(value) { + return [ + './index.d.js', + './index.d.ts', + './index.js', + './index.ts', + './index', + './', + '.', + ].includes(value) +} +/** + * Checks if an import is a sibling module (same directory). + * + * @param value - Import path to check. + * @returns True if importing from the same directory. + */ +function isSibling(value) { + return value.startsWith('./') +} +/** + * Checks if an import is from a parent directory. + * + * @param value - Import path to check. + * @returns True if importing from a parent directory. + */ +function isParent(value) { + return value.startsWith('..') +} +/** + * Checks if an import is a Node.js subpath import. + * + * Subpath imports start with '#' and are defined in package.json imports field. + * + * @param value - Import path to check. + * @returns True if using subpath import syntax. + */ +function isSubpath(value) { + return value.startsWith('#') +} +export { computeCommonSelectors } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-dependencies.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-dependencies.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0de1066c29de6aa4bddb5b5547147ac9d1c9be15 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-dependencies.d.ts @@ -0,0 +1,10 @@ +import { SortImportsNode } from './types.js' +/** + * Computes the dependencies of an import-like AST node. + * + * @deprecated - To remove when experimental dependency detection is the only + * option. + * @param node - The AST node representing an import-like declaration. + * @returns The names of the dependencies. + */ +export declare function computeDependencies(node: SortImportsNode): string[] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-dependencies.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-dependencies.js new file mode 100644 index 0000000000000000000000000000000000000000..5982968376b8075397b8473b766de1017837b352 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-dependencies.js @@ -0,0 +1,57 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the dependencies of an import-like AST node. + * + * @deprecated - To remove when experimental dependency detection is the only + * option. + * @param node - The AST node representing an import-like declaration. + * @returns The names of the dependencies. + */ +function computeDependencies(node) { + switch (node.type) { + case AST_NODE_TYPES.TSImportEqualsDeclaration: + return computeImportEqualsDeclarationDependencies(node) + case AST_NODE_TYPES.VariableDeclaration: + case AST_NODE_TYPES.ImportDeclaration: + return [] + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(node) + } +} +function computeImportEqualsDeclarationDependencies(node) { + switch (node.moduleReference.type) { + case AST_NODE_TYPES.TSExternalModuleReference: + case AST_NODE_TYPES.Identifier: + return [] + case AST_NODE_TYPES.TSQualifiedName: { + let qualifiedName = getQualifiedNameDependencyName(node.moduleReference) + /* v8 ignore if -- @preserve Unsure how we can reach that case */ + if (!qualifiedName) { + return [] + } + return [qualifiedName] + } + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(node.moduleReference) + } +} +function getQualifiedNameDependencyName(node) { + let currentNode = node + while (currentNode.type === AST_NODE_TYPES.TSQualifiedName) { + currentNode = currentNode.left + } + switch (currentNode.type) { + /* v8 ignore next -- @preserve Unsure how we can reach that case */ + case AST_NODE_TYPES.ThisExpression: + return null + case AST_NODE_TYPES.Identifier: + return currentNode.name + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(currentNode) + } +} +export { computeDependencies } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-dependency-names.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-dependency-names.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd167c4b6038add28a29970c976b092a91caa320 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-dependency-names.d.ts @@ -0,0 +1,17 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { SortImportsNode } from './types.js' +/** + * Computes the dependency names of an import-like AST node. + * + * @param props - The parameters object. + * @param props.sourceCode - ESLint source code object for text extraction. + * @param props.node - The AST node representing an import-like declaration. + * @returns The names of the dependencies. + */ +export declare function computeDependencyNames({ + sourceCode, + node, +}: { + sourceCode: TSESLint.SourceCode + node: SortImportsNode +}): string[] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-dependency-names.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-dependency-names.js new file mode 100644 index 0000000000000000000000000000000000000000..9248e7658dc98b1919b41ed639207d504521d242 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-dependency-names.js @@ -0,0 +1,36 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the dependency names of an import-like AST node. + * + * @param props - The parameters object. + * @param props.sourceCode - ESLint source code object for text extraction. + * @param props.node - The AST node representing an import-like declaration. + * @returns The names of the dependencies. + */ +function computeDependencyNames({ sourceCode, node }) { + switch (node.type) { + case AST_NODE_TYPES.TSImportEqualsDeclaration: + return [node.id.name] + case AST_NODE_TYPES.VariableDeclaration: + return [] + case AST_NODE_TYPES.ImportDeclaration: + return node.specifiers.map(computeImportClauseDependencyName) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(node) + } + function computeImportClauseDependencyName(specifier) { + switch (specifier.type) { + case AST_NODE_TYPES.ImportNamespaceSpecifier: + case AST_NODE_TYPES.ImportDefaultSpecifier: + return sourceCode.getText(specifier.local) + case AST_NODE_TYPES.ImportSpecifier: + return sourceCode.getText(specifier.imported) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(specifier) + } + } +} +export { computeDependencyNames } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-node-name.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-node-name.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..00c63394e3a95f1b77e71639fa89fd58f7064b83 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-node-name.d.ts @@ -0,0 +1,17 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { SortImportsNode } from './types.js' +/** + * Computes the name of an import-like AST node. + * + * @param props - The parameters object. + * @param props.sourceCode - ESLint source code object for text extraction. + * @param props.node - The AST node representing an import-like declaration. + * @returns The name of the import. + */ +export declare function computeNodeName({ + sourceCode, + node, +}: { + sourceCode: TSESLint.SourceCode + node: SortImportsNode +}): string diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-node-name.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-node-name.js new file mode 100644 index 0000000000000000000000000000000000000000..6ca311c474cd4ed6f691b6da4f65eda7c4f55242 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-node-name.js @@ -0,0 +1,38 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the name of an import-like AST node. + * + * @param props - The parameters object. + * @param props.sourceCode - ESLint source code object for text extraction. + * @param props.node - The AST node representing an import-like declaration. + * @returns The name of the import. + */ +function computeNodeName({ sourceCode, node }) { + switch (node.type) { + case AST_NODE_TYPES.TSImportEqualsDeclaration: + return computeImportEqualsDeclarationName(node) + case AST_NODE_TYPES.VariableDeclaration: { + let { value } = node.declarations[0].init.arguments[0] + return value.toString() + } + case AST_NODE_TYPES.ImportDeclaration: + return node.source.value + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(node) + } + function computeImportEqualsDeclarationName(declaration) { + switch (declaration.moduleReference.type) { + case AST_NODE_TYPES.TSExternalModuleReference: + return declaration.moduleReference.expression.value + case AST_NODE_TYPES.TSQualifiedName: + case AST_NODE_TYPES.Identifier: + return sourceCode.getText(declaration.moduleReference) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(declaration.moduleReference) + } + } +} +export { computeNodeName } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-specifier-modifiers.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-specifier-modifiers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..07f69e4247c77969146075c73f068b10c908343b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-specifier-modifiers.d.ts @@ -0,0 +1,12 @@ +import { SortImportsNode } from './types.js' +type Modifier = 'wildcard' | 'default' | 'named' +/** + * Computes the specifier modifiers of an import-like AST node. + * + * @param node - The AST node representing an import-like declaration. + * @returns A list of specifier modifiers. + */ +export declare function computeSpecifierModifiers( + node: SortImportsNode, +): Modifier[] +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-specifier-modifiers.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-specifier-modifiers.js new file mode 100644 index 0000000000000000000000000000000000000000..f948b386b339209406e4f5a3a24f7980fa8cede5 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-specifier-modifiers.js @@ -0,0 +1,31 @@ +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the specifier modifiers of an import-like AST node. + * + * @param node - The AST node representing an import-like declaration. + * @returns A list of specifier modifiers. + */ +function computeSpecifierModifiers(node) { + if (node.type !== AST_NODE_TYPES.ImportDeclaration) { + return [] + } + return computeImportDeclarationModifiers(node) +} +function computeImportDeclarationModifiers(node) { + let importClauses = node.specifiers + return [ + ...(hasSpecifier(importClauses, AST_NODE_TYPES.ImportDefaultSpecifier) ? + ['default'] + : []), + ...(hasSpecifier(importClauses, AST_NODE_TYPES.ImportNamespaceSpecifier) ? + ['wildcard'] + : []), + ...(hasSpecifier(importClauses, AST_NODE_TYPES.ImportSpecifier) ? + ['named'] + : []), + ] +} +function hasSpecifier(importClauses, specifier) { + return importClauses.some(importClause => importClause.type === specifier) +} +export { computeSpecifierModifiers } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-specifier-name.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-specifier-name.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..44429957df1cd21ba519c715c71d95c78c42c049 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-specifier-name.d.ts @@ -0,0 +1,9 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { SortImportsNode } from './types.js' +export declare function computeSpecifierName({ + sourceCode, + node, +}: { + sourceCode: TSESLint.SourceCode + node: SortImportsNode +}): string | null diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-specifier-name.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-specifier-name.js new file mode 100644 index 0000000000000000000000000000000000000000..acb8a82401eed92ee80cbb7ee1a472259d43f7c4 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/compute-specifier-name.js @@ -0,0 +1,64 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +function computeSpecifierName({ sourceCode, node }) { + switch (node.type) { + case AST_NODE_TYPES.TSImportEqualsDeclaration: + return node.id.name + case AST_NODE_TYPES.VariableDeclaration: + return computeVariableDeclarationSpecifierName(node, sourceCode) + case AST_NODE_TYPES.ImportDeclaration: + return computeImportDeclarationSpecifierName(node) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(node) + } +} +function computeVariableDeclarationSpecifierName(node, sourceCode) { + let [declaration] = node.declarations + switch (declaration.id.type) { + case AST_NODE_TYPES.ObjectPattern: + return computeObjectPatternPropertyName(declaration.id.properties[0]) + case AST_NODE_TYPES.ArrayPattern: + if (!declaration.id.elements[0]) { + return null + } + return sourceCode.getText(declaration.id.elements[0]) + case AST_NODE_TYPES.Identifier: + return declaration.id.name + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(declaration.id) + } + function computeObjectPatternPropertyName(property) { + if (!property) { + return null + } + switch (property.type) { + case AST_NODE_TYPES.RestElement: + return sourceCode.getText(property.argument) + case AST_NODE_TYPES.Property: + return sourceCode.getText(property.value) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(property) + } + } +} +function computeImportDeclarationSpecifierName(node) { + let [specifier] = node.specifiers + if (!specifier) { + return null + } + switch (specifier.type) { + case AST_NODE_TYPES.ImportNamespaceSpecifier: + return specifier.local.name + case AST_NODE_TYPES.ImportDefaultSpecifier: + return specifier.local.name + case AST_NODE_TYPES.ImportSpecifier: + return specifier.local.name + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(specifier) + } +} +export { computeSpecifierName } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/get-typescript-import.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/get-typescript-import.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5b0dded5327181e0e6c43de61e1fdd40050aa2d7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/get-typescript-import.d.ts @@ -0,0 +1,20 @@ +import { default as ts } from 'typescript' +declare let requiredTypescriptAttributes: [ + 'createModuleResolutionCache', + 'isExternalModuleNameRelative', + 'parseJsonConfigFileContent', + 'readConfigFile', + 'resolveModuleName', + 'sys', +] +export type TypescriptImport = Pick< + typeof ts, + (typeof requiredTypescriptAttributes)[number] +> +/** + * Dynamically loads the typescript module if it's available and caches it. + * + * @returns The TypeScript module or null if it's not available. + */ +export declare function getTypescriptImport(): TypescriptImport | null +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/get-typescript-import.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/get-typescript-import.js new file mode 100644 index 0000000000000000000000000000000000000000..93d3ba4d446e950373e7ffb0423952e1d935bccb --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/get-typescript-import.js @@ -0,0 +1,48 @@ +import { createRequire } from 'node:module' +/** + * Cached reference to the TypeScript module. + */ +var cachedImport +/** + * Indicates whether an attempt to load the TypeScript module has already been + * made. + */ +var hasTriedLoadingTypescript = false +var requiredTypescriptAttributes = [ + 'createModuleResolutionCache', + 'isExternalModuleNameRelative', + 'parseJsonConfigFileContent', + 'readConfigFile', + 'resolveModuleName', + 'sys', +] +/** + * Dynamically loads the typescript module if it's available and caches it. + * + * @returns The TypeScript module or null if it's not available. + */ +function getTypescriptImport() { + if (cachedImport) { + return cachedImport + } + if (hasTriedLoadingTypescript) { + return null + } + hasTriedLoadingTypescript = true + try { + let tsImport = createRequire(import.meta.url)('typescript') + if (!isSupportedTypescriptVersion(tsImport)) { + return null + } + cachedImport = tsImport + return cachedImport + } catch (_error) { + return null + } +} +function isSupportedTypescriptVersion(typescriptImport) { + return requiredTypescriptAttributes.every(attribute => + Object.hasOwn(typescriptImport, attribute), + ) +} +export { getTypescriptImport } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-non-external-reference-ts-import-equals.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-non-external-reference-ts-import-equals.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6e8a74c30bcc43d93763836a46e6442ec2e64d20 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-non-external-reference-ts-import-equals.d.ts @@ -0,0 +1,13 @@ +import { TSESTree } from '@typescript-eslint/types' +import { SortImportsNode } from './types.js' +/** + * Determines whether the given AST node is a non-external-reference TS import + * equals declaration. + * + * @param node - The AST node representing an import-like declaration. + * @returns True if the node is a non-external-reference TS import equals + * declaration; otherwise, false. + */ +export declare function isNonExternalReferenceTsImportEquals( + node: SortImportsNode, +): node is TSESTree.TSImportEqualsDeclaration diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-non-external-reference-ts-import-equals.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-non-external-reference-ts-import-equals.js new file mode 100644 index 0000000000000000000000000000000000000000..f78378394edc629c2d74b4652e54784ac43ca4aa --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-non-external-reference-ts-import-equals.js @@ -0,0 +1,16 @@ +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Determines whether the given AST node is a non-external-reference TS import + * equals declaration. + * + * @param node - The AST node representing an import-like declaration. + * @returns True if the node is a non-external-reference TS import equals + * declaration; otherwise, false. + */ +function isNonExternalReferenceTsImportEquals(node) { + if (node.type !== AST_NODE_TYPES.TSImportEqualsDeclaration) { + return false + } + return node.moduleReference.type !== AST_NODE_TYPES.TSExternalModuleReference +} +export { isNonExternalReferenceTsImportEquals } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-side-effect-import.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-side-effect-import.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d0f3962a13ede09cf19fe1e7f13baef1b07b6de --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-side-effect-import.d.ts @@ -0,0 +1,17 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { SortImportsNode } from './types.js' +/** + * Determines whether the given AST node is a side-effect import. + * + * @param props - The parameters object. + * @param props.sourceCode - ESLint source code object for text extraction. + * @param props.node - The AST node representing an import-like declaration. + * @returns True if the node is a side-effect import; otherwise, false. + */ +export declare function isSideEffectImport({ + sourceCode, + node, +}: { + sourceCode: TSESLint.SourceCode + node: SortImportsNode +}): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-side-effect-import.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-side-effect-import.js new file mode 100644 index 0000000000000000000000000000000000000000..dbb5f5168d8ecbbdc9706f3904dabe698390439c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-side-effect-import.js @@ -0,0 +1,26 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Determines whether the given AST node is a side-effect import. + * + * @param props - The parameters object. + * @param props.sourceCode - ESLint source code object for text extraction. + * @param props.node - The AST node representing an import-like declaration. + * @returns True if the node is a side-effect import; otherwise, false. + */ +function isSideEffectImport({ sourceCode, node }) { + switch (node.type) { + case AST_NODE_TYPES.TSImportEqualsDeclaration: + case AST_NODE_TYPES.VariableDeclaration: + return false + case AST_NODE_TYPES.ImportDeclaration: + return ( + node.specifiers.length === 0 && + !/\}\s*from\s+/u.test(sourceCode.getText(node)) + ) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(node) + } +} +export { isSideEffectImport } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-side-effect-only-group.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-side-effect-only-group.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..db2bc25f3db42e48fa7b1fe2da9ab12f79d23329 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-side-effect-only-group.d.ts @@ -0,0 +1,14 @@ +import { GroupsOptions } from '../../types/common-groups-options.js' +/** + * Checks if a group is a side-effect-only group. + * + * A side-effect-only group is one that contains no imports or exports, and is + * typically used for modules that only execute code without exporting any + * values. + * + * @param group - The group to check. + * @returns True if the group is a side-effect-only group, false otherwise. + */ +export declare function isSideEffectOnlyGroup( + group: GroupsOptions[0] | undefined, +): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-side-effect-only-group.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-side-effect-only-group.js new file mode 100644 index 0000000000000000000000000000000000000000..121cc4b801d28169f5f8330e19cf70485b3c5430 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-side-effect-only-group.js @@ -0,0 +1,23 @@ +import { computeGroupsNames } from '../../utils/compute-groups-names.js' +import { isStringGroupSideEffectOnlyGroup } from './is-string-group-side-effect-only-group.js' +/** + * Checks if a group is a side-effect-only group. + * + * A side-effect-only group is one that contains no imports or exports, and is + * typically used for modules that only execute code without exporting any + * values. + * + * @param group - The group to check. + * @returns True if the group is a side-effect-only group, false otherwise. + */ +function isSideEffectOnlyGroup(group) { + if (!group) { + return false + } + let groupNames = computeGroupsNames([group]) + if (groupNames.length === 0) { + return false + } + return groupNames.every(isStringGroupSideEffectOnlyGroup) +} +export { isSideEffectOnlyGroup } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-string-group-side-effect-only-group.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-string-group-side-effect-only-group.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..132e78726f141fe74e9b3c1d4b5b93411a00e4c0 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-string-group-side-effect-only-group.d.ts @@ -0,0 +1,12 @@ +/** + * Checks if a group name represents a side-effect-only import group. + * + * Side-effect-only groups are 'side-effect' and 'side-effect-style', which + * contain imports executed only for their side effects without bindings. + * + * @param groupName - The group name to check. + * @returns True if the group is a side-effect-only group. + */ +export declare function isStringGroupSideEffectOnlyGroup( + groupName: string, +): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-string-group-side-effect-only-group.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-string-group-side-effect-only-group.js new file mode 100644 index 0000000000000000000000000000000000000000..3fb552eba0880807f444724bc99188c4f14c31df --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/is-string-group-side-effect-only-group.js @@ -0,0 +1,13 @@ +/** + * Checks if a group name represents a side-effect-only import group. + * + * Side-effect-only groups are 'side-effect' and 'side-effect-style', which + * contain imports executed only for their side effects without bindings. + * + * @param groupName - The group name to check. + * @returns True if the group is a side-effect-only group. + */ +function isStringGroupSideEffectOnlyGroup(groupName) { + return groupName === 'side-effect' || groupName === 'side-effect-style' +} +export { isStringGroupSideEffectOnlyGroup } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/matches-tsconfig-paths.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/matches-tsconfig-paths.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..77e8403c390596c263891a2a0cc3119773affebb --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/matches-tsconfig-paths.d.ts @@ -0,0 +1,20 @@ +import { ReadClosestTsConfigByPathValue } from './read-closest-ts-config-by-path.js' +/** + * Checks if an import matches any of the path mappings in tsconfig.json. + * + * Path mappings allow custom module resolution (e.g., '@/_' → './src/_'). This + * function determines if an import uses such a mapped path. + * + * @param options - Configuration options. + * @param options.tsConfigOutput - Parsed TypeScript configuration with path + * mappings. + * @param options.name - Import module specifier to check. + * @returns True if the import matches a tsconfig path mapping. + */ +export declare function matchesTsconfigPaths({ + tsConfigOutput, + name, +}: { + tsConfigOutput: ReadClosestTsConfigByPathValue + name: string +}): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/matches-tsconfig-paths.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/matches-tsconfig-paths.js new file mode 100644 index 0000000000000000000000000000000000000000..60463ee6ef4fba0d3b0a614927f79c891ebb98b7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/matches-tsconfig-paths.js @@ -0,0 +1,53 @@ +/** + * Cache for compiled regex patterns from tsconfig paths. Avoids recompiling the + * same path patterns repeatedly. + */ +var regexByTsconfigPathCache = /* @__PURE__ */ new Map() +/** + * Checks if an import matches any of the path mappings in tsconfig.json. + * + * Path mappings allow custom module resolution (e.g., '@/_' → './src/_'). This + * function determines if an import uses such a mapped path. + * + * @param options - Configuration options. + * @param options.tsConfigOutput - Parsed TypeScript configuration with path + * mappings. + * @param options.name - Import module specifier to check. + * @returns True if the import matches a tsconfig path mapping. + */ +function matchesTsconfigPaths({ tsConfigOutput, name }) { + if (!tsConfigOutput.compilerOptions.paths) { + return false + } + return Object.keys(tsConfigOutput.compilerOptions.paths).some(key => + getRegexByTsconfigPath(key).test(name), + ) +} +/** + * Converts a tsconfig path pattern into a regular expression. + * + * Handles wildcard patterns (e.g., '@/*' becomes regex that matches + * '@/anything'). Results are cached to avoid recompiling the same patterns. + * + * @param path - TSConfig path pattern with wildcards. + * @returns Compiled regex for matching imports. + */ +function getRegexByTsconfigPath(path) { + let existingRegex = regexByTsconfigPathCache.get(path) + if (existingRegex) { + return existingRegex + } + let regex = new RegExp(`^${escapeRegExp(path).replaceAll('*', '(.+)')}$`) + regexByTsconfigPathCache.set(path, regex) + return regex +} +/** + * Escapes special regex characters in a string. + * + * @param value - String to escape for use in regex. + * @returns Escaped string safe for regex construction. + */ +function escapeRegExp(value) { + return value.replaceAll(/[$+.?[\\\]]/gu, String.raw`\$&`) +} +export { matchesTsconfigPaths } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/read-closest-ts-config-by-path.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/read-closest-ts-config-by-path.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f032e05f6a0e360d92b6ca53fa5143e566717c55 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/read-closest-ts-config-by-path.d.ts @@ -0,0 +1,60 @@ +import { default as ts } from 'typescript' +/** + * Heavily inspired from: + * https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-estree/src/parseSettings/getProjectConfigFiles.ts. + */ +/** + * Parsed TypeScript configuration with compiler options and module resolution + * cache. + */ +export interface ReadClosestTsConfigByPathValue { + /** + * TypeScript compiler options including path mappings and module resolution + * settings. + */ + compilerOptions: ts.CompilerOptions + /** + * Module resolution cache for efficient repeated resolutions. + */ + cache: ts.ModuleResolutionCache +} +/** + * Cache mapping directories to their nearest tsconfig file path. Speeds up + * config resolution for files in the same directory. + */ +export declare let directoryCacheByPath: Map +/** + * Cache mapping file paths to their parsed tsconfig content. Prevents + * re-parsing the same config files multiple times. + */ +export declare let contentCacheByPath: Map< + string, + ReadClosestTsConfigByPathValue +> +/** + * Finds and parses the closest tsconfig.json file in the directory hierarchy. + * + * Searches upward from the file's directory until finding a tsconfig file or + * reaching the configured root directory. Results are cached for performance. + * + * @param options - Configuration options. + * @param options.tsconfigFilename - Name of the config file to search for + * (e.g., 'tsconfig.json'). + * @param options.tsconfigRootDir - Root directory to stop searching at. + * @param options.contextCwd - Current working directory for module resolution. + * @param options.filePath - Path of the file to find config for. + * @returns Parsed TypeScript configuration or null if TypeScript is + * unavailable. + * @throws {Error} If no tsconfig file is found within the root directory. + */ +export declare function readClosestTsConfigByPath({ + tsconfigFilename, + tsconfigRootDir, + contextCwd, + filePath, +}: { + tsconfigFilename: string + tsconfigRootDir: string + contextCwd: string + filePath: string +}): ReadClosestTsConfigByPathValue | null diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/read-closest-ts-config-by-path.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/read-closest-ts-config-by-path.js new file mode 100644 index 0000000000000000000000000000000000000000..06f9ea2133ace296662cb8e3b36b5df59a3d22d2 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/read-closest-ts-config-by-path.js @@ -0,0 +1,108 @@ +import { getTypescriptImport } from './get-typescript-import.js' +import * as path from 'node:path' +import * as fs from 'node:fs' +/** + * Cache mapping directories to their nearest tsconfig file path. Speeds up + * config resolution for files in the same directory. + */ +var directoryCacheByPath = /* @__PURE__ */ new Map() +/** + * Cache mapping file paths to their parsed tsconfig content. Prevents + * re-parsing the same config files multiple times. + */ +var contentCacheByPath = /* @__PURE__ */ new Map() +/** + * Finds and parses the closest tsconfig.json file in the directory hierarchy. + * + * Searches upward from the file's directory until finding a tsconfig file or + * reaching the configured root directory. Results are cached for performance. + * + * @param options - Configuration options. + * @param options.tsconfigFilename - Name of the config file to search for + * (e.g., 'tsconfig.json'). + * @param options.tsconfigRootDir - Root directory to stop searching at. + * @param options.contextCwd - Current working directory for module resolution. + * @param options.filePath - Path of the file to find config for. + * @returns Parsed TypeScript configuration or null if TypeScript is + * unavailable. + * @throws {Error} If no tsconfig file is found within the root directory. + */ +function readClosestTsConfigByPath({ + tsconfigFilename, + tsconfigRootDir, + contextCwd, + filePath, +}) { + let typescriptImport = getTypescriptImport() + if (!typescriptImport) { + return null + } + let directory = path.dirname(filePath) + let checkedDirectories = [directory] + do { + let tsconfigPath = path.join(directory, tsconfigFilename) + let cachedDirectory = directoryCacheByPath.get(directory) + if (!cachedDirectory && fs.existsSync(tsconfigPath)) { + cachedDirectory = tsconfigPath + } + if (cachedDirectory) { + for (let checkedDirectory of checkedDirectories) { + directoryCacheByPath.set(checkedDirectory, cachedDirectory) + } + return getCompilerOptions(typescriptImport, contextCwd, cachedDirectory) + } + directory = path.dirname(directory) + checkedDirectories.push(directory) + } while (directory.length > 1 && directory.length >= tsconfigRootDir.length) + throw new Error( + `Couldn't find any ${tsconfigFilename} relative to '${filePath}' within '${tsconfigRootDir}'.`, + ) +} +/** + * Parses a TypeScript configuration file and extracts compiler options. + * + * Reads and validates the tsconfig file, then creates a module resolution cache + * for efficient import resolution. Results are cached to avoid re-parsing. + * + * @param typescriptImport - TypeScript library import. + * @param contextCwd - Current working directory for resolution. + * @param filePath - Path to the tsconfig file to parse. + * @returns Parsed compiler options and resolution cache. + * @throws {Error} If the config file cannot be read or parsed. + */ +function getCompilerOptions(typescriptImport, contextCwd, filePath) { + if (contentCacheByPath.has(filePath)) { + return contentCacheByPath.get(filePath) + } + let configFileRead = typescriptImport.readConfigFile( + filePath, + typescriptImport.sys.readFile, + ) + if (configFileRead.error) { + throw new Error( + `Error reading tsconfig file: ${JSON.stringify(configFileRead.error)}`, + ) + } + let parsedContent = typescriptImport.parseJsonConfigFileContent( + configFileRead.config, + typescriptImport.sys, + path.dirname(filePath), + ) + if (parsedContent.errors.length > 0) { + throw new Error( + `Error getting compiler options: ${JSON.stringify(parsedContent.errors)}`, + ) + } + let cache = typescriptImport.createModuleResolutionCache( + contextCwd, + fileName => typescriptImport.sys.resolvePath(fileName), + parsedContent.options, + ) + let output = { + compilerOptions: parsedContent.options, + cache, + } + contentCacheByPath.set(filePath, output) + return output +} +export { contentCacheByPath, directoryCacheByPath, readClosestTsConfigByPath } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..35305d1be9e591bdda3fae964e5d46a178afadda --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/types.d.ts @@ -0,0 +1,169 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +import { TSESTree } from '@typescript-eslint/types' +import { SortingNodeWithDependencies } from '../../utils/sort-nodes-by-dependencies.js' +import { RegexOption, TypeOption } from '../../types/common-options.js' +import { AllCommonOptions } from '../../types/all-common-options.js' +/** + * Configuration options for the sort-imports rule. + * + * This rule enforces consistent ordering of import statements to improve code + * organization, readability, and maintainability. + */ +export type Options = Partial< + { + /** + * TypeScript configuration for resolving module paths. Enables path alias + * resolution based on tsconfig.json paths configuration. + */ + tsconfig: { + /** + * Optional filename of the TypeScript config file. `@default` + * tsconfig.json'. + */ + filename?: string + /** + * Root directory where to search for the TypeScript config file. + */ + rootDir: string + } + /** + * Enables experimental dependency detection. + */ + useExperimentalDependencyDetection: boolean + /** + * Patterns to identify internal imports. Imports matching these patterns + * are categorized as 'internal'. + */ + internalPattern: RegexOption[] + /** + * Runtime environment for resolving built-in modules. Determines which + * modules are considered built-in. + * + * @default 'node' + */ + environment: 'node' | 'bun' + /** + * Controls whether side-effect imports should be sorted. When false, + * side-effect imports remain in their original positions. + * + * @default false + */ + sortSideEffects: boolean + /** + * Maximum line length for imports. When exceeded, import names are used for + * sorting instead of the entire line. + */ + maxLineLength: number + } & AllCommonOptions< + CustomTypeOption, + AdditionalSortOptions, + CustomGroupMatchOptions + > +>[] +/** + * Represents a sorting node for an import statement. Extends the base sorting + * node with dependency information and ignore flag. + */ +export interface SortImportsSortingNode extends SortingNodeWithDependencies { + /** + * The name of the import specifier for sorting purposes. + */ + specifierName: string | null + /** + * Whether this import is a type-only import. + */ + isTypeImport: boolean + /** + * Whether this import should be ignored during sorting. Typically true for + * side-effect imports when sortSideEffects is false. + */ + isIgnored: boolean +} +export type SortImportsNode = + | TSESTree.TSImportEqualsDeclaration + | TSESTree.VariableDeclaration + | TSESTree.ImportDeclaration +/** + * Union type of all available import selectors. Used to categorize different + * types of import statements. + */ +export type Selector = (typeof allSelectors)[number] +/** + * Union type of all available import modifiers. Used to identify specific + * characteristics of import statements. + */ +export type Modifier = (typeof allModifiers)[number] +/** + * Additional configuration for a single custom group. + * + * @example + * + * ```ts + * { + * "modifiers": ["type"], + * "selector": "external" + * } + * ``` + */ +interface CustomGroupMatchOptions { + /** + * List of modifiers that imports must have to be included in this group. + */ + modifiers?: Modifier[] + /** + * The selector type that imports must match to be included in this group. + */ + selector?: Selector +} +interface AdditionalSortOptions { + sortBy: SortByOption +} +type CustomTypeOption = 'type-import-first' | TypeOption +/** + * Complete list of available active import selectors. Used for validation and + * JSON schema generation. + */ +export declare let allSelectors: readonly [ + 'side-effect-style', + 'tsconfig-path', + 'side-effect', + 'external', + 'internal', + 'builtin', + 'sibling', + 'subpath', + 'import', + 'parent', + 'index', + 'style', + 'type', +] +/** + * Complete list of available import modifiers. Used for validation and JSON + * schema generation. + */ +export declare let allModifiers: readonly [ + 'default', + 'multiline', + 'named', + 'require', + 'side-effect', + 'singleline', + 'ts-equals', + 'type', + 'value', + 'wildcard', +] +/** + * Ideally, we should generate as many schemas as there are selectors, and + * ensure that users do not enter invalid modifiers for a given selector. + */ +export declare let additionalCustomGroupMatchOptionsJsonSchema: Record< + string, + JSONSchema4 +> +declare const SORT_BY_OPTION: readonly ['specifier', 'path'] +type SortByOption = (typeof SORT_BY_OPTION)[number] +export declare let additionalSortOptionsJsonSchema: Record +export declare const TYPE_IMPORT_FIRST_TYPE_OPTION = 'type-import-first' +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/types.js new file mode 100644 index 0000000000000000000000000000000000000000..ec698cc7ca7cc90d90c9a2cb3c99b322366a9259 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/types.js @@ -0,0 +1,61 @@ +import { + buildCustomGroupModifiersJsonSchema, + buildCustomGroupSelectorJsonSchema, +} from '../../utils/json-schemas/common-groups-json-schemas.js' +/** + * Complete list of available active import selectors. Used for validation and + * JSON schema generation. + */ +var allSelectors = [ + 'side-effect-style', + 'tsconfig-path', + 'side-effect', + 'external', + 'internal', + 'builtin', + 'sibling', + 'subpath', + 'import', + 'parent', + 'index', + 'style', + 'type', +] +/** + * Complete list of available import modifiers. Used for validation and JSON + * schema generation. + */ +var allModifiers = [ + 'default', + 'multiline', + 'named', + 'require', + 'side-effect', + 'singleline', + 'ts-equals', + 'type', + 'value', + 'wildcard', +] +/** + * Ideally, we should generate as many schemas as there are selectors, and + * ensure that users do not enter invalid modifiers for a given selector. + */ +var additionalCustomGroupMatchOptionsJsonSchema = { + modifiers: buildCustomGroupModifiersJsonSchema(allModifiers), + selector: buildCustomGroupSelectorJsonSchema(allSelectors), +} +var additionalSortOptionsJsonSchema = { + sortBy: { + enum: [...['specifier', 'path']], + type: 'string', + }, +} +var TYPE_IMPORT_FIRST_TYPE_OPTION = 'type-import-first' +export { + TYPE_IMPORT_FIRST_TYPE_OPTION, + additionalCustomGroupMatchOptionsJsonSchema, + additionalSortOptionsJsonSchema, + allModifiers, + allSelectors, +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/validate-side-effects-config.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/validate-side-effects-config.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..04e54f7ccd3db4fe56691de080948f622820d6a3 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/validate-side-effects-config.d.ts @@ -0,0 +1,21 @@ +import { GroupsOptions } from '../../types/common-groups-options.js' +/** + * Validates that side-effect import groups are configured correctly. + * + * When sortSideEffects is false, side-effect imports must be in standalone + * groups, not mixed with regular imports. This prevents unintended reordering + * that could break code execution order. + * + * @param options - Options for validating side-effect groups. + * @param options.groups - Import group configuration. + * @param options.sortSideEffects - Whether side-effect imports can be sorted. + * @throws {Error} If side-effect groups are incorrectly nested with regular + * groups. + */ +export declare function validateSideEffectsConfig({ + sortSideEffects, + groups, +}: { + sortSideEffects: boolean + groups: GroupsOptions +}): void diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/validate-side-effects-config.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/validate-side-effects-config.js new file mode 100644 index 0000000000000000000000000000000000000000..193d823ace6d7f999b9b0f8a80a4db54d57df3a2 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-imports/validate-side-effects-config.js @@ -0,0 +1,38 @@ +import { computeGroupsNames } from '../../utils/compute-groups-names.js' +import { isStringGroupSideEffectOnlyGroup } from './is-string-group-side-effect-only-group.js' +import { isSideEffectOnlyGroup } from './is-side-effect-only-group.js' +/** + * Validates that side-effect import groups are configured correctly. + * + * When sortSideEffects is false, side-effect imports must be in standalone + * groups, not mixed with regular imports. This prevents unintended reordering + * that could break code execution order. + * + * @param options - Options for validating side-effect groups. + * @param options.groups - Import group configuration. + * @param options.sortSideEffects - Whether side-effect imports can be sorted. + * @throws {Error} If side-effect groups are incorrectly nested with regular + * groups. + */ +function validateSideEffectsConfig({ sortSideEffects, groups }) { + if (sortSideEffects) { + return + } + if ( + groups + .map(group => computeGroupsNames([group])) + .some( + nestedGroup => + hasSideEffectGroup(nestedGroup) && + !isSideEffectOnlyGroup(nestedGroup), + ) + ) { + throw new Error( + "Side effect groups cannot be nested with non side effect groups when 'sortSideEffects' is 'false'.", + ) + } +} +function hasSideEffectGroup(stringGroups) { + return stringGroups.some(isStringGroupSideEffectOnlyGroup) +} +export { validateSideEffectsConfig } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-interfaces.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-interfaces.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..07082473834f420ba24dcadd7268d9027f4ec7ff --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-interfaces.d.ts @@ -0,0 +1,20 @@ +declare const ORDER_ERROR_ID = 'unexpectedInterfacePropertiesOrder' +declare const GROUP_ORDER_ERROR_ID = 'unexpectedInterfacePropertiesGroupOrder' +declare const EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenInterfaceMembers' +declare const MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenInterfaceMembers' +type MessageId = + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +declare const _default: import('@typescript-eslint/utils/ts-eslint').RuleModule< + MessageId, + import('...js').SortObjectTypesOptions, + { + recommended?: boolean + }, + import('@typescript-eslint/utils/ts-eslint').RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-interfaces.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-interfaces.js new file mode 100644 index 0000000000000000000000000000000000000000..622f22a87b8671d8a838f96b6bf8b6604203ee39 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-interfaces.js @@ -0,0 +1,56 @@ +import { + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { buildAstListeners } from '../utils/build-ast-listeners.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { sortObjectTypeElements } from './sort-object-types/sort-object-type-elements.js' +import { defaultOptions, jsonSchema } from './sort-object-types.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var ORDER_ERROR_ID = 'unexpectedInterfacePropertiesOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedInterfacePropertiesGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenInterfaceMembers' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenInterfaceMembers' +var sort_interfaces_default = createEslintRule({ + meta: { + messages: { + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-interfaces', + description: 'Enforce sorted interface properties.', + recommended: true, + }, + schema: jsonSchema, + type: 'suggestion', + fixable: 'code', + }, + create: context => + buildAstListeners({ + nodeTypes: [AST_NODE_TYPES.TSInterfaceDeclaration], + sorter: sortInterface, + context, + }), + defaultOptions: [defaultOptions], + name: 'sort-interfaces', +}) +function sortInterface({ matchedAstSelectors, context, node }) { + sortObjectTypeElements({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + elements: node.body.body, + matchedAstSelectors, + parentNodes: [node], + context, + }) +} +export { sort_interfaces_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-interfaces/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-interfaces/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6cb89224d0d54aa4b61a4f4d76f9563838a0a15c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-interfaces/types.d.ts @@ -0,0 +1,2 @@ +import { Options as SortObjectTypesOptions } from '../sort-object-types/types.js' +export type Options = SortObjectTypesOptions diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-intersection-types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-intersection-types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ca4a7ecb6eb07ca8ac5f5130e93141614f752da3 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-intersection-types.d.ts @@ -0,0 +1,21 @@ +import { Options } from './sort-intersection-types/types.js' +declare const ORDER_ERROR_ID = 'unexpectedIntersectionTypesOrder' +declare const GROUP_ORDER_ERROR_ID = 'unexpectedIntersectionTypesGroupOrder' +declare const EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenIntersectionTypes' +declare const MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenIntersectionTypes' +type MessageId = + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +declare const _default: import('@typescript-eslint/utils/ts-eslint').RuleModule< + MessageId, + Options, + { + recommended?: boolean + }, + import('@typescript-eslint/utils/ts-eslint').RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-intersection-types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-intersection-types.js new file mode 100644 index 0000000000000000000000000000000000000000..0d53136389d8b6f7930bb4cbec25b0d788c036ae --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-intersection-types.js @@ -0,0 +1,79 @@ +import { + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { buildAstListeners } from '../utils/build-ast-listeners.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { sortUnionOrIntersectionTypes } from './sort-union-or-intersection-types/sort-union-or-intersection-types.js' +import { buildJsonSchema } from './sort-union-or-intersection-types/build-json-schema.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Cache computed groups by modifiers and selectors for performance. + */ +var cachedGroupsByModifiersAndSelectors = /* @__PURE__ */ new Map() +var ORDER_ERROR_ID = 'unexpectedIntersectionTypesOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedIntersectionTypesGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenIntersectionTypes' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenIntersectionTypes' +var defaultOptions = { + fallbackSort: { type: 'unsorted' }, + newlinesInside: 'newlinesBetween', + ignoreCallableTypes: true, + specialCharacters: 'keep', + newlinesBetween: 'ignore', + partitionByComment: false, + partitionByNewLine: false, + useConfigurationIf: {}, + type: 'alphabetical', + ignoreCase: true, + locales: 'en-US', + customGroups: [], + alphabet: '', + order: 'asc', + groups: [], +} +var sort_intersection_types_default = createEslintRule({ + meta: { + messages: { + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-intersection-types', + description: 'Enforce sorted intersection types.', + recommended: true, + }, + schema: buildJsonSchema({ ignoreCallableTypes: true }), + type: 'suggestion', + fixable: 'code', + }, + create: context => + buildAstListeners({ + nodeTypes: [AST_NODE_TYPES.TSIntersectionType], + sorter: sortIntersectionType, + context, + }), + defaultOptions: [defaultOptions], + name: 'sort-intersection-types', +}) +function sortIntersectionType({ matchedAstSelectors, context, node }) { + sortUnionOrIntersectionTypes({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + cachedGroupsByModifiersAndSelectors, + tokenValueToIgnoreBefore: '&', + matchedAstSelectors, + defaultOptions, + context, + node, + }) +} +export { sort_intersection_types_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-intersection-types/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-intersection-types/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2c6e833ed4ccac1a3bc12e4d79ba1ce6f0d95007 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-intersection-types/types.d.ts @@ -0,0 +1,10 @@ +import { Options as SortUnionTypesOptions } from '../sort-union-types/types.js' +export type Options = (Partial<{ + /** + * When true, skips sorting intersection members that contain callable types + * (function types, constructor types, or objects with call/method + * signatures) to preserve TypeScript's overload resolution order. + */ + ignoreCallableTypes: boolean +}> & + SortUnionTypesOptions[number])[] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a69b8570e12a604b12e90fd514a09e0fcdd6d371 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props.d.ts @@ -0,0 +1,12 @@ +import { MessageId, Options } from './sort-jsx-props/types.js' +declare const _default: import('@typescript-eslint/utils/ts-eslint').RuleModule< + MessageId, + Options, + { + recommended?: boolean + }, + import('@typescript-eslint/utils/ts-eslint').RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props.js new file mode 100644 index 0000000000000000000000000000000000000000..ad5f06989204ec3879ae207b20aa8cbccf559ec7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props.js @@ -0,0 +1,76 @@ +import { + buildCommonJsonSchemas, + buildRegexJsonSchema, + buildUseConfigIfJsonSchema, + matchesAstSelectorJsonSchema, +} from '../utils/json-schemas/common-json-schemas.js' +import { buildCommonGroupsJsonSchemas } from '../utils/json-schemas/common-groups-json-schemas.js' +import { + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { partitionByNewlineJsonSchema } from '../utils/json-schemas/common-partition-json-schemas.js' +import { buildAstListeners } from '../utils/build-ast-listeners.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + additionalCustomGroupMatchOptionsJsonSchema, +} from './sort-jsx-props/types.js' +import { + defaultOptions, + sortJsxObject, +} from './sort-jsx-props/sort-jsx-object.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var sort_jsx_props_default = createEslintRule({ + meta: { + schema: { + items: { + properties: { + ...buildCommonJsonSchemas(), + ...buildCommonGroupsJsonSchemas({ + additionalCustomGroupMatchProperties: + additionalCustomGroupMatchOptionsJsonSchema, + }), + useConfigurationIf: buildUseConfigIfJsonSchema({ + additionalProperties: { + matchesAstSelector: matchesAstSelectorJsonSchema, + tagMatchesPattern: buildRegexJsonSchema(), + }, + }), + partitionByNewLine: partitionByNewlineJsonSchema, + }, + additionalProperties: false, + type: 'object', + }, + uniqueItems: true, + type: 'array', + }, + messages: { + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-jsx-props', + description: 'Enforce sorted JSX props.', + recommended: true, + }, + type: 'suggestion', + fixable: 'code', + }, + create: context => + buildAstListeners({ + nodeTypes: [AST_NODE_TYPES.JSXElement], + sorter: sortJsxObject, + context, + }), + defaultOptions: [defaultOptions], + name: 'sort-jsx-props', +}) +export { sort_jsx_props_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/compute-matched-context-options.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/compute-matched-context-options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..439570edcf85c84a2e4f593a2e080064a03969d1 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/compute-matched-context-options.d.ts @@ -0,0 +1,24 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +import { Options } from './types.js' +/** + * Computes the matched context options for a given JSX element node. + * + * @param params - Parameters. + * @param params.matchedAstSelectors - The matched AST selectors for a JSX node. + * @param params.sourceCode - The source code object. + * @param params.node - The JSX element node to evaluate. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +export declare function computeMatchedContextOptions({ + matchedAstSelectors, + sourceCode, + context, + node, +}: { + context: TSESLint.RuleContext + matchedAstSelectors: ReadonlySet + sourceCode: TSESLint.SourceCode + node: TSESTree.JSXElement +}): Options[number] | undefined diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/compute-matched-context-options.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/compute-matched-context-options.js new file mode 100644 index 0000000000000000000000000000000000000000..336e3ffcee35d68359e3219cb7973179f61cba8e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/compute-matched-context-options.js @@ -0,0 +1,74 @@ +import { matches } from '../../utils/matches.js' +import { passesAllNamesMatchPatternFilter } from '../../utils/context-matching/passes-all-names-match-pattern-filter.js' +import { passesAstSelectorFilter } from '../../utils/context-matching/passes-ast-selector-filter.js' +import { computeNodeName } from './compute-node-name.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the matched context options for a given JSX element node. + * + * @param params - Parameters. + * @param params.matchedAstSelectors - The matched AST selectors for a JSX node. + * @param params.sourceCode - The source code object. + * @param params.node - The JSX element node to evaluate. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +function computeMatchedContextOptions({ + matchedAstSelectors, + sourceCode, + context, + node, +}) { + let nodeNames = node.openingElement.attributes + .filter(attribute => attribute.type !== AST_NODE_TYPES.JSXSpreadAttribute) + .map(attribute => computeNodeName(attribute)) + return context.options.find(options => + isContextOptionMatching({ + matchedAstSelectors, + sourceCode, + nodeNames, + options, + node, + }), + ) +} +function isContextOptionMatching({ + matchedAstSelectors, + sourceCode, + nodeNames, + options, + node, +}) { + if (!options.useConfigurationIf) { + return true + } + return ( + passesAllNamesMatchPatternFilter({ + allNamesMatchPattern: options.useConfigurationIf.allNamesMatchPattern, + nodeNames, + }) && + passesTagMatchesPatternFilter({ + tagMatchesPattern: options.useConfigurationIf.tagMatchesPattern, + sourceCode, + node, + }) && + passesAstSelectorFilter({ + matchesAstSelector: options.useConfigurationIf.matchesAstSelector, + matchedAstSelectors, + }) + ) +} +function passesTagMatchesPatternFilter({ + tagMatchesPattern, + sourceCode, + node, +}) { + if (!tagMatchesPattern) { + return true + } + return matches( + sourceCode.getText(node.openingElement.name), + tagMatchesPattern, + ) +} +export { computeMatchedContextOptions } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/compute-node-name.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/compute-node-name.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce495a3285a143d4d65e78d0136109b19a09a47f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/compute-node-name.d.ts @@ -0,0 +1,8 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Computes the name of a JSX attribute node. + * + * @param node - The JSX attribute node. + * @returns The computed name of the JSX attribute. + */ +export declare function computeNodeName(node: TSESTree.JSXAttribute): string diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/compute-node-name.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/compute-node-name.js new file mode 100644 index 0000000000000000000000000000000000000000..94d97b0250aa2435c3800452e5df16ae1b38ee7f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/compute-node-name.js @@ -0,0 +1,20 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the name of a JSX attribute node. + * + * @param node - The JSX attribute node. + * @returns The computed name of the JSX attribute. + */ +function computeNodeName(node) { + switch (node.name.type) { + case AST_NODE_TYPES.JSXNamespacedName: + return `${node.name.namespace.name}:${node.name.name.name}` + case AST_NODE_TYPES.JSXIdentifier: + return node.name.name + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(node.name) + } +} +export { computeNodeName } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/sort-jsx-object.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/sort-jsx-object.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd78565aeb70b53d106375751b5ac59d94389f86 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/sort-jsx-object.d.ts @@ -0,0 +1,13 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +import { MessageId, Options } from './types.js' +export declare let defaultOptions: Required +export declare function sortJsxObject({ + matchedAstSelectors, + context, + node, +}: { + context: Readonly> + matchedAstSelectors: ReadonlySet + node: TSESTree.JSXElement +}): void diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/sort-jsx-object.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/sort-jsx-object.js new file mode 100644 index 0000000000000000000000000000000000000000..2a08d6021df4bfbfdb2282f4c24dc75a66c2b16d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/sort-jsx-object.js @@ -0,0 +1,167 @@ +import { defaultComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +import { validateNewlinesAndPartitionConfig } from '../../utils/validate-newlines-and-partition-config.js' +import { buildOptionsByGroupIndexComputer } from '../../utils/build-options-by-group-index-computer.js' +import { validateCustomSortConfig } from '../../utils/validate-custom-sort-config.js' +import { generatePredefinedGroups } from '../../utils/generate-predefined-groups.js' +import { getEslintDisabledLines } from '../../utils/get-eslint-disabled-lines.js' +import { doesCustomGroupMatch } from '../../utils/does-custom-group-match.js' +import { isNodeEslintDisabled } from '../../utils/is-node-eslint-disabled.js' +import { validateGroupsConfig } from '../../utils/validate-groups-config.js' +import { sortNodesByGroups } from '../../utils/sort-nodes-by-groups.js' +import { reportAllErrors } from '../../utils/report-all-errors.js' +import { shouldPartition } from '../../utils/should-partition.js' +import { computeGroup } from '../../utils/compute-group.js' +import { rangeToDiff } from '../../utils/range-to-diff.js' +import { getSettings } from '../../utils/get-settings.js' +import { isSortable } from '../../utils/is-sortable.js' +import { complete } from '../../utils/complete.js' +import { isNodeOnSingleLine } from '../../utils/is-node-on-single-line.js' +import { + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + allModifiers, + allSelectors, +} from './types.js' +import { computeNodeName } from './compute-node-name.js' +import { computeMatchedContextOptions } from './compute-matched-context-options.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Cache computed groups by modifiers and selectors for performance. + */ +var cachedGroupsByModifiersAndSelectors = /* @__PURE__ */ new Map() +var defaultOptions = { + fallbackSort: { type: 'unsorted' }, + newlinesInside: 'newlinesBetween', + specialCharacters: 'keep', + newlinesBetween: 'ignore', + partitionByNewLine: false, + useConfigurationIf: {}, + type: 'alphabetical', + ignoreCase: true, + customGroups: [], + locales: 'en-US', + alphabet: '', + order: 'asc', + groups: [], +} +function sortJsxObject({ matchedAstSelectors, context, node }) { + if (!isSortable(node.openingElement.attributes)) { + return + } + let { sourceCode, id } = context + let settings = getSettings(context.settings) + let matchedContextOptions = computeMatchedContextOptions({ + matchedAstSelectors, + sourceCode, + context, + node, + }) + let options = complete(matchedContextOptions, settings, defaultOptions) + validateCustomSortConfig(options) + validateGroupsConfig({ + selectors: allSelectors, + modifiers: allModifiers, + options, + }) + validateNewlinesAndPartitionConfig(options) + let eslintDisabledLines = getEslintDisabledLines({ + ruleName: id, + sourceCode, + }) + let optionsByGroupIndexComputer = buildOptionsByGroupIndexComputer(options) + let formattedMembers = node.openingElement.attributes.reduce( + (accumulator, attribute) => { + if (attribute.type === AST_NODE_TYPES.JSXSpreadAttribute) { + accumulator.push([]) + return accumulator + } + let name = computeNodeName(attribute) + let selectors = [] + let modifiers = [] + if (attribute.value === null) { + modifiers.push('shorthand') + } + if (!isNodeOnSingleLine(attribute)) { + modifiers.push('multiline') + } + selectors.push('prop') + let predefinedGroups = generatePredefinedGroups({ + cache: cachedGroupsByModifiersAndSelectors, + selectors, + modifiers, + }) + let group = computeGroup({ + customGroupMatcher: customGroup => + doesCustomGroupMatch({ + elementValue: + attribute.value ? sourceCode.getText(attribute.value) : null, + elementName: name, + customGroup, + selectors, + modifiers, + }), + predefinedGroups, + options, + }) + let sortingNode = { + isEslintDisabled: isNodeEslintDisabled(attribute, eslintDisabledLines), + size: rangeToDiff(attribute, sourceCode), + node: attribute, + group, + name, + } + let lastSortingNode = accumulator.at(-1)?.at(-1) + if ( + shouldPartition({ + options: { + partitionByNewLine: options.partitionByNewLine, + partitionByComment: false, + }, + lastSortingNode, + sortingNode, + sourceCode, + }) + ) { + accumulator.push([]) + } + accumulator.at(-1).push({ + ...sortingNode, + partitionId: accumulator.length, + }) + return accumulator + }, + [[]], + ) + for (let currentNodes of formattedMembers) { + function createSortNodesExcludingEslintDisabled(nodes) { + return function (ignoreEslintDisabledNodes) { + return sortNodesByGroups({ + comparatorByOptionsComputer: defaultComparatorByOptionsComputer, + optionsByGroupIndexComputer, + ignoreEslintDisabledNodes, + groups: options.groups, + nodes, + }) + } + } + reportAllErrors({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + sortNodesExcludingEslintDisabled: + createSortNodesExcludingEslintDisabled(currentNodes), + options: { + ...options, + partitionByComment: false, + }, + nodes: currentNodes, + context, + }) + } +} +export { defaultOptions, sortJsxObject } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7b56514887295877dbc3c2d2844069aeb775a895 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/types.d.ts @@ -0,0 +1,111 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +import { RegexOption, TypeOption } from '../../types/common-options.js' +import { AllCommonOptions } from '../../types/all-common-options.js' +export type MessageId = + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +export declare const ORDER_ERROR_ID = 'unexpectedJSXPropsOrder' +export declare const GROUP_ORDER_ERROR_ID = 'unexpectedJSXPropsGroupOrder' +export declare const EXTRA_SPACING_ERROR_ID = + 'extraSpacingBetweenJSXPropsMembers' +export declare const MISSED_SPACING_ERROR_ID = + 'missedSpacingBetweenJSXPropsMembers' +/** + * Configuration options for the sort-jsx-props rule. + * + * This rule enforces consistent ordering of JSX element props/attributes to + * improve code readability and maintainability. + */ +export type Options = Partial< + { + /** + * Conditional configuration based on pattern matching. Allows applying the + * rule only to specific JSX elements. + */ + useConfigurationIf: { + /** + * Regular expression pattern to match against all prop names. The rule + * is only applied when all prop names match this pattern. + */ + allNamesMatchPattern?: RegexOption + /** + * Regular expression pattern to match against JSX element tag names. + * The rule is only applied to elements with matching tag names. + */ + tagMatchesPattern?: RegexOption + /** + * AST selector to match against JSXElement nodes. + */ + matchesAstSelector?: string + } + } & Omit< + AllCommonOptions< + TypeOption, + AdditionalSortOptions, + CustomGroupMatchOptions + >, + 'partitionByComment' + > +>[] +/** + * Union type of all available JSX prop modifiers. Used to identify specific + * characteristics of JSX props. + */ +export type Modifier = (typeof allModifiers)[number] +/** + * Union type of all available JSX prop selectors. Used to categorize different + * types of JSX props. + */ +export type Selector = (typeof allSelectors)[number] +/** + * Additional configuration for a single custom group. + * + * @example + * + * ```ts + * { + * "selector": "prop", + * "modifiers": ["shorthand"] + * } + * ``` + */ +interface CustomGroupMatchOptions { + /** + * Regular expression pattern to match prop values. Props with values + * matching this pattern will be included in this custom group. + */ + elementValuePattern?: RegexOption + /** + * List of modifiers that props must have to be included in this group. Can + * include 'shorthand' for props without values or 'multiline' for + * multi-line props. + */ + modifiers?: Modifier[] + /** + * The selector type for this group. Can be 'prop' for regular props, + * 'multiline' for multi-line props, or 'shorthand' for shorthand props. + */ + selector?: Selector +} +type AdditionalSortOptions = object +/** + * Complete list of available JSX prop selectors. Used for validation and JSON + * schema generation. + */ +export declare let allSelectors: readonly ['prop'] +/** + * Complete list of available JSX prop modifiers. Used for validation and JSON + * schema generation. + */ +export declare let allModifiers: readonly ['shorthand', 'multiline'] +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +export declare let additionalCustomGroupMatchOptionsJsonSchema: Record< + string, + JSONSchema4 +> +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/types.js new file mode 100644 index 0000000000000000000000000000000000000000..bf55eaacbf6bbde7187027b7c615c6ddafaff3cc --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-jsx-props/types.js @@ -0,0 +1,37 @@ +import { buildRegexJsonSchema } from '../../utils/json-schemas/common-json-schemas.js' +import { + buildCustomGroupModifiersJsonSchema, + buildCustomGroupSelectorJsonSchema, +} from '../../utils/json-schemas/common-groups-json-schemas.js' +var ORDER_ERROR_ID = 'unexpectedJSXPropsOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedJSXPropsGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenJSXPropsMembers' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenJSXPropsMembers' +/** + * Complete list of available JSX prop selectors. Used for validation and JSON + * schema generation. + */ +var allSelectors = ['prop'] +/** + * Complete list of available JSX prop modifiers. Used for validation and JSON + * schema generation. + */ +var allModifiers = ['shorthand', 'multiline'] +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +var additionalCustomGroupMatchOptionsJsonSchema = { + modifiers: buildCustomGroupModifiersJsonSchema(allModifiers), + selector: buildCustomGroupSelectorJsonSchema(allSelectors), + elementValuePattern: buildRegexJsonSchema(), +} +export { + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + additionalCustomGroupMatchOptionsJsonSchema, + allModifiers, + allSelectors, +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..647f0dbe5c9f5e5d76cbb29c93cdd85126f851bd --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps.d.ts @@ -0,0 +1,12 @@ +import { MessageId, Options } from './sort-maps/types.js' +declare const _default: import('@typescript-eslint/utils/ts-eslint').RuleModule< + MessageId, + Options, + { + recommended?: boolean + }, + import('@typescript-eslint/utils/ts-eslint').RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps.js new file mode 100644 index 0000000000000000000000000000000000000000..b52e1053ca7df8d9d6c3ca273418791e498508e5 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps.js @@ -0,0 +1,74 @@ +import { + buildCommonJsonSchemas, + buildUseConfigIfJsonSchema, + matchesAstSelectorJsonSchema, +} from '../utils/json-schemas/common-json-schemas.js' +import { buildCommonGroupsJsonSchemas } from '../utils/json-schemas/common-groups-json-schemas.js' +import { + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { + partitionByCommentJsonSchema, + partitionByNewlineJsonSchema, +} from '../utils/json-schemas/common-partition-json-schemas.js' +import { buildAstListeners } from '../utils/build-ast-listeners.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, +} from './sort-maps/types.js' +import { + defaultOptions, + sortPotentialMap, +} from './sort-maps/sort-potential-map.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var sort_maps_default = createEslintRule({ + meta: { + schema: { + items: { + properties: { + ...buildCommonJsonSchemas(), + ...buildCommonGroupsJsonSchemas(), + useConfigurationIf: buildUseConfigIfJsonSchema({ + additionalProperties: { + matchesAstSelector: matchesAstSelectorJsonSchema, + }, + }), + partitionByComment: partitionByCommentJsonSchema, + partitionByNewLine: partitionByNewlineJsonSchema, + }, + additionalProperties: false, + type: 'object', + }, + uniqueItems: true, + type: 'array', + }, + messages: { + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-maps', + description: 'Enforce sorted Map elements.', + recommended: true, + }, + type: 'suggestion', + fixable: 'code', + }, + create: context => + buildAstListeners({ + nodeTypes: [AST_NODE_TYPES.NewExpression], + sorter: sortPotentialMap, + context, + }), + defaultOptions: [defaultOptions], + name: 'sort-maps', +}) +export { sort_maps_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/compute-matched-context-options.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/compute-matched-context-options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..962b0e3db6fe923494a271915bf6a70ffc941a34 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/compute-matched-context-options.d.ts @@ -0,0 +1,21 @@ +import { RuleContext } from '@typescript-eslint/utils/ts-eslint' +import { TSESTree } from '@typescript-eslint/types' +import { MessageId, Options } from './types.js' +/** + * Computes the matched context options for a given map node. + * + * @param params - Parameters. + * @param params.matchedAstSelectors - The matched AST selectors for a map node. + * @param params.elements - The map elements to compute the context options for. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +export declare function computeMatchedContextOptions({ + matchedAstSelectors, + elements, + context, +}: { + elements: (TSESTree.SpreadElement | TSESTree.Expression | null)[] + context: Readonly> + matchedAstSelectors: ReadonlySet +}): Options[number] | undefined diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/compute-matched-context-options.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/compute-matched-context-options.js new file mode 100644 index 0000000000000000000000000000000000000000..0c0f0b693c1b7dd055dcb687ee866ba9ec7872d5 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/compute-matched-context-options.js @@ -0,0 +1,53 @@ +import { passesAllNamesMatchPatternFilter } from '../../utils/context-matching/passes-all-names-match-pattern-filter.js' +import { passesAstSelectorFilter } from '../../utils/context-matching/passes-ast-selector-filter.js' +import { computeNodeName } from './compute-node-name.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the matched context options for a given map node. + * + * @param params - Parameters. + * @param params.matchedAstSelectors - The matched AST selectors for a map node. + * @param params.elements - The map elements to compute the context options for. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +function computeMatchedContextOptions({ + matchedAstSelectors, + elements, + context, +}) { + let nodeNames = elements + .filter( + element => + element !== null && element.type !== AST_NODE_TYPES.SpreadElement, + ) + .map(element => + computeNodeName({ + sourceCode: context.sourceCode, + node: element, + }), + ) + return context.options.find(options => + isContextOptionMatching({ + matchedAstSelectors, + nodeNames, + options, + }), + ) +} +function isContextOptionMatching({ matchedAstSelectors, nodeNames, options }) { + if (!options.useConfigurationIf) { + return true + } + return ( + passesAllNamesMatchPatternFilter({ + allNamesMatchPattern: options.useConfigurationIf.allNamesMatchPattern, + nodeNames, + }) && + passesAstSelectorFilter({ + matchesAstSelector: options.useConfigurationIf.matchesAstSelector, + matchedAstSelectors, + }) + ) +} +export { computeMatchedContextOptions } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/compute-node-name.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/compute-node-name.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3f1f484b69cbc97c34cce684917553fedae2bee9 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/compute-node-name.d.ts @@ -0,0 +1,21 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { TSESTree } from '@typescript-eslint/types' +/** + * Extracts the name of a Map element for sorting purposes. + * + * For array expressions (key-value pairs), extracts the first element as the + * key. Returns the literal raw value for literals, or the source code text for + * other expressions. + * + * @param params - Parameters object. + * @param params.sourceCode - The ESLint source code object. + * @param params.node - The Map element expression to get the name from. + * @returns The name to use for sorting this Map element. + */ +export declare function computeNodeName({ + sourceCode, + node, +}: { + sourceCode: TSESLint.SourceCode + node: TSESTree.Expression +}): string diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/compute-node-name.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/compute-node-name.js new file mode 100644 index 0000000000000000000000000000000000000000..0f3540ada626db8d1ae947b369d482cba962f4f4 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/compute-node-name.js @@ -0,0 +1,26 @@ +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Extracts the name of a Map element for sorting purposes. + * + * For array expressions (key-value pairs), extracts the first element as the + * key. Returns the literal raw value for literals, or the source code text for + * other expressions. + * + * @param params - Parameters object. + * @param params.sourceCode - The ESLint source code object. + * @param params.node - The Map element expression to get the name from. + * @returns The name to use for sorting this Map element. + */ +function computeNodeName({ sourceCode, node }) { + if (node.type !== AST_NODE_TYPES.ArrayExpression) { + return sourceCode.getText(node) + } + let [left] = node.elements + if (!left) { + return 'undefined' + } + return left.type === AST_NODE_TYPES.Literal ? + left.raw + : sourceCode.getText(left) +} +export { computeNodeName } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/sort-potential-map.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/sort-potential-map.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6cee9cc1bdfd5dcfc27aa3a1296a3536733e4590 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/sort-potential-map.d.ts @@ -0,0 +1,13 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +import { MessageId, Options } from './types.js' +export declare let defaultOptions: Required +export declare function sortPotentialMap({ + matchedAstSelectors, + context, + node, +}: { + context: TSESLint.RuleContext + matchedAstSelectors: ReadonlySet + node: TSESTree.NewExpression +}): void diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/sort-potential-map.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/sort-potential-map.js new file mode 100644 index 0000000000000000000000000000000000000000..2ca140ba396430105d4412e157e36eaa191b527f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/sort-potential-map.js @@ -0,0 +1,153 @@ +import { defaultComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +import { buildOptionsByGroupIndexComputer } from '../../utils/build-options-by-group-index-computer.js' +import { validateCustomSortConfig } from '../../utils/validate-custom-sort-config.js' +import { getEslintDisabledLines } from '../../utils/get-eslint-disabled-lines.js' +import { doesCustomGroupMatch } from '../../utils/does-custom-group-match.js' +import { isNodeEslintDisabled } from '../../utils/is-node-eslint-disabled.js' +import { validateGroupsConfig } from '../../utils/validate-groups-config.js' +import { sortNodesByGroups } from '../../utils/sort-nodes-by-groups.js' +import { reportAllErrors } from '../../utils/report-all-errors.js' +import { shouldPartition } from '../../utils/should-partition.js' +import { computeGroup } from '../../utils/compute-group.js' +import { rangeToDiff } from '../../utils/range-to-diff.js' +import { getSettings } from '../../utils/get-settings.js' +import { isSortable } from '../../utils/is-sortable.js' +import { complete } from '../../utils/complete.js' +import { + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, +} from './types.js' +import { computeNodeName } from './compute-node-name.js' +import { computeMatchedContextOptions } from './compute-matched-context-options.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var defaultOptions = { + fallbackSort: { type: 'unsorted' }, + newlinesInside: 'newlinesBetween', + specialCharacters: 'keep', + partitionByComment: false, + partitionByNewLine: false, + newlinesBetween: 'ignore', + useConfigurationIf: {}, + type: 'alphabetical', + ignoreCase: true, + customGroups: [], + locales: 'en-US', + alphabet: '', + order: 'asc', + groups: [], +} +function sortPotentialMap({ matchedAstSelectors, context, node }) { + if ( + node.callee.type !== AST_NODE_TYPES.Identifier || + node.callee.name !== 'Map' || + node.arguments.length === 0 || + node.arguments[0]?.type !== AST_NODE_TYPES.ArrayExpression + ) { + return + } + let [{ elements }] = node.arguments + if (!isSortable(elements)) { + return + } + let { sourceCode, id } = context + let settings = getSettings(context.settings) + let matchedContextOptions = computeMatchedContextOptions({ + matchedAstSelectors, + elements, + context, + }) + let options = complete(matchedContextOptions, settings, defaultOptions) + validateCustomSortConfig(options) + validateGroupsConfig({ + selectors: [], + modifiers: [], + options, + }) + let eslintDisabledLines = getEslintDisabledLines({ + ruleName: id, + sourceCode, + }) + let optionsByGroupIndexComputer = buildOptionsByGroupIndexComputer(options) + let parts = elements.reduce( + (accumulator, element) => { + if (element === null || element.type === AST_NODE_TYPES.SpreadElement) { + accumulator.push([]) + } else { + accumulator.at(-1).push(element) + } + return accumulator + }, + [[]], + ) + for (let part of parts) { + let formattedMembers = [[]] + for (let element of part) { + let name = computeNodeName({ + node: element, + sourceCode, + }) + let lastSortingNode = formattedMembers.at(-1)?.at(-1) + let group = computeGroup({ + customGroupMatcher: customGroup => + doesCustomGroupMatch({ + elementName: name, + selectors: [], + modifiers: [], + customGroup, + }), + predefinedGroups: [], + options, + }) + let sortingNode = { + isEslintDisabled: isNodeEslintDisabled(element, eslintDisabledLines), + size: rangeToDiff(element, sourceCode), + node: element, + group, + name, + } + if ( + shouldPartition({ + lastSortingNode, + sortingNode, + sourceCode, + options, + }) + ) { + formattedMembers.push([]) + } + formattedMembers.at(-1).push({ + ...sortingNode, + partitionId: formattedMembers.length, + }) + } + for (let nodes of formattedMembers) { + function createSortNodesExcludingEslintDisabled(sortingNodes) { + return function (ignoreEslintDisabledNodes) { + return sortNodesByGroups({ + comparatorByOptionsComputer: defaultComparatorByOptionsComputer, + optionsByGroupIndexComputer, + ignoreEslintDisabledNodes, + groups: options.groups, + nodes: sortingNodes, + }) + } + } + reportAllErrors({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + sortNodesExcludingEslintDisabled: + createSortNodesExcludingEslintDisabled(nodes), + options, + context, + nodes, + }) + } + } +} +export { defaultOptions, sortPotentialMap } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9ddb07dbc3c9a674596747068fd75979b36fc60 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/types.d.ts @@ -0,0 +1,49 @@ +import { RegexOption, TypeOption } from '../../types/common-options.js' +import { AllCommonOptions } from '../../types/all-common-options.js' +export type MessageId = + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +export declare const ORDER_ERROR_ID = 'unexpectedMapElementsOrder' +export declare const GROUP_ORDER_ERROR_ID = 'unexpectedMapElementsGroupOrder' +export declare const EXTRA_SPACING_ERROR_ID = + 'extraSpacingBetweenMapElementsMembers' +export declare const MISSED_SPACING_ERROR_ID = + 'missedSpacingBetweenMapElementsMembers' +/** + * Configuration options for the sort-maps rule. + * + * This rule enforces consistent ordering of Map elements to improve code + * readability and maintainability. + */ +export type Options = Partial< + { + /** + * Conditional configuration based on pattern matching. Allows applying the + * rule only when specific conditions are met. + */ + useConfigurationIf: { + /** + * Regular expression pattern to match against all Map element keys. The + * rule is only applied when all keys match this pattern. + */ + allNamesMatchPattern?: RegexOption + /** + * AST selector to match against NewExpression nodes targeting Map + * constructions. + */ + matchesAstSelector?: string + } + } & AllCommonOptions< + TypeOption, + AdditionalSortOptions, + CustomGroupMatchOptions + > +>[] +/** + * Match options for a custom group. + */ +type CustomGroupMatchOptions = object +type AdditionalSortOptions = object +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/types.js new file mode 100644 index 0000000000000000000000000000000000000000..8508cfc6943e7417046da619e3502cc51f9bd221 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-maps/types.js @@ -0,0 +1,10 @@ +var ORDER_ERROR_ID = 'unexpectedMapElementsOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedMapElementsGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenMapElementsMembers' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenMapElementsMembers' +export { + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fa75ba96a02de61b175b84eab7adaa108e4c255f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules.d.ts @@ -0,0 +1,24 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { Options } from './sort-modules/types.js' +declare const ORDER_ERROR_ID = 'unexpectedModulesOrder' +declare const GROUP_ORDER_ERROR_ID = 'unexpectedModulesGroupOrder' +declare const EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenModulesMembers' +declare const MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenModulesMembers' +declare const DEPENDENCY_ORDER_ERROR_ID = 'unexpectedModulesDependencyOrder' +type MessageId = + | typeof DEPENDENCY_ORDER_ERROR_ID + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +declare const _default: TSESLint.RuleModule< + MessageId, + Options, + { + recommended?: boolean + }, + TSESLint.RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules.js new file mode 100644 index 0000000000000000000000000000000000000000..c5516f62f93b1f26ce4229b69d12c839cd9b054a --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules.js @@ -0,0 +1,355 @@ +import { + buildCommonJsonSchemas, + useExperimentalDependencyDetectionJsonSchema, +} from '../utils/json-schemas/common-json-schemas.js' +import { + buildCommonGroupsJsonSchemas, + newlinesBetweenJsonSchema, +} from '../utils/json-schemas/common-groups-json-schemas.js' +import { getGroupIndex } from '../utils/get-group-index.js' +import { + DEPENDENCY_ORDER_ERROR, + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { + partitionByCommentJsonSchema, + partitionByNewlineJsonSchema, +} from '../utils/json-schemas/common-partition-json-schemas.js' +import { populateSortingNodeGroupsWithDependencies } from '../utils/populate-sorting-node-groups-with-dependencies.js' +import { validateNewlinesAndPartitionConfig } from '../utils/validate-newlines-and-partition-config.js' +import { buildOptionsByGroupIndexComputer } from '../utils/build-options-by-group-index-computer.js' +import { validateCustomSortConfig } from '../utils/validate-custom-sort-config.js' +import { generatePredefinedGroups } from '../utils/generate-predefined-groups.js' +import { sortNodesByDependencies } from '../utils/sort-nodes-by-dependencies.js' +import { getEslintDisabledLines } from '../utils/get-eslint-disabled-lines.js' +import { doesCustomGroupMatch } from '../utils/does-custom-group-match.js' +import { isNodeEslintDisabled } from '../utils/is-node-eslint-disabled.js' +import { validateGroupsConfig } from '../utils/validate-groups-config.js' +import { sortNodesByGroups } from '../utils/sort-nodes-by-groups.js' +import { reportAllErrors } from '../utils/report-all-errors.js' +import { shouldPartition } from '../utils/should-partition.js' +import { computeGroup } from '../utils/compute-group.js' +import { rangeToDiff } from '../utils/range-to-diff.js' +import { getSettings } from '../utils/get-settings.js' +import { complete } from '../utils/complete.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { getDecoratorName } from '../utils/get-decorator-name.js' +import { buildOverloadSignatureNewlinesBetweenValueGetter } from '../utils/overload-signature/build-overload-signature-newlines-between-value-getter.js' +import { populateSortingNodeGroupsWithOverloadSignature } from '../utils/overload-signature/populate-sorting-node-groups-with-overload-signature.js' +import '../utils/assert-is-never.js' +import { + USAGE_TYPE_OPTION, + additionalCustomGroupMatchOptionsJsonSchema, + allModifiers, + allSelectors, +} from './sort-modules/types.js' +import { computeDependenciesBySortingNode } from './sort-modules/compute-dependencies-by-sorting-node.js' +import { buildComparatorByOptionsComputer } from './sort-modules/build-comparator-by-options-computer.js' +import { computeOverloadSignatureGroups } from './sort-modules/compute-overload-signature-groups.js' +import { computeNodeDetails } from './sort-modules/compute-node-details.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Cache computed groups by modifiers and selectors for performance. + */ +var cachedGroupsByModifiersAndSelectors = /* @__PURE__ */ new Map() +var ORDER_ERROR_ID = 'unexpectedModulesOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedModulesGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenModulesMembers' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenModulesMembers' +var DEPENDENCY_ORDER_ERROR_ID = 'unexpectedModulesDependencyOrder' +var defaultOptions = { + groups: [ + 'declare-enum', + 'export-enum', + 'enum', + ['declare-interface', 'declare-type'], + ['export-interface', 'export-type'], + ['interface', 'type'], + 'declare-class', + 'class', + 'export-class', + 'declare-function', + 'export-function', + 'function', + ], + useExperimentalDependencyDetection: true, + newlinesBetweenOverloadSignatures: 0, + fallbackSort: { type: 'unsorted' }, + newlinesInside: 'newlinesBetween', + partitionByComment: false, + partitionByNewLine: false, + newlinesBetween: 'ignore', + specialCharacters: 'keep', + type: 'alphabetical', + ignoreCase: true, + customGroups: [], + locales: 'en-US', + alphabet: '', + order: 'asc', +} +var sort_modules_default = createEslintRule({ + meta: { + schema: [ + { + properties: { + ...buildCommonJsonSchemas({ + allowedAdditionalTypeValues: [USAGE_TYPE_OPTION], + }), + ...buildCommonGroupsJsonSchemas({ + additionalCustomGroupMatchProperties: + additionalCustomGroupMatchOptionsJsonSchema, + allowedAdditionalTypeValues: [USAGE_TYPE_OPTION], + }), + useExperimentalDependencyDetection: + useExperimentalDependencyDetectionJsonSchema, + newlinesBetweenOverloadSignatures: newlinesBetweenJsonSchema, + partitionByComment: partitionByCommentJsonSchema, + partitionByNewLine: partitionByNewlineJsonSchema, + }, + additionalProperties: false, + type: 'object', + }, + ], + messages: { + [DEPENDENCY_ORDER_ERROR_ID]: DEPENDENCY_ORDER_ERROR, + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-modules', + description: 'Enforce sorted modules.', + recommended: true, + }, + type: 'suggestion', + fixable: 'code', + }, + create: context => { + let settings = getSettings(context.settings) + let options = complete(context.options.at(0), settings, defaultOptions) + validateCustomSortConfig(options) + validateGroupsConfig({ + modifiers: allModifiers, + selectors: allSelectors, + options, + }) + validateNewlinesAndPartitionConfig(options) + let { sourceCode, id } = context + let eslintDisabledLines = getEslintDisabledLines({ + ruleName: id, + sourceCode, + }) + return { + Program: program => + analyzeModule({ + eslintDisabledLines, + module: program, + sourceCode, + options, + context, + }), + } + }, + defaultOptions: [defaultOptions], + name: 'sort-modules', +}) +function analyzeModule({ + eslintDisabledLines, + sourceCode, + options, + context, + module, +}) { + let optionsByGroupIndexComputer = buildOptionsByGroupIndexComputer(options) + let overloadSignatureNewlinesBetweenValueGetter = + buildOverloadSignatureNewlinesBetweenValueGetter( + options.newlinesBetweenOverloadSignatures, + ) + let sortingNodeGroupsWithoutOverloadSignature = [[]] + for (let node of module.body) { + switch (node.type) { + case AST_NODE_TYPES.TSNamespaceExportDeclaration: + case AST_NODE_TYPES.ExportAllDeclaration: + case AST_NODE_TYPES.ImportDeclaration: + case AST_NODE_TYPES.DebuggerStatement: + case AST_NODE_TYPES.ContinueStatement: + case AST_NODE_TYPES.ReturnStatement: + case AST_NODE_TYPES.EmptyStatement: + case AST_NODE_TYPES.BreakStatement: + case AST_NODE_TYPES.WithStatement: + continue + case AST_NODE_TYPES.ExportDefaultDeclaration: + case AST_NODE_TYPES.ExportNamedDeclaration: + case AST_NODE_TYPES.TSInterfaceDeclaration: + case AST_NODE_TYPES.TSTypeAliasDeclaration: + case AST_NODE_TYPES.FunctionDeclaration: + case AST_NODE_TYPES.TSModuleDeclaration: + break + case AST_NODE_TYPES.TSImportEqualsDeclaration: + case AST_NODE_TYPES.VariableDeclaration: + case AST_NODE_TYPES.ExpressionStatement: + case AST_NODE_TYPES.TSExportAssignment: + case AST_NODE_TYPES.DoWhileStatement: + case AST_NODE_TYPES.LabeledStatement: + case AST_NODE_TYPES.SwitchStatement: + case AST_NODE_TYPES.WhileStatement: + case AST_NODE_TYPES.ForInStatement: + case AST_NODE_TYPES.ForOfStatement: + case AST_NODE_TYPES.ThrowStatement: + case AST_NODE_TYPES.BlockStatement: + case AST_NODE_TYPES.ForStatement: + case AST_NODE_TYPES.TryStatement: + case AST_NODE_TYPES.IfStatement: + sortingNodeGroupsWithoutOverloadSignature.push([]) + continue + case AST_NODE_TYPES.TSDeclareFunction: + case AST_NODE_TYPES.TSEnumDeclaration: + case AST_NODE_TYPES.ClassDeclaration: + break + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + continue + } + let details = computeNodeDetails({ + useExperimentalDependencyDetection: + options.useExperimentalDependencyDetection, + node, + }) + if (!details.nodeDetails) { + if (details.shouldPartitionAfterNode) { + sortingNodeGroupsWithoutOverloadSignature.push([]) + } + if (details.moduleBlock) { + analyzeModule({ + module: details.moduleBlock, + eslintDisabledLines, + sourceCode, + options, + context, + }) + } + continue + } + let { + addSafetySemicolonWhenInline, + dependencyDetection, + dependencies, + decorators, + modifiers, + selector, + name, + } = details.nodeDetails + let predefinedGroups = generatePredefinedGroups({ + cache: cachedGroupsByModifiersAndSelectors, + selectors: [selector], + modifiers, + }) + let decoratorNames = decorators.map(decorator => + getDecoratorName({ + sourceCode, + decorator, + }), + ) + let group = computeGroup({ + customGroupMatcher: customGroup => + doesCustomGroupMatch({ + selectors: [selector], + elementName: name, + decoratorNames, + customGroup, + modifiers, + }), + predefinedGroups, + options, + }) + let sortingNode = { + isEslintDisabled: isNodeEslintDisabled(node, eslintDisabledLines), + size: rangeToDiff(node, sourceCode), + implicitDecorators: decorators, + addSafetySemicolonWhenInline, + dependencyNames: [name], + dependencyDetection, + dependencies, + group, + name, + node, + } + let lastSortingNode = sortingNodeGroupsWithoutOverloadSignature + .at(-1) + ?.at(-1) + if ( + shouldPartition({ + lastSortingNode, + sortingNode, + sourceCode, + options, + }) + ) { + sortingNodeGroupsWithoutOverloadSignature.push([]) + } + sortingNodeGroupsWithoutOverloadSignature.at(-1)?.push({ + ...sortingNode, + partitionId: sortingNodeGroupsWithoutOverloadSignature.length, + }) + } + let overloadSignatureGroups = computeOverloadSignatureGroups( + sortingNodeGroupsWithoutOverloadSignature.flat().map(({ node }) => node), + ) + let sortingNodeGroups = populateSortingNodeGroupsWithOverloadSignature({ + sortingNodeGroups: sortingNodeGroupsWithoutOverloadSignature, + overloadSignatureGroups, + }) + if (options.useExperimentalDependencyDetection) { + let dependenciesBySortingNode = computeDependenciesBySortingNode({ + sortingNodes: sortingNodeGroups.flat(), + dependencyDetection: 'hard', + sourceCode, + }) + sortingNodeGroups = populateSortingNodeGroupsWithDependencies({ + dependenciesBySortingNode, + sortingNodeGroups, + }) + } + let sortingNodes = sortingNodeGroups.flat() + reportAllErrors({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + unexpectedDependencyOrder: DEPENDENCY_ORDER_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + newlinesBetweenValueGetter: overloadSignatureNewlinesBetweenValueGetter, + sortNodesExcludingEslintDisabled, + nodes: sortingNodes, + options, + context, + }) + function sortNodesExcludingEslintDisabled(ignoreEslintDisabledNodes) { + let nodesSortedByGroups = sortingNodeGroups.flatMap(sortingNodeGroup => + sortNodesByGroups({ + comparatorByOptionsComputer: buildComparatorByOptionsComputer({ + useExperimentalDependencyDetection: + options.useExperimentalDependencyDetection, + sortingNodes: sortingNodeGroup, + ignoreEslintDisabledNodes, + sourceCode, + }), + isNodeIgnored: sortingNode => + getGroupIndex(options.groups, sortingNode) === options.groups.length, + optionsByGroupIndexComputer, + ignoreEslintDisabledNodes, + nodes: sortingNodeGroup, + groups: options.groups, + }), + ) + return sortNodesByDependencies(nodesSortedByGroups, { + ignoreEslintDisabledNodes, + }) + } +} +export { sort_modules_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/build-comparator-by-options-computer.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/build-comparator-by-options-computer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..db630d1c2225b68a33baf87fae12e2f2f345c318 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/build-comparator-by-options-computer.d.ts @@ -0,0 +1,17 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { ComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +import { SortModulesSortingNode, Options } from './types.js' +export declare function buildComparatorByOptionsComputer({ + useExperimentalDependencyDetection, + ignoreEslintDisabledNodes, + sortingNodes, + sourceCode, +}: { + useExperimentalDependencyDetection: boolean + sortingNodes: SortModulesSortingNode[] + ignoreEslintDisabledNodes: boolean + sourceCode: TSESLint.SourceCode +}): ComparatorByOptionsComputer< + Required, + SortModulesSortingNode +> diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/build-comparator-by-options-computer.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/build-comparator-by-options-computer.js new file mode 100644 index 0000000000000000000000000000000000000000..ae92e07d2a8d46e665442813913a9d1f0bb42449 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/build-comparator-by-options-computer.js @@ -0,0 +1,35 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { defaultComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +import { buildUsageComparator } from './build-usage-comparator.js' +function buildComparatorByOptionsComputer({ + useExperimentalDependencyDetection, + ignoreEslintDisabledNodes, + sortingNodes, + sourceCode, +}) { + return options => { + switch (options.type) { + case 'subgroup-order': + case 'alphabetical': + case 'line-length': + case 'unsorted': + case 'natural': + case 'custom': + return defaultComparatorByOptionsComputer({ + ...options, + type: options.type, + }) + case 'usage': + return buildUsageComparator({ + useExperimentalDependencyDetection, + ignoreEslintDisabledNodes, + sortingNodes, + sourceCode, + }) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(options.type) + } + } +} +export { buildComparatorByOptionsComputer } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/build-usage-comparator.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/build-usage-comparator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c66784e6e433d45d31e26bf16582647a8cda824b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/build-usage-comparator.d.ts @@ -0,0 +1,26 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { Comparator } from '../../utils/compare/default-comparator-by-options-computer.js' +import { SortModulesSortingNode } from './types.js' +/** + * Builds a comparator function for sorting module nodes based on their usage. + * + * @param params - The parameters object. + * @param params.ignoreEslintDisabledNodes - Whether to ignore ESLint disabled + * nodes. + * @param params.sortingNodes - The module sorting nodes. + * @param params.useExperimentalDependencyDetection - Whether to use + * experimental dependency detection. + * @param params.sourceCode - The source code object. + * @returns A comparator function for sorting module nodes by usage. + */ +export declare function buildUsageComparator({ + useExperimentalDependencyDetection, + ignoreEslintDisabledNodes, + sortingNodes, + sourceCode, +}: { + useExperimentalDependencyDetection: boolean + sortingNodes: SortModulesSortingNode[] + ignoreEslintDisabledNodes: boolean + sourceCode: TSESLint.SourceCode +}): Comparator diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/build-usage-comparator.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/build-usage-comparator.js new file mode 100644 index 0000000000000000000000000000000000000000..ccc63b109bdc906e47ac38857270d1b53a8d738f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/build-usage-comparator.js @@ -0,0 +1,127 @@ +import { populateSortingNodeGroupsWithDependencies } from '../../utils/populate-sorting-node-groups-with-dependencies.js' +import { isNodeDependentOnOtherNode } from '../../utils/is-node-dependent-on-other-node.js' +import { sortNodesByDependencies } from '../../utils/sort-nodes-by-dependencies.js' +import { buildSortingNodeByNodeMap } from '../../utils/build-sorting-node-by-node-map.js' +import { computeDependenciesBySortingNode } from './compute-dependencies-by-sorting-node.js' +import { computeDependencies } from './compute-dependencies.js' +/** + * Builds a comparator function for sorting module nodes based on their usage. + * + * @param params - The parameters object. + * @param params.ignoreEslintDisabledNodes - Whether to ignore ESLint disabled + * nodes. + * @param params.sortingNodes - The module sorting nodes. + * @param params.useExperimentalDependencyDetection - Whether to use + * experimental dependency detection. + * @param params.sourceCode - The source code object. + * @returns A comparator function for sorting module nodes by usage. + */ +function buildUsageComparator({ + useExperimentalDependencyDetection, + ignoreEslintDisabledNodes, + sortingNodes, + sourceCode, +}) { + let { updatedSortingNodeByNode, orderByUnsortedNode, orderBySortedNode } = + buildOrderByNodeMaps({ + useExperimentalDependencyDetection, + ignoreEslintDisabledNodes, + sortingNodes, + sourceCode, + }) + return (a, b) => { + let nodeA = a.node + let nodeB = b.node + let sortedOrderA = orderBySortedNode.get(nodeA) + let unsortedOrderA = orderByUnsortedNode.get(nodeA) + let sortedOrderB = orderBySortedNode.get(nodeB) + let unsortedOrderB = orderByUnsortedNode.get(nodeB) + let sortedOrderedValue = sortedOrderA - sortedOrderB + let unsortedOrderedValue = unsortedOrderA - unsortedOrderB + if (Math.sign(sortedOrderedValue) !== Math.sign(unsortedOrderedValue)) { + return sortedOrderedValue + } + let aWithUpdatedDependencies = updatedSortingNodeByNode.get(nodeA) + let bWithUpdatedDependencies = updatedSortingNodeByNode.get(nodeB) + if ( + isNodeDependentOnOtherNode( + aWithUpdatedDependencies, + bWithUpdatedDependencies, + ) || + isNodeDependentOnOtherNode( + bWithUpdatedDependencies, + aWithUpdatedDependencies, + ) + ) { + return sortedOrderedValue + } + return 0 + } +} +function buildOrderByNodeMaps({ + useExperimentalDependencyDetection, + ignoreEslintDisabledNodes, + sortingNodes, + sourceCode, +}) { + let sortingNodesWithUpdatedDependencies + if (useExperimentalDependencyDetection) { + let dependenciesBySortingNode = computeDependenciesBySortingNode({ + dependencyDetection: 'soft', + sortingNodes, + sourceCode, + }) + sortingNodesWithUpdatedDependencies = + populateSortingNodeGroupsWithDependencies({ + sortingNodeGroups: [sortingNodes], + dependenciesBySortingNode, + })[0] + } else { + sortingNodesWithUpdatedDependencies = sortingNodes.map( + computeSortingNodeWithUpdatedDependencies, + ) + } + let sortedSortingNodes = sortNodesByDependencies( + sortingNodesWithUpdatedDependencies, + { ignoreEslintDisabledNodes }, + ) + return { + updatedSortingNodeByNode: buildSortingNodeByNodeMap( + sortingNodesWithUpdatedDependencies, + ), + orderBySortedNode: buildOrderByNodeMap(sortedSortingNodes), + orderByUnsortedNode: buildOrderByNodeMap(sortingNodes), + } + /** + * Computes a sorting node with updated dependencies. + * + * @deprecated - To remove when experimental dependency detection is the only + * option. + * @param params - The parameters object. + * @returns The sorting node populated with updated dependencies. + */ + function computeSortingNodeWithUpdatedDependencies({ + isEslintDisabled, + dependencyNames, + node, + }) { + let dependencies = computeDependencies(node, { type: 'soft' }) + let dependencyNamesSet = new Set(dependencyNames) + return { + dependencies: dependencies.filter( + dependency => !dependencyNamesSet.has(dependency), + ), + isEslintDisabled, + dependencyNames, + node, + } + } +} +function buildOrderByNodeMap(sortingNodes) { + let returnValue = /* @__PURE__ */ new Map() + for (let [i, { node }] of sortingNodes.entries()) { + returnValue.set(node, i) + } + return returnValue +} +export { buildUsageComparator } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-dependencies-by-sorting-node.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-dependencies-by-sorting-node.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..425443ec252f26a954d0113d7f8f0f633b167f8b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-dependencies-by-sorting-node.d.ts @@ -0,0 +1,16 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { SortModulesSortingNode, DependencyDetection } from './types.js' +type SortingNodeWithoutDependencies = Omit< + SortModulesSortingNode, + 'dependencies' +> +export declare function computeDependenciesBySortingNode({ + dependencyDetection, + sortingNodes, + sourceCode, +}: { + sortingNodes: SortingNodeWithoutDependencies[] + dependencyDetection: DependencyDetection + sourceCode: TSESLint.SourceCode +}): Map +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-dependencies-by-sorting-node.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-dependencies-by-sorting-node.js new file mode 100644 index 0000000000000000000000000000000000000000..788761427a7d3bd4c07c93989559bc11826102e5 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-dependencies-by-sorting-node.js @@ -0,0 +1,129 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { computeDependenciesBySortingNode as computeDependenciesBySortingNode$1 } from '../../utils/compute-dependencies-by-sorting-node.js' +import { computeParentNodesWithTypes } from '../../utils/compute-parent-nodes-with-types.js' +import { doesSortingNodeHaveOneOfDependencyNames } from '../../utils/does-sorting-node-have-one-of-dependency-names.js' +import { isPropertyOrAccessorNode } from './is-property-or-accessor-node.js' +import { isArrowFunctionNode } from './is-arrow-function-node.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +function computeDependenciesBySortingNode({ + dependencyDetection, + sortingNodes, + sourceCode, +}) { + return computeDependenciesBySortingNode$1({ + additionalIdentifierDependenciesComputer: + buildAdditionalIdentifierDependenciesComputer({ sortingNodes }), + shouldIgnoreSortingNodeComputer: + buildShouldIgnoreSortingNodeComputer(dependencyDetection), + shouldIgnoreIdentifierComputer: + buildShouldIgnoreIdentifierComputer(dependencyDetection), + sortingNodes, + sourceCode, + }) +} +function buildShouldIgnoreIdentifierComputer(dependencyDetection) { + return ({ referencingSortingNode, identifier }) => { + switch (dependencyDetection) { + case 'soft': + return false + case 'hard': + return !isInRelevantClassContext() + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(dependencyDetection) + } + function isInRelevantClassContext() { + let relevantParentNodes = computeParentNodesWithTypes({ + allowedTypes: [ + AST_NODE_TYPES.ClassBody, + AST_NODE_TYPES.PropertyDefinition, + AST_NODE_TYPES.AccessorProperty, + AST_NODE_TYPES.MethodDefinition, + AST_NODE_TYPES.ArrowFunctionExpression, + ], + maxParent: referencingSortingNode.node, + consecutiveOnly: false, + node: identifier, + }) + let firstClassBodyParent = relevantParentNodes.findIndex( + parentNode => parentNode.type === AST_NODE_TYPES.ClassBody, + ) + if (firstClassBodyParent < 0) { + return true + } + let searchStaticMethodsAndFunctionProperties = relevantParentNodes[ + firstClassBodyParent + ].body.some( + classElement => + classElement.type === AST_NODE_TYPES.StaticBlock || + (classElement.static && + isPropertyOrAccessorNode(classElement) && + !isArrowFunctionNode(classElement)), + ) + return relevantParentNodes + .slice(0, firstClassBodyParent) + .every(otherParent => + isClassElementRelevant( + otherParent, + searchStaticMethodsAndFunctionProperties, + ), + ) + } + function isClassElementRelevant( + classElement, + searchStaticMethodsAndFunctionProperties, + ) { + if ( + classElement.type !== AST_NODE_TYPES.MethodDefinition && + !isArrowFunctionNode(classElement) + ) { + return true + } + return classElement.static && searchStaticMethodsAndFunctionProperties + } + } +} +function buildAdditionalIdentifierDependenciesComputer({ sortingNodes }) { + return ({ referencingSortingNode, reference }) => { + let relatedIdentifiers = [ + ...computeMemberExpressionIdentifiers(), + ...computeQualifiedNameIdentifiers(), + ] + return sortingNodes.filter(sortingNode => + doesSortingNodeHaveOneOfDependencyNames(sortingNode, relatedIdentifiers), + ) + function computeMemberExpressionIdentifiers() { + return computeParentNodesWithTypes({ + allowedTypes: [AST_NODE_TYPES.MemberExpression], + maxParent: referencingSortingNode.node, + node: reference.identifier, + consecutiveOnly: true, + }) + .map(node => node.property) + .filter(property => property.type === AST_NODE_TYPES.Identifier) + .map(property => property.name) + } + function computeQualifiedNameIdentifiers() { + return computeParentNodesWithTypes({ + allowedTypes: [AST_NODE_TYPES.TSQualifiedName], + maxParent: referencingSortingNode.node, + node: reference.identifier, + consecutiveOnly: true, + }).map(node => node.right.name) + } + } +} +function buildShouldIgnoreSortingNodeComputer(dependencyDetection) { + return sortingNode => { + switch (dependencyDetection) { + case 'hard': + return sortingNode.dependencyDetection !== 'hard' + case 'soft': + return false + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(dependencyDetection) + } + } +} +export { computeDependenciesBySortingNode } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-dependencies.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-dependencies.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9988c807f5b75fa346ae86f8e279b4bcaf8b3625 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-dependencies.d.ts @@ -0,0 +1,26 @@ +import { SortModulesNode } from './types.js' +interface HardDependencyDetection { + searchStaticMethodsAndFunctionProperties: boolean + type: 'hard' +} +interface SoftDependencyDetection { + searchStaticMethodsAndFunctionProperties?: never + type: 'soft' +} +type DependencyDetection = HardDependencyDetection | SoftDependencyDetection +/** + * Computes the dependencies of a given AST node. + * + * @deprecated - To remove when experimental dependency detection is the only + * option. + * @param node - The AST node to analyze. + * @param dependencyDetection - The dependency detection strategy. Hard + * dependencies consider dependencies impacting compilation, while soft + * dependencies also consider type references. + * @returns The names of the dependencies. + */ +export declare function computeDependencies( + node: SortModulesNode, + dependencyDetection: DependencyDetection, +): string[] +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-dependencies.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-dependencies.js new file mode 100644 index 0000000000000000000000000000000000000000..27dbc05f9ac7cd0f0b4b4b4a9e6e70c087c1b8e3 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-dependencies.js @@ -0,0 +1,215 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { isArrowFunctionNode } from './is-arrow-function-node.js' +import { getEnumMembers } from '../../utils/get-enum-members.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the dependencies of a given AST node. + * + * @deprecated - To remove when experimental dependency detection is the only + * option. + * @param node - The AST node to analyze. + * @param dependencyDetection - The dependency detection strategy. Hard + * dependencies consider dependencies impacting compilation, while soft + * dependencies also consider type references. + * @returns The names of the dependencies. + */ +function computeDependencies(node, dependencyDetection) { + let dependencies = [] + checkNode(node) + return dependencies + function checkNode(nodeToCheck, options) { + switch (dependencyDetection.type) { + case 'hard': + if ( + (nodeToCheck.type === AST_NODE_TYPES.MethodDefinition || + isArrowFunctionNode(nodeToCheck)) && + (!nodeToCheck.static || + !dependencyDetection.searchStaticMethodsAndFunctionProperties) + ) { + return + } + break + case 'soft': + checkNodesForSoftDependencies() + break + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(dependencyDetection) + } + checkNodesForCommonDependencies() + function checkNodesForCommonDependencies() { + if ( + !options?.ignoreNextIdentifier && + nodeToCheck.type === AST_NODE_TYPES.Identifier + ) { + dependencies.push(nodeToCheck.name) + } + if ('alternate' in nodeToCheck && nodeToCheck.alternate) { + checkNode(nodeToCheck.alternate) + } + if ('argument' in nodeToCheck && nodeToCheck.argument) { + checkNode(nodeToCheck.argument) + } + if ('arguments' in nodeToCheck) { + traverseNode(nodeToCheck.arguments) + } + if ( + 'body' in nodeToCheck && + nodeToCheck.body && + nodeToCheck.type !== AST_NODE_TYPES.TSEnumDeclaration + ) { + traverseNode(nodeToCheck.body) + } + if ('callee' in nodeToCheck) { + checkNode(nodeToCheck.callee) + } + if ('consequent' in nodeToCheck) { + traverseNode(nodeToCheck.consequent) + } + if ('declarations' in nodeToCheck) { + traverseNode(nodeToCheck.declarations) + } + if ('decorators' in nodeToCheck) { + traverseNode(nodeToCheck.decorators) + } + if ('elements' in nodeToCheck) { + traverseNode( + nodeToCheck.elements.filter(currentNode => currentNode !== null), + ) + } + if ( + 'expression' in nodeToCheck && + typeof nodeToCheck.expression !== 'boolean' + ) { + checkNode(nodeToCheck.expression) + } + if ('expressions' in nodeToCheck) { + traverseNode(nodeToCheck.expressions) + } + if ('init' in nodeToCheck && nodeToCheck.init) { + checkNode(nodeToCheck.init) + } + if ('initializer' in nodeToCheck && nodeToCheck.initializer) { + checkNode(nodeToCheck.initializer) + } + if ('left' in nodeToCheck) { + checkNode(nodeToCheck.left) + } + if (nodeToCheck.type === AST_NODE_TYPES.TSEnumDeclaration) { + traverseNode(getEnumMembers(nodeToCheck)) + } else if ('members' in nodeToCheck) { + traverseNode(nodeToCheck.members) + } + if ('object' in nodeToCheck) { + checkNode(nodeToCheck.object) + } + if ('properties' in nodeToCheck) { + traverseNode(nodeToCheck.properties) + } + if ('property' in nodeToCheck) { + checkNode(nodeToCheck.property) + } + if ('right' in nodeToCheck) { + checkNode(nodeToCheck.right) + } + if ('superClass' in nodeToCheck && nodeToCheck.superClass) { + checkNode(nodeToCheck.superClass) + } + if ('test' in nodeToCheck && nodeToCheck.test) { + checkNode(nodeToCheck.test) + } + if ( + 'value' in nodeToCheck && + nodeToCheck.value && + typeof nodeToCheck.value === 'object' && + 'type' in nodeToCheck.value + ) { + checkNode(nodeToCheck.value) + } + } + function checkNodesForSoftDependencies() { + if ('checkType' in nodeToCheck) { + checkNode(nodeToCheck.checkType) + } + if ('constraint' in nodeToCheck && nodeToCheck.constraint) { + checkNode(nodeToCheck.constraint) + } + if ('declaration' in nodeToCheck && nodeToCheck.declaration) { + checkNode(nodeToCheck.declaration) + } + if ('elementTypes' in nodeToCheck) { + traverseNode(nodeToCheck.elementTypes) + } + if ('elementType' in nodeToCheck) { + checkNode(nodeToCheck.elementType) + } + if ('extends' in nodeToCheck) { + traverseNode(nodeToCheck.extends) + } + if ('extendsType' in nodeToCheck) { + checkNode(nodeToCheck.extendsType) + } + if ('exprName' in nodeToCheck) { + checkNode(nodeToCheck.exprName) + } + if ('falseType' in nodeToCheck) { + checkNode(nodeToCheck.falseType) + } + if ('key' in nodeToCheck) { + checkNode(nodeToCheck.key, { ignoreNextIdentifier: true }) + } + if ('id' in nodeToCheck && nodeToCheck.id) { + checkNode(nodeToCheck.id) + } + if ('implements' in nodeToCheck) { + traverseNode(nodeToCheck.implements) + } + if ('indexType' in nodeToCheck) { + checkNode(nodeToCheck.indexType) + } + if ('name' in nodeToCheck && typeof nodeToCheck.name !== 'string') { + checkNode(nodeToCheck.name) + } + if ('objectType' in nodeToCheck) { + checkNode(nodeToCheck.objectType) + } + if ('params' in nodeToCheck) { + traverseNode(nodeToCheck.params, { ignoreNextIdentifier: true }) + } + if ('returnType' in nodeToCheck && nodeToCheck.returnType) { + checkNode(nodeToCheck.returnType) + } + if ('trueType' in nodeToCheck) { + checkNode(nodeToCheck.trueType) + } + if ('typeAnnotation' in nodeToCheck && nodeToCheck.typeAnnotation) { + checkNode(nodeToCheck.typeAnnotation) + } + if ('typeArguments' in nodeToCheck && nodeToCheck.typeArguments) { + checkNode(nodeToCheck.typeArguments) + } + if ('typeName' in nodeToCheck) { + checkNode(nodeToCheck.typeName) + } + if ('typeParameters' in nodeToCheck && nodeToCheck.typeParameters) { + traverseNode(nodeToCheck.typeParameters) + } + if ('typeParameter' in nodeToCheck) { + checkNode(nodeToCheck.typeParameter) + } + if ('types' in nodeToCheck) { + traverseNode(nodeToCheck.types) + } + } + } + function traverseNode(nodeToTraverse, options) { + if (Array.isArray(nodeToTraverse)) { + for (let nodeItem of nodeToTraverse) { + traverseNode(nodeItem, options) + } + } else { + checkNode(nodeToTraverse, options) + } + } +} +export { computeDependencies } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-node-details.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-node-details.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f5b07a5b3e62b9ca36750699d134c821fd6330d1 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-node-details.d.ts @@ -0,0 +1,44 @@ +import { TSESTree } from '@typescript-eslint/types' +import { + DependencyDetection, + SortModulesNode, + Modifier, + Selector, +} from './types.js' +interface ParsableNodeDetails { + nodeDetails: { + dependencyDetection: DependencyDetection + addSafetySemicolonWhenInline: boolean + decorators: TSESTree.Decorator[] + dependencies: string[] + modifiers: Modifier[] + selector: Selector + name: string + } + shouldPartitionAfterNode?: never + moduleBlock?: never +} +interface NonParsableNodeDetails { + moduleBlock: TSESTree.TSModuleBlock | null + shouldPartitionAfterNode: boolean + nodeDetails?: never +} +type Details = NonParsableNodeDetails | ParsableNodeDetails +/** + * Compute details about a module-related node. + * + * @param params - The parameters object. + * @param params.node - The AST node to compute details for. + * @param params.useExperimentalDependencyDetection - Whether to use + * experimental dependency detection. + * @returns The computed details about the node, such as whether it should be + * ignored, if a module block was found, and information about the node. + */ +export declare function computeNodeDetails({ + useExperimentalDependencyDetection, + node, +}: { + useExperimentalDependencyDetection: boolean + node: SortModulesNode +}): Details +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-node-details.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-node-details.js new file mode 100644 index 0000000000000000000000000000000000000000..7f0d8e50a0ffce9c382772228d556ed2a1a31d9c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-node-details.js @@ -0,0 +1,153 @@ +import { getNodeDecorators } from '../../utils/get-node-decorators.js' +import { isPropertyOrAccessorNode } from './is-property-or-accessor-node.js' +import { isArrowFunctionNode } from './is-arrow-function-node.js' +import { computeDependencies } from './compute-dependencies.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Compute details about a module-related node. + * + * @param params - The parameters object. + * @param params.node - The AST node to compute details for. + * @param params.useExperimentalDependencyDetection - Whether to use + * experimental dependency detection. + * @returns The computed details about the node, such as whether it should be + * ignored, if a module block was found, and information about the node. + */ +function computeNodeDetails({ useExperimentalDependencyDetection, node }) { + let selector + let name + let modifiers = [] + let dependencies = [] + let decorators = [] + let addSafetySemicolonWhenInline = false + let moduleBlock = null + let shouldPartitionAfterNode = false + let dependencyDetection = 'soft' + function parseNode(nodeToParse) { + if ('declare' in nodeToParse && nodeToParse.declare) { + modifiers.push('declare') + } + switch (nodeToParse.type) { + case AST_NODE_TYPES.ExportDefaultDeclaration: + modifiers.push('default', 'export') + if ('decorators' in nodeToParse.declaration) { + decorators = getNodeDecorators(nodeToParse.declaration) + } + parseNode(nodeToParse.declaration) + break + case AST_NODE_TYPES.ExportNamedDeclaration: + if (nodeToParse.declaration) { + if ('decorators' in nodeToParse.declaration) { + decorators = getNodeDecorators(nodeToParse.declaration) + } + parseNode(nodeToParse.declaration) + } + modifiers.push('export') + break + case AST_NODE_TYPES.TSInterfaceDeclaration: + selector = 'interface' + ;({ name } = nodeToParse.id) + break + case AST_NODE_TYPES.TSTypeAliasDeclaration: + selector = 'type' + ;({ name } = nodeToParse.id) + addSafetySemicolonWhenInline = true + break + case AST_NODE_TYPES.FunctionDeclaration: + case AST_NODE_TYPES.TSDeclareFunction: + selector = 'function' + if (nodeToParse.async) { + modifiers.push('async') + } + if (modifiers.includes('declare')) { + addSafetySemicolonWhenInline = true + } + name = nodeToParse.id?.name + break + case AST_NODE_TYPES.TSModuleDeclaration: + shouldPartitionAfterNode = true + moduleBlock = nodeToParse.body ?? null + break + case AST_NODE_TYPES.VariableDeclaration: + shouldPartitionAfterNode = true + break + case AST_NODE_TYPES.TSEnumDeclaration: + selector = 'enum' + ;({ name } = nodeToParse.id) + dependencyDetection = 'hard' + dependencies.push( + ...extractDependencies( + nodeToParse, + useExperimentalDependencyDetection, + ), + ) + break + case AST_NODE_TYPES.ClassDeclaration: + selector = 'class' + name = nodeToParse.id?.name + let nodeDecorators = getNodeDecorators(nodeToParse) + if (nodeDecorators[0]) { + modifiers.push('decorated') + } + decorators = nodeDecorators + dependencyDetection = 'hard' + dependencies.push( + ...extractDependencies( + nodeToParse, + useExperimentalDependencyDetection, + ), + ) + } + } + parseNode(node) + if (!selector || !name) { + return { + shouldPartitionAfterNode, + moduleBlock, + } + } + return { + nodeDetails: { + addSafetySemicolonWhenInline, + dependencyDetection, + dependencies, + decorators, + modifiers, + selector, + name, + }, + } +} +/** + * Extract dependencies from an enum or class declaration. + * + * @deprecated - To remove when experimental dependency detection is the only + * option. + * @param expression - The enum or class declaration node. + * @param useExperimentalDependencyDetection - Whether to use experimental + * dependency detection. + * @returns The list of dependencies. + */ +function extractDependencies(expression, useExperimentalDependencyDetection) { + if (useExperimentalDependencyDetection) { + return [] + } + /** + * Search static methods only if there is a static block or a static property + * that is not an arrow function. + */ + let searchStaticMethodsAndFunctionProperties = + expression.type === AST_NODE_TYPES.ClassDeclaration && + expression.body.body.some( + classElement => + classElement.type === AST_NODE_TYPES.StaticBlock || + (classElement.static && + isPropertyOrAccessorNode(classElement) && + !isArrowFunctionNode(classElement)), + ) + return computeDependencies(expression, { + searchStaticMethodsAndFunctionProperties, + type: 'hard', + }) +} +export { computeNodeDetails } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-overload-signature-groups.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-overload-signature-groups.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..614893fb972cbb67daa9daba30aed79cc93742c2 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-overload-signature-groups.d.ts @@ -0,0 +1,11 @@ +import { SortModulesNode } from './types.js' +import { OverloadSignatureGroup } from '../../utils/overload-signature/overload-signature-group.js' +/** + * Returns a list of groups of overload signatures. + * + * @param nodes - The nodes to process. + * @returns A list of overload signature groups. + */ +export declare function computeOverloadSignatureGroups( + nodes: SortModulesNode[], +): OverloadSignatureGroup[] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-overload-signature-groups.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-overload-signature-groups.js new file mode 100644 index 0000000000000000000000000000000000000000..f6c11d1af916c1a57254d952796cc38c9eae4b56 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/compute-overload-signature-groups.js @@ -0,0 +1,85 @@ +import { isSortable } from '../../utils/is-sortable.js' +import { OverloadSignatureGroup } from '../../utils/overload-signature/overload-signature-group.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Returns a list of groups of overload signatures. + * + * @param nodes - The nodes to process. + * @returns A list of overload signature groups. + */ +function computeOverloadSignatureGroups(nodes) { + let functionDetailsByName = /* @__PURE__ */ new Map() + for (let node of nodes) { + let functionDetails = computeNodeFunctionDetails(node) + if (!functionDetails) { + continue + } + let functionDetailsArray = functionDetailsByName.get(functionDetails.name) + if (!functionDetailsArray) { + functionDetailsArray = [] + functionDetailsByName.set(functionDetails.name, functionDetailsArray) + } + functionDetailsArray.push({ + ...functionDetails, + node, + }) + } + let overloadSignatureGroups = [] + for (let functionDetailsArray of functionDetailsByName.values()) { + if (isSortable(functionDetailsArray)) { + overloadSignatureGroups.push( + buildOverloadSignatureGroup(functionDetailsArray), + ) + } + } + return overloadSignatureGroups +} +function computeNodeFunctionDetails(node) { + let currentNode = node + while ( + currentNode.type === AST_NODE_TYPES.ExportDefaultDeclaration || + currentNode.type === AST_NODE_TYPES.ExportNamedDeclaration + ) { + /* v8 ignore start -- @preserve Unsure how we can reach that case */ + if (!currentNode.declaration) { + return null + } + /* v8 ignore stop -- @preserve Unsure how we can reach that case */ + currentNode = currentNode.declaration + } + switch (currentNode.type) { + case AST_NODE_TYPES.FunctionDeclaration: + case AST_NODE_TYPES.TSDeclareFunction: + return computeFunctionDetails(currentNode) + default: + return null + } + function computeFunctionDetails(functionNode) { + /* v8 ignore if -- @preserve Unsure how we can reach that case */ + if (!functionNode.id) { + return null + } + return { + isImplementation: + functionNode.type === AST_NODE_TYPES.FunctionDeclaration, + name: functionNode.id.name, + } + } +} +function buildOverloadSignatureGroup(functionDetailsArray) { + let implementation = ( + functionDetailsArray.find(isFunctionImplementation) ?? + functionDetailsArray.at(-1) + ).node + let overloadSignatures = functionDetailsArray + .filter(functionDetails => !isFunctionImplementation(functionDetails)) + .map(functionDetails => functionDetails.node) + return new OverloadSignatureGroup({ + overloadSignatures, + implementation, + }) + function isFunctionImplementation(functionDetails) { + return functionDetails.isImplementation + } +} +export { computeOverloadSignatureGroups } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/is-arrow-function-node.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/is-arrow-function-node.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..586190e880e6f56e58cf314b19787221b3fec92e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/is-arrow-function-node.d.ts @@ -0,0 +1,12 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Checks whether a node is a property or accessor node with an + * ArrowFunctionExpression value. + * + * @param node - The AST node to check. + * @returns True if the node is a property or accessor node with an + * ArrowFunctionExpression value, false otherwise. + */ +export declare function isArrowFunctionNode( + node: TSESTree.Node, +): node is TSESTree.PropertyDefinition | TSESTree.AccessorProperty diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/is-arrow-function-node.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/is-arrow-function-node.js new file mode 100644 index 0000000000000000000000000000000000000000..f9590605b93261166a5880c00eedd4151dd587de --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/is-arrow-function-node.js @@ -0,0 +1,18 @@ +import { isPropertyOrAccessorNode } from './is-property-or-accessor-node.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Checks whether a node is a property or accessor node with an + * ArrowFunctionExpression value. + * + * @param node - The AST node to check. + * @returns True if the node is a property or accessor node with an + * ArrowFunctionExpression value, false otherwise. + */ +function isArrowFunctionNode(node) { + return ( + isPropertyOrAccessorNode(node) && + node.value !== null && + node.value.type === AST_NODE_TYPES.ArrowFunctionExpression + ) +} +export { isArrowFunctionNode } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/is-property-or-accessor-node.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/is-property-or-accessor-node.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..209c101aace48b2d3695255dddf52856a0328b16 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/is-property-or-accessor-node.d.ts @@ -0,0 +1,11 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Checks whether a node is a PropertyDefinition or AccessorProperty. + * + * @param node - The AST node to check. + * @returns True if the node is a PropertyDefinition or AccessorProperty, false + * otherwise. + */ +export declare function isPropertyOrAccessorNode( + node: TSESTree.Node, +): node is TSESTree.PropertyDefinition | TSESTree.AccessorProperty diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/is-property-or-accessor-node.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/is-property-or-accessor-node.js new file mode 100644 index 0000000000000000000000000000000000000000..c85be07fbf37c84502ad0c4b6c277f9345199d7b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/is-property-or-accessor-node.js @@ -0,0 +1,15 @@ +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Checks whether a node is a PropertyDefinition or AccessorProperty. + * + * @param node - The AST node to check. + * @returns True if the node is a PropertyDefinition or AccessorProperty, false + * otherwise. + */ +function isPropertyOrAccessorNode(node) { + return ( + node.type === AST_NODE_TYPES.PropertyDefinition || + node.type === AST_NODE_TYPES.AccessorProperty + ) +} +export { isPropertyOrAccessorNode } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0df96463c3ecf547ae9c0bc8404bfc05de56342 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/types.d.ts @@ -0,0 +1,114 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +import { TSESTree } from '@typescript-eslint/types' +import { SortingNodeWithDependencies } from '../../utils/sort-nodes-by-dependencies.js' +import { NewlinesBetweenOption } from '../../types/common-groups-options.js' +import { RegexOption, TypeOption } from '../../types/common-options.js' +import { AllCommonOptions } from '../../types/all-common-options.js' +/** + * Configuration options for the sort-modules rule. + * + * This rule enforces consistent ordering of module-level declarations (classes, + * interfaces, functions, types, enums) to improve code organization. + */ +export type Options = [ + Partial< + { + /** + * Determines how many newlines should be placed between overload + * signatures of the same function. + */ + newlinesBetweenOverloadSignatures: NewlinesBetweenOption + /** + * Enables experimental dependency detection. + */ + useExperimentalDependencyDetection: boolean + } & AllCommonOptions< + CustomTypeOption, + AdditionalSortOptions, + CustomGroupMatchOptions + > + >, +] +export type SortModulesNode = + | TSESTree.ExportDefaultDeclaration + | TSESTree.ExportNamedDeclaration + | TSESTree.TSInterfaceDeclaration + | TSESTree.TSTypeAliasDeclaration + | TSESTree.FunctionDeclaration + | TSESTree.TSModuleDeclaration + | TSESTree.TSDeclareFunction + | TSESTree.TSEnumDeclaration + | TSESTree.ClassDeclaration +/** + * Represents a sorting node for a module statement. + */ +export type SortModulesSortingNode = { + overloadSignatureImplementation: SortModulesNode | null + dependencyDetection: DependencyDetection +} & SortingNodeWithDependencies +/** + * Union type of all available module member selectors. Used to categorize + * different types of module-level declarations. + */ +export type Selector = (typeof allSelectors)[number] +/** + * Union type of all available module member modifiers. Used to identify + * specific characteristics of module declarations. + */ +export type Modifier = (typeof allModifiers)[number] +export type DependencyDetection = 'soft' | 'hard' +/** + * Additional configuration for a single custom group. + * + * Custom groups allow fine-grained control over how module members are grouped + * and sorted based on their types, modifiers, and patterns. + */ +interface CustomGroupMatchOptions { + /** + * Regular expression pattern to match decorator names. Members with + * decorators matching this pattern will be included in this custom group. + */ + decoratorNamePattern?: RegexOption + /** + * List of modifiers that members must have to be included in this group. + */ + modifiers?: Modifier[] + /** + * The type of module member this group applies to. + */ + selector?: Selector +} +type CustomTypeOption = typeof USAGE_TYPE_OPTION | TypeOption +type AdditionalSortOptions = object +/** + * Complete list of available module member selectors. Used for validation and + * JSON schema generation. + */ +export declare let allSelectors: readonly [ + 'enum', + 'function', + 'interface', + 'type', + 'class', +] +/** + * Complete list of available module member modifiers. Used for validation and + * JSON schema generation. + */ +export declare let allModifiers: readonly [ + 'async', + 'declare', + 'decorated', + 'default', + 'export', +] +/** + * Ideally, we should generate as many schemas as there are selectors, and + * ensure that users do not enter invalid modifiers for a given selector. + */ +export declare let additionalCustomGroupMatchOptionsJsonSchema: Record< + string, + JSONSchema4 +> +export declare const USAGE_TYPE_OPTION = 'usage' +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/types.js new file mode 100644 index 0000000000000000000000000000000000000000..479b4390222047ff966419c1f732467aeabf50a6 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-modules/types.js @@ -0,0 +1,31 @@ +import { buildRegexJsonSchema } from '../../utils/json-schemas/common-json-schemas.js' +import { + buildCustomGroupModifiersJsonSchema, + buildCustomGroupSelectorJsonSchema, +} from '../../utils/json-schemas/common-groups-json-schemas.js' +/** + * Complete list of available module member selectors. Used for validation and + * JSON schema generation. + */ +var allSelectors = ['enum', 'function', 'interface', 'type', 'class'] +/** + * Complete list of available module member modifiers. Used for validation and + * JSON schema generation. + */ +var allModifiers = ['async', 'declare', 'decorated', 'default', 'export'] +/** + * Ideally, we should generate as many schemas as there are selectors, and + * ensure that users do not enter invalid modifiers for a given selector. + */ +var additionalCustomGroupMatchOptionsJsonSchema = { + modifiers: buildCustomGroupModifiersJsonSchema(allModifiers), + selector: buildCustomGroupSelectorJsonSchema(allSelectors), + decoratorNamePattern: buildRegexJsonSchema(), +} +var USAGE_TYPE_OPTION = 'usage' +export { + USAGE_TYPE_OPTION, + additionalCustomGroupMatchOptionsJsonSchema, + allModifiers, + allSelectors, +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..96958be6e9dc71a6407b00389644aceeaaaac6ea --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports.d.ts @@ -0,0 +1,12 @@ +import { MessageId, Options } from './sort-named-exports/types.js' +declare const _default: import('@typescript-eslint/utils/ts-eslint').RuleModule< + MessageId, + Options, + { + recommended?: boolean + }, + import('@typescript-eslint/utils/ts-eslint').RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports.js new file mode 100644 index 0000000000000000000000000000000000000000..5ee52bc0841235cbcda74e360d4d47ffd9aa48b4 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports.js @@ -0,0 +1,82 @@ +import { + buildCommonJsonSchemas, + buildUseConfigIfJsonSchema, + matchesAstSelectorJsonSchema, +} from '../utils/json-schemas/common-json-schemas.js' +import { buildCommonGroupsJsonSchemas } from '../utils/json-schemas/common-groups-json-schemas.js' +import { + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { + partitionByCommentJsonSchema, + partitionByNewlineJsonSchema, +} from '../utils/json-schemas/common-partition-json-schemas.js' +import { buildAstListeners } from '../utils/build-ast-listeners.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + additionalCustomGroupMatchOptionsJsonSchema, +} from './sort-named-exports/types.js' +import { + defaultOptions, + sortNamedExport, +} from './sort-named-exports/sort-named-export.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var sort_named_exports_default = createEslintRule({ + meta: { + schema: { + items: { + properties: { + ...buildCommonJsonSchemas(), + ...buildCommonGroupsJsonSchemas({ + additionalCustomGroupMatchProperties: + additionalCustomGroupMatchOptionsJsonSchema, + }), + useConfigurationIf: buildUseConfigIfJsonSchema({ + additionalProperties: { + matchesAstSelector: matchesAstSelectorJsonSchema, + }, + }), + ignoreAlias: { + description: 'Controls whether to ignore alias names.', + type: 'boolean', + }, + partitionByComment: partitionByCommentJsonSchema, + partitionByNewLine: partitionByNewlineJsonSchema, + }, + additionalProperties: false, + type: 'object', + }, + uniqueItems: true, + type: 'array', + }, + messages: { + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-named-exports', + description: 'Enforce sorted named exports.', + recommended: true, + }, + type: 'suggestion', + fixable: 'code', + }, + create: context => + buildAstListeners({ + nodeTypes: [AST_NODE_TYPES.ExportNamedDeclaration], + sorter: sortNamedExport, + context, + }), + defaultOptions: [defaultOptions], + name: 'sort-named-exports', +}) +export { sort_named_exports_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/compute-export-kind-modifier.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/compute-export-kind-modifier.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..00eff981239360f533a8b1e3c48831dc02a25a11 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/compute-export-kind-modifier.d.ts @@ -0,0 +1,4 @@ +import { TSESTree } from '@typescript-eslint/types' +export declare function computeExportKindModifier( + node: TSESTree.ExportSpecifier, +): 'value' | 'type' diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/compute-export-kind-modifier.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/compute-export-kind-modifier.js new file mode 100644 index 0000000000000000000000000000000000000000..f3a599e62730105d371cd8f69fea2c3745f27ac3 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/compute-export-kind-modifier.js @@ -0,0 +1,15 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +function computeExportKindModifier(node) { + let exportKind = 'exportKind' in node ? node.exportKind : void 0 + switch (exportKind) { + case void 0: + case 'value': + return 'value' + case 'type': + return 'type' + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(exportKind) + } +} +export { computeExportKindModifier } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/compute-matched-context-options.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/compute-matched-context-options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ccb45b0e117bc0a3ed569efec285614370f03e7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/compute-matched-context-options.d.ts @@ -0,0 +1,23 @@ +import { RuleContext } from '@typescript-eslint/utils/ts-eslint' +import { TSESTree } from '@typescript-eslint/types' +import { MessageId, Options } from './types.js' +/** + * Computes the matched context options for a given named export node. + * + * @param params - Parameters. + * @param params.node - The named export node to compute the context options + * for. + * @param params.matchedAstSelectors - The matched AST selectors for a named + * export node. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +export declare function computeMatchedContextOptions({ + matchedAstSelectors, + context, + node, +}: { + context: Readonly> + matchedAstSelectors: ReadonlySet + node: TSESTree.ExportNamedDeclaration +}): Options[number] | undefined diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/compute-matched-context-options.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/compute-matched-context-options.js new file mode 100644 index 0000000000000000000000000000000000000000..1ae2518bbdbd6ab6a335df285bbc1a87f5d1d05b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/compute-matched-context-options.js @@ -0,0 +1,42 @@ +import { passesAllNamesMatchPatternFilter } from '../../utils/context-matching/passes-all-names-match-pattern-filter.js' +import { passesAstSelectorFilter } from '../../utils/context-matching/passes-ast-selector-filter.js' +import { computeNodeName } from './compute-node-name.js' +/** + * Computes the matched context options for a given named export node. + * + * @param params - Parameters. + * @param params.node - The named export node to compute the context options + * for. + * @param params.matchedAstSelectors - The matched AST selectors for a named + * export node. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +function computeMatchedContextOptions({ matchedAstSelectors, context, node }) { + return context.options.find(options => + isContextOptionMatching({ + matchedAstSelectors, + options, + node, + }), + ) +} +function isContextOptionMatching({ matchedAstSelectors, options, node }) { + if (!options.useConfigurationIf) { + return true + } + let nodeNames = node.specifiers.map(specifier => + computeNodeName(specifier, !!options.ignoreAlias), + ) + return ( + passesAllNamesMatchPatternFilter({ + allNamesMatchPattern: options.useConfigurationIf.allNamesMatchPattern, + nodeNames, + }) && + passesAstSelectorFilter({ + matchesAstSelector: options.useConfigurationIf.matchesAstSelector, + matchedAstSelectors, + }) + ) +} +export { computeMatchedContextOptions } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/compute-node-name.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/compute-node-name.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9b1ad5f79bf5ca1db4a77fecd3863e5b68d42147 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/compute-node-name.d.ts @@ -0,0 +1,12 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Computes the name of an export specifier node. + * + * @param node - The export specifier node. + * @param ignoreAlias - Whether to ignore the alias and use the local name. + * @returns The computed name of the export specifier. + */ +export declare function computeNodeName( + node: TSESTree.ExportSpecifier, + ignoreAlias: boolean, +): string diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/compute-node-name.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/compute-node-name.js new file mode 100644 index 0000000000000000000000000000000000000000..022b1f12cefeb986040ab5ec778a058771c42a24 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/compute-node-name.js @@ -0,0 +1,22 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the name of an export specifier node. + * + * @param node - The export specifier node. + * @param ignoreAlias - Whether to ignore the alias and use the local name. + * @returns The computed name of the export specifier. + */ +function computeNodeName(node, ignoreAlias) { + let identifierToCheck = ignoreAlias ? node.local : node.exported + switch (identifierToCheck.type) { + case AST_NODE_TYPES.Identifier: + return identifierToCheck.name + case AST_NODE_TYPES.Literal: + return identifierToCheck.value + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(identifierToCheck) + } +} +export { computeNodeName } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/sort-named-export.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/sort-named-export.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..88914e1f136aef993937248236f132df7232898b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/sort-named-export.d.ts @@ -0,0 +1,13 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { TSESTree } from '@typescript-eslint/types' +import { MessageId, Options } from './types.js' +export declare let defaultOptions: Required +export declare function sortNamedExport({ + matchedAstSelectors, + context, + node, +}: { + context: TSESLint.RuleContext + matchedAstSelectors: ReadonlySet + node: TSESTree.ExportNamedDeclaration +}): void diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/sort-named-export.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/sort-named-export.js new file mode 100644 index 0000000000000000000000000000000000000000..d8d745d8dfa2a22057c9cda2dda43b8db51b9ecf --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/sort-named-export.js @@ -0,0 +1,143 @@ +import { defaultComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +import { validateNewlinesAndPartitionConfig } from '../../utils/validate-newlines-and-partition-config.js' +import { buildOptionsByGroupIndexComputer } from '../../utils/build-options-by-group-index-computer.js' +import { validateCustomSortConfig } from '../../utils/validate-custom-sort-config.js' +import { generatePredefinedGroups } from '../../utils/generate-predefined-groups.js' +import { getEslintDisabledLines } from '../../utils/get-eslint-disabled-lines.js' +import { doesCustomGroupMatch } from '../../utils/does-custom-group-match.js' +import { isNodeEslintDisabled } from '../../utils/is-node-eslint-disabled.js' +import { validateGroupsConfig } from '../../utils/validate-groups-config.js' +import { sortNodesByGroups } from '../../utils/sort-nodes-by-groups.js' +import { reportAllErrors } from '../../utils/report-all-errors.js' +import { shouldPartition } from '../../utils/should-partition.js' +import { computeGroup } from '../../utils/compute-group.js' +import { rangeToDiff } from '../../utils/range-to-diff.js' +import { getSettings } from '../../utils/get-settings.js' +import { isSortable } from '../../utils/is-sortable.js' +import { complete } from '../../utils/complete.js' +import { + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + allModifiers, + allSelectors, +} from './types.js' +import { computeNodeName } from './compute-node-name.js' +import { computeMatchedContextOptions } from './compute-matched-context-options.js' +import { computeExportKindModifier } from './compute-export-kind-modifier.js' +/** + * Cache computed groups by modifiers and selectors for performance. + */ +var cachedGroupsByModifiersAndSelectors = /* @__PURE__ */ new Map() +var defaultOptions = { + fallbackSort: { type: 'unsorted' }, + newlinesInside: 'newlinesBetween', + specialCharacters: 'keep', + partitionByNewLine: false, + partitionByComment: false, + newlinesBetween: 'ignore', + useConfigurationIf: {}, + type: 'alphabetical', + ignoreAlias: false, + customGroups: [], + ignoreCase: true, + locales: 'en-US', + alphabet: '', + order: 'asc', + groups: [], +} +function sortNamedExport({ matchedAstSelectors, context, node }) { + if (!isSortable(node.specifiers)) { + return + } + let settings = getSettings(context.settings) + let matchedContextOptions = computeMatchedContextOptions({ + matchedAstSelectors, + context, + node, + }) + let options = complete(matchedContextOptions, settings, defaultOptions) + validateCustomSortConfig(options) + validateGroupsConfig({ + modifiers: allModifiers, + selectors: allSelectors, + options, + }) + validateNewlinesAndPartitionConfig(options) + let { sourceCode, id } = context + let eslintDisabledLines = getEslintDisabledLines({ + ruleName: id, + sourceCode, + }) + let optionsByGroupIndexComputer = buildOptionsByGroupIndexComputer(options) + let formattedMembers = [[]] + for (let specifier of node.specifiers) { + let name = computeNodeName(specifier, options.ignoreAlias) + let selector = 'export' + let modifiers = [computeExportKindModifier(specifier)] + let predefinedGroups = generatePredefinedGroups({ + cache: cachedGroupsByModifiersAndSelectors, + selectors: [selector], + modifiers, + }) + let group = computeGroup({ + customGroupMatcher: customGroup => + doesCustomGroupMatch({ + selectors: [selector], + elementName: name, + customGroup, + modifiers, + }), + predefinedGroups, + options, + }) + let sortingNode = { + isEslintDisabled: isNodeEslintDisabled(specifier, eslintDisabledLines), + size: rangeToDiff(specifier, sourceCode), + node: specifier, + group, + name, + } + let lastSortingNode = formattedMembers.at(-1)?.at(-1) + if ( + shouldPartition({ + lastSortingNode, + sortingNode, + sourceCode, + options, + }) + ) { + formattedMembers.push([]) + } + formattedMembers.at(-1).push({ + ...sortingNode, + partitionId: formattedMembers.length, + }) + } + function sortNodesExcludingEslintDisabled(ignoreEslintDisabledNodes) { + return formattedMembers.flatMap(groupedNodes => + sortNodesByGroups({ + comparatorByOptionsComputer: defaultComparatorByOptionsComputer, + optionsByGroupIndexComputer, + ignoreEslintDisabledNodes, + groups: options.groups, + nodes: groupedNodes, + }), + ) + } + let nodes = formattedMembers.flat() + reportAllErrors({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + sortNodesExcludingEslintDisabled, + options, + context, + nodes, + }) +} +export { defaultOptions, sortNamedExport } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5960915340f7d4ff93587cbec84126ce3ab4274e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/types.d.ts @@ -0,0 +1,102 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +import { TSESTree } from '@typescript-eslint/types' +import { RegexOption, TypeOption } from '../../types/common-options.js' +import { AllCommonOptions } from '../../types/all-common-options.js' +import { SortingNode } from '../../types/sorting-node.js' +export type MessageId = + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +export declare const ORDER_ERROR_ID = 'unexpectedNamedExportsOrder' +export declare const GROUP_ORDER_ERROR_ID = 'unexpectedNamedExportsGroupOrder' +export declare const EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenNamedExports' +export declare const MISSED_SPACING_ERROR_ID = + 'missedSpacingBetweenNamedExports' +/** + * Configuration options for the sort-named-exports rule. + * + * Controls how named exports are sorted within export statements. + */ +export type Options = Partial< + { + /** + * Conditional configuration based on pattern matching. + */ + useConfigurationIf: { + /** + * Regular expression pattern to match against all named export element + * names. The rule is only applied when all names match this pattern. + */ + allNamesMatchPattern?: RegexOption + /** + * AST selector to match against ExportNamedDeclaration nodes. + */ + matchesAstSelector?: string + } + /** + * Whether to ignore export aliases when sorting. When true, sorts by the + * original name rather than the alias. + * + * @default false + */ + ignoreAlias: boolean + } & AllCommonOptions< + TypeOption, + AdditionalSortOptions, + CustomGroupMatchOptions + > +>[] +/** + * Extended sorting node for named export specifiers. + */ +export type SortNamedExportsSortingNode = SortingNode +/** + * Union type of all available modifiers for named exports. + * + * Modifiers distinguish between type exports and value exports. + */ +export type Modifier = (typeof allModifiers)[number] +/** + * Union type of all available selectors for named exports. + * + * Currently only includes the 'export' selector. + */ +export type Selector = (typeof allSelectors)[number] +/** + * Match options for a custom group. + */ +interface CustomGroupMatchOptions { + /** + * Array of modifiers that exports must have to match this group. Can + * include 'type' for type exports or 'value' for value exports. + */ + modifiers?: Modifier[] + /** + * The selector type this group matches. Currently only 'export' is + * available for named exports. + */ + selector?: Selector +} +type AdditionalSortOptions = object +/** + * Array of all available selectors for named exports. + * + * Used for validation and configuration in the ESLint rule. + */ +export declare let allSelectors: readonly ['export'] +/** + * Array of all available modifiers for named exports. + * + * Used for validation and configuration in the ESLint rule. + */ +export declare let allModifiers: readonly ['value', 'type'] +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +export declare let additionalCustomGroupMatchOptionsJsonSchema: Record< + string, + JSONSchema4 +> +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/types.js new file mode 100644 index 0000000000000000000000000000000000000000..f0b76fa34769f681fcb4f04daa222b7f453ce662 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-exports/types.js @@ -0,0 +1,37 @@ +import { + buildCustomGroupModifiersJsonSchema, + buildCustomGroupSelectorJsonSchema, +} from '../../utils/json-schemas/common-groups-json-schemas.js' +var ORDER_ERROR_ID = 'unexpectedNamedExportsOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedNamedExportsGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenNamedExports' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenNamedExports' +/** + * Array of all available selectors for named exports. + * + * Used for validation and configuration in the ESLint rule. + */ +var allSelectors = ['export'] +/** + * Array of all available modifiers for named exports. + * + * Used for validation and configuration in the ESLint rule. + */ +var allModifiers = ['value', 'type'] +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +var additionalCustomGroupMatchOptionsJsonSchema = { + modifiers: buildCustomGroupModifiersJsonSchema(allModifiers), + selector: buildCustomGroupSelectorJsonSchema(allSelectors), +} +export { + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + additionalCustomGroupMatchOptionsJsonSchema, + allModifiers, + allSelectors, +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b80baa0983530f21854bd188fd733b30a3ada285 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports.d.ts @@ -0,0 +1,12 @@ +import { MessageId, Options } from './sort-named-imports/types.js' +declare const _default: import('@typescript-eslint/utils/ts-eslint').RuleModule< + MessageId, + Options, + { + recommended?: boolean + }, + import('@typescript-eslint/utils/ts-eslint').RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports.js new file mode 100644 index 0000000000000000000000000000000000000000..704064a4c2e9173fbdbb62482fd4e24ed5516d77 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports.js @@ -0,0 +1,82 @@ +import { + buildCommonJsonSchemas, + buildUseConfigIfJsonSchema, + matchesAstSelectorJsonSchema, +} from '../utils/json-schemas/common-json-schemas.js' +import { buildCommonGroupsJsonSchemas } from '../utils/json-schemas/common-groups-json-schemas.js' +import { + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { + partitionByCommentJsonSchema, + partitionByNewlineJsonSchema, +} from '../utils/json-schemas/common-partition-json-schemas.js' +import { buildAstListeners } from '../utils/build-ast-listeners.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + additionalCustomGroupMatchOptionsJsonSchema, +} from './sort-named-imports/types.js' +import { + defaultOptions, + sortNamedImport, +} from './sort-named-imports/sort-named-import.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var sort_named_imports_default = createEslintRule({ + meta: { + schema: { + items: { + properties: { + ...buildCommonJsonSchemas(), + ...buildCommonGroupsJsonSchemas({ + additionalCustomGroupMatchProperties: + additionalCustomGroupMatchOptionsJsonSchema, + }), + useConfigurationIf: buildUseConfigIfJsonSchema({ + additionalProperties: { + matchesAstSelector: matchesAstSelectorJsonSchema, + }, + }), + ignoreAlias: { + description: 'Controls whether to ignore alias names.', + type: 'boolean', + }, + partitionByComment: partitionByCommentJsonSchema, + partitionByNewLine: partitionByNewlineJsonSchema, + }, + additionalProperties: false, + type: 'object', + }, + uniqueItems: true, + type: 'array', + }, + messages: { + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-named-imports', + description: 'Enforce sorted named imports.', + recommended: true, + }, + type: 'suggestion', + fixable: 'code', + }, + create: context => + buildAstListeners({ + nodeTypes: [AST_NODE_TYPES.ImportDeclaration], + sorter: sortNamedImport, + context, + }), + defaultOptions: [defaultOptions], + name: 'sort-named-imports', +}) +export { sort_named_imports_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/compute-import-kind-modifier.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/compute-import-kind-modifier.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..12729c93ddc724f91b6f27020254838bc9d0370e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/compute-import-kind-modifier.d.ts @@ -0,0 +1,4 @@ +import { TSESTree } from '@typescript-eslint/types' +export declare function computeImportKindModifier( + node: TSESTree.ImportSpecifier, +): 'value' | 'type' diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/compute-import-kind-modifier.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/compute-import-kind-modifier.js new file mode 100644 index 0000000000000000000000000000000000000000..6f1053d10a7d168cfcdfbf578644dd877a7b15c2 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/compute-import-kind-modifier.js @@ -0,0 +1,15 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +function computeImportKindModifier(node) { + let importKind = 'importKind' in node ? node.importKind : void 0 + switch (importKind) { + case void 0: + case 'value': + return 'value' + case 'type': + return 'type' + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(importKind) + } +} +export { computeImportKindModifier } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/compute-matched-context-options.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/compute-matched-context-options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d32e4347faf85182f4173a7f0cf10d01da9856e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/compute-matched-context-options.d.ts @@ -0,0 +1,23 @@ +import { RuleContext } from '@typescript-eslint/utils/ts-eslint' +import { TSESTree } from '@typescript-eslint/types' +import { MessageId, Options } from './types.js' +/** + * Computes the matched context options for a given named import node. + * + * @param params - Parameters. + * @param params.node - The named import node to compute the context options + * for. + * @param params.matchedAstSelectors - The matched AST selectors for a named + * export node. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +export declare function computeMatchedContextOptions({ + matchedAstSelectors, + context, + node, +}: { + context: Readonly> + matchedAstSelectors: ReadonlySet + node: TSESTree.ImportDeclaration +}): Options[number] | undefined diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/compute-matched-context-options.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/compute-matched-context-options.js new file mode 100644 index 0000000000000000000000000000000000000000..0ea41e17b26ded8547a775155981155eaefec0ee --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/compute-matched-context-options.js @@ -0,0 +1,43 @@ +import { passesAllNamesMatchPatternFilter } from '../../utils/context-matching/passes-all-names-match-pattern-filter.js' +import { passesAstSelectorFilter } from '../../utils/context-matching/passes-ast-selector-filter.js' +import { computeNodeName } from './compute-node-name.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the matched context options for a given named import node. + * + * @param params - Parameters. + * @param params.node - The named import node to compute the context options + * for. + * @param params.matchedAstSelectors - The matched AST selectors for a named + * export node. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +function computeMatchedContextOptions({ matchedAstSelectors, context, node }) { + return context.options.find(options => + isContextOptionMatching({ + matchedAstSelectors, + options, + node, + }), + ) +} +function isContextOptionMatching({ matchedAstSelectors, options, node }) { + if (!options.useConfigurationIf) { + return true + } + let nodeNames = node.specifiers + .filter(specifier => specifier.type === AST_NODE_TYPES.ImportSpecifier) + .map(specifier => computeNodeName(specifier, !!options.ignoreAlias)) + return ( + passesAllNamesMatchPatternFilter({ + allNamesMatchPattern: options.useConfigurationIf.allNamesMatchPattern, + nodeNames, + }) && + passesAstSelectorFilter({ + matchesAstSelector: options.useConfigurationIf.matchesAstSelector, + matchedAstSelectors, + }) + ) +} +export { computeMatchedContextOptions } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/compute-node-name.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/compute-node-name.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..51dfb726de5a2b244e0f08c752e1d0f025ee7fef --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/compute-node-name.d.ts @@ -0,0 +1,12 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Computes the name of an import specifier node. + * + * @param node - The import specifier node. + * @param ignoreAlias - Whether to ignore the alias and use the local name. + * @returns The computed name of the import specifier. + */ +export declare function computeNodeName( + node: TSESTree.ImportSpecifier, + ignoreAlias: boolean, +): string diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/compute-node-name.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/compute-node-name.js new file mode 100644 index 0000000000000000000000000000000000000000..0c2b193921227a431e9ca084aa5428a02a0219b8 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/compute-node-name.js @@ -0,0 +1,24 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the name of an import specifier node. + * + * @param node - The import specifier node. + * @param ignoreAlias - Whether to ignore the alias and use the local name. + * @returns The computed name of the import specifier. + */ +function computeNodeName(node, ignoreAlias) { + if (!ignoreAlias) { + return node.local.name + } + switch (node.imported.type) { + case AST_NODE_TYPES.Identifier: + return node.imported.name + case AST_NODE_TYPES.Literal: + return node.imported.value + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(node.imported) + } +} +export { computeNodeName } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/sort-named-import.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/sort-named-import.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f0aa2b077649cf8d1d9fd7c0c6442e7e9ffda382 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/sort-named-import.d.ts @@ -0,0 +1,13 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { TSESTree } from '@typescript-eslint/types' +import { MessageId, Options } from './types.js' +export declare let defaultOptions: Required +export declare function sortNamedImport({ + matchedAstSelectors, + context, + node, +}: { + context: TSESLint.RuleContext + matchedAstSelectors: ReadonlySet + node: TSESTree.ImportDeclaration +}): void diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/sort-named-import.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/sort-named-import.js new file mode 100644 index 0000000000000000000000000000000000000000..b9ec4578fa581235efa1afc74f2484a701c804d5 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/sort-named-import.js @@ -0,0 +1,147 @@ +import { defaultComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +import { validateNewlinesAndPartitionConfig } from '../../utils/validate-newlines-and-partition-config.js' +import { buildOptionsByGroupIndexComputer } from '../../utils/build-options-by-group-index-computer.js' +import { validateCustomSortConfig } from '../../utils/validate-custom-sort-config.js' +import { generatePredefinedGroups } from '../../utils/generate-predefined-groups.js' +import { getEslintDisabledLines } from '../../utils/get-eslint-disabled-lines.js' +import { doesCustomGroupMatch } from '../../utils/does-custom-group-match.js' +import { isNodeEslintDisabled } from '../../utils/is-node-eslint-disabled.js' +import { validateGroupsConfig } from '../../utils/validate-groups-config.js' +import { sortNodesByGroups } from '../../utils/sort-nodes-by-groups.js' +import { reportAllErrors } from '../../utils/report-all-errors.js' +import { shouldPartition } from '../../utils/should-partition.js' +import { computeGroup } from '../../utils/compute-group.js' +import { rangeToDiff } from '../../utils/range-to-diff.js' +import { getSettings } from '../../utils/get-settings.js' +import { isSortable } from '../../utils/is-sortable.js' +import { complete } from '../../utils/complete.js' +import { + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + allModifiers, + allSelectors, +} from './types.js' +import { computeNodeName } from './compute-node-name.js' +import { computeMatchedContextOptions } from './compute-matched-context-options.js' +import { computeImportKindModifier } from './compute-import-kind-modifier.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Cache computed groups by modifiers and selectors for performance. + */ +var cachedGroupsByModifiersAndSelectors = /* @__PURE__ */ new Map() +var defaultOptions = { + fallbackSort: { type: 'unsorted' }, + newlinesInside: 'newlinesBetween', + specialCharacters: 'keep', + partitionByNewLine: false, + partitionByComment: false, + newlinesBetween: 'ignore', + useConfigurationIf: {}, + type: 'alphabetical', + ignoreAlias: false, + customGroups: [], + ignoreCase: true, + locales: 'en-US', + alphabet: '', + order: 'asc', + groups: [], +} +function sortNamedImport({ matchedAstSelectors, context, node }) { + let specifiers = node.specifiers.filter( + importClause => importClause.type === AST_NODE_TYPES.ImportSpecifier, + ) + if (!isSortable(specifiers)) { + return + } + let settings = getSettings(context.settings) + let matchedContextOptions = computeMatchedContextOptions({ + matchedAstSelectors, + context, + node, + }) + let options = complete(matchedContextOptions, settings, defaultOptions) + validateCustomSortConfig(options) + validateGroupsConfig({ + modifiers: allModifiers, + selectors: allSelectors, + options, + }) + validateNewlinesAndPartitionConfig(options) + let { sourceCode, id } = context + let eslintDisabledLines = getEslintDisabledLines({ + ruleName: id, + sourceCode, + }) + let optionsByGroupIndexComputer = buildOptionsByGroupIndexComputer(options) + let formattedMembers = [[]] + for (let specifier of specifiers) { + let name = computeNodeName(specifier, options.ignoreAlias) + let selector = 'import' + let modifiers = [computeImportKindModifier(specifier)] + let predefinedGroups = generatePredefinedGroups({ + cache: cachedGroupsByModifiersAndSelectors, + selectors: [selector], + modifiers, + }) + let group = computeGroup({ + customGroupMatcher: customGroup => + doesCustomGroupMatch({ + selectors: [selector], + elementName: name, + customGroup, + modifiers, + }), + predefinedGroups, + options, + }) + let sortingNode = { + isEslintDisabled: isNodeEslintDisabled(specifier, eslintDisabledLines), + size: rangeToDiff(specifier, sourceCode), + node: specifier, + group, + name, + } + let lastSortingNode = formattedMembers.at(-1)?.at(-1) + if ( + shouldPartition({ + lastSortingNode, + sortingNode, + sourceCode, + options, + }) + ) { + formattedMembers.push([]) + } + formattedMembers.at(-1).push({ + ...sortingNode, + partitionId: formattedMembers.length, + }) + } + function sortNodesExcludingEslintDisabled(ignoreEslintDisabledNodes) { + return formattedMembers.flatMap(groupedNodes => + sortNodesByGroups({ + comparatorByOptionsComputer: defaultComparatorByOptionsComputer, + optionsByGroupIndexComputer, + ignoreEslintDisabledNodes, + groups: options.groups, + nodes: groupedNodes, + }), + ) + } + let nodes = formattedMembers.flat() + reportAllErrors({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + sortNodesExcludingEslintDisabled, + options, + context, + nodes, + }) +} +export { defaultOptions, sortNamedImport } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5cea7eb00f1cee05c0b7dd7d60b93b18bd117e3d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/types.d.ts @@ -0,0 +1,102 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +import { TSESTree } from '@typescript-eslint/types' +import { RegexOption, TypeOption } from '../../types/common-options.js' +import { AllCommonOptions } from '../../types/all-common-options.js' +import { SortingNode } from '../../types/sorting-node.js' +export type MessageId = + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +export declare const ORDER_ERROR_ID = 'unexpectedNamedImportsOrder' +export declare const GROUP_ORDER_ERROR_ID = 'unexpectedNamedImportsGroupOrder' +export declare const EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenNamedImports' +export declare const MISSED_SPACING_ERROR_ID = + 'missedSpacingBetweenNamedImports' +/** + * Configuration options for the sort-named-imports rule. + * + * Controls how named imports are sorted within import statements. + */ +export type Options = Partial< + { + /** + * Conditional configuration based on pattern matching. + */ + useConfigurationIf: { + /** + * Regular expression pattern to match against all named import element + * names. The rule is only applied when all names match this pattern. + */ + allNamesMatchPattern?: RegexOption + /** + * AST selector to match against ImportDeclaration nodes. + */ + matchesAstSelector?: string + } + /** + * Whether to ignore import aliases when sorting. When true, sorts by the + * original name rather than the alias. + * + * @default false + */ + ignoreAlias: boolean + } & AllCommonOptions< + TypeOption, + AdditionalSortOptions, + CustomGroupMatchOptions + > +>[] +/** + * Extended sorting node for named import specifiers. + */ +export type SortNamedImportsSortingNode = SortingNode +/** + * Union type of all available modifiers for named imports. + * + * Modifiers distinguish between type imports and value imports. + */ +export type Modifier = (typeof allModifiers)[number] +/** + * Union type of all available selectors for named imports. + * + * Currently only includes the 'import' selector. + */ +export type Selector = (typeof allSelectors)[number] +/** + * Match options for a custom group. + */ +interface CustomGroupMatchOptions { + /** + * Array of modifiers that imports must have to match this group. Can + * include 'type' for type imports or 'value' for value imports. + */ + modifiers?: Modifier[] + /** + * The selector type this group matches. Currently only 'import' is + * available for named imports. + */ + selector?: Selector +} +type AdditionalSortOptions = object +/** + * Array of all available selectors for named imports. + * + * Used for validation and configuration in the ESLint rule. + */ +export declare let allSelectors: readonly ['import'] +/** + * Array of all available modifiers for named imports. + * + * Used for validation and configuration in the ESLint rule. + */ +export declare let allModifiers: readonly ['value', 'type'] +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +export declare let additionalCustomGroupMatchOptionsJsonSchema: Record< + string, + JSONSchema4 +> +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/types.js new file mode 100644 index 0000000000000000000000000000000000000000..570a550908feb8fab1e09eeb3e9254faa3e9c045 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-named-imports/types.js @@ -0,0 +1,37 @@ +import { + buildCustomGroupModifiersJsonSchema, + buildCustomGroupSelectorJsonSchema, +} from '../../utils/json-schemas/common-groups-json-schemas.js' +var ORDER_ERROR_ID = 'unexpectedNamedImportsOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedNamedImportsGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenNamedImports' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenNamedImports' +/** + * Array of all available selectors for named imports. + * + * Used for validation and configuration in the ESLint rule. + */ +var allSelectors = ['import'] +/** + * Array of all available modifiers for named imports. + * + * Used for validation and configuration in the ESLint rule. + */ +var allModifiers = ['value', 'type'] +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +var additionalCustomGroupMatchOptionsJsonSchema = { + modifiers: buildCustomGroupModifiersJsonSchema(allModifiers), + selector: buildCustomGroupSelectorJsonSchema(allSelectors), +} +export { + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + additionalCustomGroupMatchOptionsJsonSchema, + allModifiers, + allSelectors, +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..263fe94540e9dba43fbbd21025ec8399d70327ac --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types.d.ts @@ -0,0 +1,24 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +import { Options } from './sort-object-types/types.js' +declare const ORDER_ERROR_ID = 'unexpectedObjectTypesOrder' +declare const GROUP_ORDER_ERROR_ID = 'unexpectedObjectTypesGroupOrder' +declare const EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenObjectTypeMembers' +declare const MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenObjectTypeMembers' +type MessageId = + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +export declare let defaultOptions: Required +export declare let jsonSchema: JSONSchema4 +declare const _default: import('@typescript-eslint/utils/ts-eslint').RuleModule< + MessageId, + Options, + { + recommended?: boolean + }, + import('@typescript-eslint/utils/ts-eslint').RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types.js new file mode 100644 index 0000000000000000000000000000000000000000..87fcb7609d67dafe7c23b09e925ed5c09f5cee03 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types.js @@ -0,0 +1,132 @@ +import { + buildCommonJsonSchemas, + buildUseConfigIfJsonSchema, + matchesAstSelectorJsonSchema, +} from '../utils/json-schemas/common-json-schemas.js' +import { buildCommonGroupsJsonSchemas } from '../utils/json-schemas/common-groups-json-schemas.js' +import { + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { + partitionByCommentJsonSchema, + partitionByNewlineJsonSchema, +} from '../utils/json-schemas/common-partition-json-schemas.js' +import { computeParentNodesWithTypes } from '../utils/compute-parent-nodes-with-types.js' +import { buildAstListeners } from '../utils/build-ast-listeners.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { + additionalCustomGroupMatchOptionsJsonSchema, + additionalSortOptionsJsonSchema, + objectTypeParentTypes, +} from './sort-object-types/types.js' +import { scopedRegexJsonSchema } from '../utils/json-schemas/scoped-regex-json-schema.js' +import { sortObjectTypeElements } from './sort-object-types/sort-object-type-elements.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var ORDER_ERROR_ID = 'unexpectedObjectTypesOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedObjectTypesGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenObjectTypeMembers' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenObjectTypeMembers' +var defaultOptions = { + fallbackSort: { + type: 'unsorted', + sortBy: 'name', + }, + newlinesInside: 'newlinesBetween', + partitionByComment: false, + partitionByNewLine: false, + newlinesBetween: 'ignore', + specialCharacters: 'keep', + useConfigurationIf: {}, + type: 'alphabetical', + ignoreCase: true, + customGroups: [], + locales: 'en-US', + sortBy: 'name', + alphabet: '', + order: 'asc', + groups: [], +} +var jsonSchema = { + items: { + properties: { + ...buildCommonJsonSchemas({ + additionalSortProperties: additionalSortOptionsJsonSchema, + }), + ...buildCommonGroupsJsonSchemas({ + additionalCustomGroupMatchProperties: + additionalCustomGroupMatchOptionsJsonSchema, + additionalSortProperties: additionalSortOptionsJsonSchema, + }), + useConfigurationIf: buildUseConfigIfJsonSchema({ + additionalProperties: { + hasNumericKeysOnly: { + description: + 'Specifies whether to only match types that have exclusively numeric keys.', + type: 'boolean', + }, + declarationCommentMatchesPattern: scopedRegexJsonSchema, + matchesAstSelector: matchesAstSelectorJsonSchema, + declarationMatchesPattern: scopedRegexJsonSchema, + }, + }), + partitionByComment: partitionByCommentJsonSchema, + partitionByNewLine: partitionByNewlineJsonSchema, + }, + additionalProperties: false, + type: 'object', + }, + uniqueItems: true, + type: 'array', +} +var sort_object_types_default = createEslintRule({ + meta: { + messages: { + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-object-types', + description: 'Enforce sorted object types.', + recommended: true, + }, + schema: jsonSchema, + type: 'suggestion', + fixable: 'code', + }, + create: context => + buildAstListeners({ + nodeTypes: [AST_NODE_TYPES.TSTypeLiteral], + sorter: sortObjectType, + context, + }), + defaultOptions: [defaultOptions], + name: 'sort-object-types', +}) +function sortObjectType({ matchedAstSelectors, context, node }) { + sortObjectTypeElements({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + parentNodes: computeObjectTypeParentNodes(node), + elements: node.members, + matchedAstSelectors, + context, + }) +} +function computeObjectTypeParentNodes(node) { + return computeParentNodesWithTypes({ + allowedTypes: [...objectTypeParentTypes], + consecutiveOnly: false, + maxParent: null, + node, + }) +} +export { sort_object_types_default as default, defaultOptions, jsonSchema } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/comparator-by-options-computer.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/comparator-by-options-computer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fa17b06f4d8c811dd37059bfc698cb2171984efb --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/comparator-by-options-computer.d.ts @@ -0,0 +1,6 @@ +import { ComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +import { SortObjectTypesSortingNode, Options } from './types.js' +export declare let comparatorByOptionsComputer: ComparatorByOptionsComputer< + Required, + SortObjectTypesSortingNode +> diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/comparator-by-options-computer.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/comparator-by-options-computer.js new file mode 100644 index 0000000000000000000000000000000000000000..ed729dac04ed851780dd90ea00f5282403450181 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/comparator-by-options-computer.js @@ -0,0 +1,39 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { buildLineLengthComparator } from '../../utils/compare/build-line-length-comparator.js' +import { compareAlphabetically } from '../../utils/compare/compare-alphabetically.js' +import { compareByCustomSort } from '../../utils/compare/compare-by-custom-sort.js' +import { unsortedComparator } from '../../utils/compare/unsorted-comparator.js' +import { compareNaturally } from '../../utils/compare/compare-naturally.js' +import { defaultComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +var comparatorByOptionsComputer = options => { + switch (options.sortBy) { + case 'value': + return byValueComparatorComputer(options) + case 'name': + return defaultComparatorByOptionsComputer(options) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(options.sortBy) + } +} +var byValueComparatorComputer = options => { + switch (options.type) { + /* v8 ignore next 2 -- @preserve Untested for now as not a relevant sort for this rule. */ + case 'subgroup-order': + return defaultComparatorByOptionsComputer(options) + case 'alphabetical': + return (a, b) => compareAlphabetically(a.value, b.value, options) + case 'line-length': + return buildLineLengthComparator(options) + case 'unsorted': + return unsortedComparator + case 'natural': + return (a, b) => compareNaturally(a.value, b.value, options) + case 'custom': + return (a, b) => compareByCustomSort(a.value, b.value, options) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(options.type) + } +} +export { comparatorByOptionsComputer } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/compute-matched-context-options.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/compute-matched-context-options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bfaddf7b397db3e0054c3b12759156e381cacbe5 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/compute-matched-context-options.d.ts @@ -0,0 +1,26 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +import { ObjectTypeParent, Options } from './types.js' +/** + * Computes the matched context options for the given nodes. + * + * @param params - The parameters. + * @param params.sourceCode - The source code object. + * @param params.parentNodes - The parent nodes of the type elements. + * @param params.elements - The type elements. + * @param params.context - The rule context. + * @returns The matched context options, or undefined if none match. + */ +export declare function computeMatchedContextOptions({ + matchedAstSelectors, + parentNodes, + sourceCode, + elements, + context, +}: { + context: TSESLint.RuleContext + matchedAstSelectors: ReadonlySet + elements: TSESTree.TypeElement[] + parentNodes: ObjectTypeParent[] + sourceCode: TSESLint.SourceCode +}): Options[number] | undefined diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/compute-matched-context-options.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/compute-matched-context-options.js new file mode 100644 index 0000000000000000000000000000000000000000..c13175b3198ada898b994844adccf946cd24bfea --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/compute-matched-context-options.js @@ -0,0 +1,106 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { passesAllNamesMatchPatternFilter } from '../../utils/context-matching/passes-all-names-match-pattern-filter.js' +import { passesAstSelectorFilter } from '../../utils/context-matching/passes-ast-selector-filter.js' +import { passesDeclarationMatchesPatternFilter } from './passes-declaration-matches-pattern-filter.js' +import { passesDeclarationCommentMatchesFilter } from './passes-declaration-comment-matches-filter.js' +import { computeNodeName } from './compute-node-name.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the matched context options for the given nodes. + * + * @param params - The parameters. + * @param params.sourceCode - The source code object. + * @param params.parentNodes - The parent nodes of the type elements. + * @param params.elements - The type elements. + * @param params.context - The rule context. + * @returns The matched context options, or undefined if none match. + */ +function computeMatchedContextOptions({ + matchedAstSelectors, + parentNodes, + sourceCode, + elements, + context, +}) { + return context.options.find(options => + isContextOptionMatching({ + nodeNames: elements.map(node => + computeNodeName({ + sourceCode, + node, + }), + ), + matchedAstSelectors, + parentNodes, + sourceCode, + elements, + options, + }), + ) +} +function isContextOptionMatching({ + matchedAstSelectors, + parentNodes, + sourceCode, + nodeNames, + elements, + options, +}) { + if (!options.useConfigurationIf) { + return true + } + return ( + passesAllNamesMatchPatternFilter({ + allNamesMatchPattern: options.useConfigurationIf.allNamesMatchPattern, + nodeNames, + }) && + passesDeclarationMatchesPatternFilter({ + declarationMatchesPattern: + options.useConfigurationIf.declarationMatchesPattern, + parentNodes, + sourceCode, + }) && + passesHasNumericKeysOnlyFilter({ + hasNumericKeysOnlyFilter: options.useConfigurationIf.hasNumericKeysOnly, + typeElements: elements, + }) && + passesDeclarationCommentMatchesFilter({ + declarationCommentMatchesPattern: + options.useConfigurationIf.declarationCommentMatchesPattern, + parentNodes, + sourceCode, + }) && + passesAstSelectorFilter({ + matchesAstSelector: options.useConfigurationIf.matchesAstSelector, + matchedAstSelectors, + }) + ) +} +function passesHasNumericKeysOnlyFilter({ + hasNumericKeysOnlyFilter, + typeElements, +}) { + let hasOnlyNumericKeys = hasNumericKeysOnly() + switch (hasNumericKeysOnlyFilter) { + case void 0: + return true + case false: + return !hasOnlyNumericKeys + case true: + return hasOnlyNumericKeys + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(hasNumericKeysOnlyFilter) + } + function hasNumericKeysOnly() { + return typeElements.every(isNumericKey) + function isNumericKey(typeElement) { + return ( + typeElement.type === AST_NODE_TYPES.TSPropertySignature && + typeElement.key.type === AST_NODE_TYPES.Literal && + typeof typeElement.key.value === 'number' + ) + } + } +} +export { computeMatchedContextOptions } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/compute-node-name.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/compute-node-name.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..512b7936ba910ad79a2a47a3c5395a652ef51b0e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/compute-node-name.d.ts @@ -0,0 +1,17 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +/** + * Computes the name of an object-type-like node. + * + * @param props - The parameters object. + * @param props.sourceCode - ESLint source code object for text extraction. + * @param props.node - The AST node representing an object-type-like node. + * @returns The name of the object-type like node. + */ +export declare function computeNodeName({ + sourceCode, + node, +}: { + sourceCode: TSESLint.SourceCode + node: TSESTree.TypeElement +}): string diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/compute-node-name.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/compute-node-name.js new file mode 100644 index 0000000000000000000000000000000000000000..74929882d1edcb4a1659a08fa410ea4300bc85b7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/compute-node-name.js @@ -0,0 +1,56 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the name of an object-type-like node. + * + * @param props - The parameters object. + * @param props.sourceCode - ESLint source code object for text extraction. + * @param props.node - The AST node representing an object-type-like node. + * @returns The name of the object-type like node. + */ +function computeNodeName({ sourceCode, node }) { + switch (node.type) { + case AST_NODE_TYPES.TSConstructSignatureDeclaration: + case AST_NODE_TYPES.TSCallSignatureDeclaration: + return formatName(sourceCode.getText(node)) + case AST_NODE_TYPES.TSPropertySignature: + return computePropertySignatureName(node, sourceCode) + case AST_NODE_TYPES.TSMethodSignature: + return computeMethodSignatureName(node, sourceCode) + case AST_NODE_TYPES.TSIndexSignature: + return computeIndexSignatureName(node, sourceCode) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(node) + } +} +function computePropertySignatureName(node, sourceCode) { + switch (node.key.type) { + case AST_NODE_TYPES.Identifier: + return node.key.name + case AST_NODE_TYPES.Literal: + return String(node.key.value) + default: { + let endIndex = + node.typeAnnotation?.range.at(0) ?? + node.range.at(1) - (node.optional ? 1 : 0) + return sourceCode.text.slice(node.range.at(0), endIndex) + } + } +} +function computeMethodSignatureName(node, sourceCode) { + /* v8 ignore else -- @preserve Unsure if we can reach it. */ + if ('name' in node.key) { + return node.key.name + } + /* v8 ignore next -- @preserve Unsure if we can reach it. */ + return formatName(sourceCode.getText(node)) +} +function computeIndexSignatureName(node, sourceCode) { + let endIndex = node.typeAnnotation?.range.at(0) ?? node.range.at(1) + return formatName(sourceCode.text.slice(node.range.at(0), endIndex)) +} +function formatName(value) { + return value.replace(/[,;]$/u, '') +} +export { computeNodeName } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/compute-node-parent-name.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/compute-node-parent-name.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d8a37385d8357df34ab78b63b869fcfbdf2564a6 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/compute-node-parent-name.d.ts @@ -0,0 +1,13 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { ObjectTypeParent } from './types.js' +/** + * Computes the name of an object-type-like parent node. + * + * @param node - The AST node representing an object-type-like node. + * @param sourceCode - ESLint source code object for text extraction. + * @returns The name of the object-type like node. + */ +export declare function computeNodeParentName( + node: ObjectTypeParent, + sourceCode: TSESLint.SourceCode, +): string diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/compute-node-parent-name.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/compute-node-parent-name.js new file mode 100644 index 0000000000000000000000000000000000000000..2c508490f41279d1bb35006f7f033676d7e78110 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/compute-node-parent-name.js @@ -0,0 +1,45 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the name of an object-type-like parent node. + * + * @param node - The AST node representing an object-type-like node. + * @param sourceCode - ESLint source code object for text extraction. + * @returns The name of the object-type like node. + */ +function computeNodeParentName(node, sourceCode) { + switch (node.type) { + case AST_NODE_TYPES.TSTypeAliasDeclaration: + case AST_NODE_TYPES.TSInterfaceDeclaration: + return node.id.name + case AST_NODE_TYPES.TSPropertySignature: + case AST_NODE_TYPES.PropertyDefinition: + return computePropertyName(node, sourceCode) + case AST_NODE_TYPES.VariableDeclarator: + return computeVariableDeclaratorName(node, sourceCode) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(node) + } +} +function computePropertyName(propertySignature, sourceCode) { + switch (propertySignature.key.type) { + case AST_NODE_TYPES.Identifier: + return propertySignature.key.name + case AST_NODE_TYPES.Literal: + return String(propertySignature.key.value) + /* v8 ignore next 2 -- @preserve Unsure how we can reach that case */ + default: + return sourceCode.getText(propertySignature.key) + } +} +function computeVariableDeclaratorName(variableDeclarator, sourceCode) { + if (!variableDeclarator.id.typeAnnotation) { + return sourceCode.getText(variableDeclarator.id) + } + return sourceCode.text.slice( + variableDeclarator.id.range[0], + variableDeclarator.id.typeAnnotation.range[0], + ) +} +export { computeNodeParentName } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/is-member-optional.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/is-member-optional.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..884ce9959bd66c3ab4e37cd410d7c5eb9917aabf --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/is-member-optional.d.ts @@ -0,0 +1,17 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Checks if a TypeScript type member is marked as optional. + * + * Determines whether a property or method signature in a TypeScript type or + * interface is optional (marked with '?'). Used for grouping optional and + * required members separately during sorting. + * + * @param node - AST node to check. + * @returns True if the member is optional, false otherwise. + */ +export declare function isMemberOptional( + node: + | TSESTree.TSPropertySignature + | TSESTree.TSMethodSignature + | TSESTree.TSIndexSignature, +): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/is-member-optional.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/is-member-optional.js new file mode 100644 index 0000000000000000000000000000000000000000..a7be1025aaa099831ce304901e50275edbd8277e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/is-member-optional.js @@ -0,0 +1,25 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Checks if a TypeScript type member is marked as optional. + * + * Determines whether a property or method signature in a TypeScript type or + * interface is optional (marked with '?'). Used for grouping optional and + * required members separately during sorting. + * + * @param node - AST node to check. + * @returns True if the member is optional, false otherwise. + */ +function isMemberOptional(node) { + switch (node.type) { + case AST_NODE_TYPES.TSPropertySignature: + case AST_NODE_TYPES.TSMethodSignature: + return node.optional + case AST_NODE_TYPES.TSIndexSignature: + return false + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(node) + } +} +export { isMemberOptional } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/is-node-function-type.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/is-node-function-type.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1369b304fb23274228f0261c6acdfa416ed3aa07 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/is-node-function-type.d.ts @@ -0,0 +1,57 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Determines if an AST node represents a function type. + * + * Recursively checks if a TypeScript node represents a function or method type. + * Handles various TypeScript type constructs including: + * + * - Method signatures (e.g., `method(): void`) + * - Function types (e.g., `() => void`) + * - Union types where all members are functions (e.g., `(() => void) | ((x: + * number) => void)`) + * - Intersection types where all members are functions + * - Property signatures with function type annotations (e.g., `prop: () => + * void`). + * + * Used in sorting rules to identify and group function-like members separately + * from regular properties. + * + * @example + * + * ```ts + * // Method signature + * const methodNode = { type: 'TSMethodSignature', ... }; + * isNodeFunctionType(methodNode); // Returns: true + * ``` + * + * @example + * + * ```ts + * // Property with function type + * const propNode = { + * type: 'TSPropertySignature', + * typeAnnotation: { + * typeAnnotation: { type: 'TSFunctionType', ... } + * } + * }; + * isNodeFunctionType(propNode); // Returns: true + * ``` + * + * @example + * + * ```ts + * // Union of function types + * const unionNode = { + * type: 'TSUnionType', + * types: [ + * { type: 'TSFunctionType', ... }, + * { type: 'TSFunctionType', ... } + * ] + * }; + * isNodeFunctionType(unionNode); // Returns: true + * ``` + * + * @param node - TypeScript AST node to check. + * @returns True if the node represents a function type, false otherwise. + */ +export declare function isNodeFunctionType(node: TSESTree.Node): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/is-node-function-type.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/is-node-function-type.js new file mode 100644 index 0000000000000000000000000000000000000000..2ae7b6e3abdaf62e7173684e13c364796e0637fa --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/is-node-function-type.js @@ -0,0 +1,79 @@ +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Determines if an AST node represents a function type. + * + * Recursively checks if a TypeScript node represents a function or method type. + * Handles various TypeScript type constructs including: + * + * - Method signatures (e.g., `method(): void`) + * - Function types (e.g., `() => void`) + * - Union types where all members are functions (e.g., `(() => void) | ((x: + * number) => void)`) + * - Intersection types where all members are functions + * - Property signatures with function type annotations (e.g., `prop: () => + * void`). + * + * Used in sorting rules to identify and group function-like members separately + * from regular properties. + * + * @example + * + * ```ts + * // Method signature + * const methodNode = { type: 'TSMethodSignature', ... }; + * isNodeFunctionType(methodNode); // Returns: true + * ``` + * + * @example + * + * ```ts + * // Property with function type + * const propNode = { + * type: 'TSPropertySignature', + * typeAnnotation: { + * typeAnnotation: { type: 'TSFunctionType', ... } + * } + * }; + * isNodeFunctionType(propNode); // Returns: true + * ``` + * + * @example + * + * ```ts + * // Union of function types + * const unionNode = { + * type: 'TSUnionType', + * types: [ + * { type: 'TSFunctionType', ... }, + * { type: 'TSFunctionType', ... } + * ] + * }; + * isNodeFunctionType(unionNode); // Returns: true + * ``` + * + * @param node - TypeScript AST node to check. + * @returns True if the node represents a function type, false otherwise. + */ +function isNodeFunctionType(node) { + let currentNode = node + while ( + currentNode.type === AST_NODE_TYPES.TSPropertySignature && + currentNode.typeAnnotation + ) { + currentNode = currentNode.typeAnnotation.typeAnnotation + } + if ( + currentNode.type === AST_NODE_TYPES.TSMethodSignature || + currentNode.type === AST_NODE_TYPES.TSFunctionType + ) { + return true + } + if ( + currentNode.type === AST_NODE_TYPES.TSUnionType || + currentNode.type === AST_NODE_TYPES.TSIntersectionType + ) { + return currentNode.types.every(isNodeFunctionType) + } + return false +} +export { isNodeFunctionType } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/passes-declaration-comment-matches-filter.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/passes-declaration-comment-matches-filter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..747242240729a244ccbf51111997f653f62c6128 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/passes-declaration-comment-matches-filter.d.ts @@ -0,0 +1,21 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { ScopedRegexOption } from '../../types/scoped-regex-option.js' +import { ObjectTypeParent } from './types.js' +/** + * Checks if the object passes the declaration comment matches filter. + * + * @param params - Parameters. + * @param params.declarationCommentMatchesPattern - The pattern to evaluate. + * @param params.parentNodes - The parent nodes of the object type. + * @param params.sourceCode - The source code object. + * @returns True if the object type passes the filter, false otherwise. + */ +export declare function passesDeclarationCommentMatchesFilter({ + declarationCommentMatchesPattern, + parentNodes, + sourceCode, +}: { + declarationCommentMatchesPattern: ScopedRegexOption | undefined + parentNodes: ObjectTypeParent[] + sourceCode: TSESLint.SourceCode +}): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/passes-declaration-comment-matches-filter.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/passes-declaration-comment-matches-filter.js new file mode 100644 index 0000000000000000000000000000000000000000..b5eeb291b99261ad455723322b248990b5ffded8 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/passes-declaration-comment-matches-filter.js @@ -0,0 +1,49 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { objectTypeParentTypes } from './types.js' +import { matchesScopedExpressions } from '../../utils/scoped-regex/matches-scoped-expressions.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Checks if the object passes the declaration comment matches filter. + * + * @param params - Parameters. + * @param params.declarationCommentMatchesPattern - The pattern to evaluate. + * @param params.parentNodes - The parent nodes of the object type. + * @param params.sourceCode - The source code object. + * @returns True if the object type passes the filter, false otherwise. + */ +function passesDeclarationCommentMatchesFilter({ + declarationCommentMatchesPattern, + parentNodes, + sourceCode, +}) { + return matchesScopedExpressions({ + nodeValuesComputer: buildNodeValuesComputer(sourceCode), + scopedRegexOption: declarationCommentMatchesPattern, + allowedNodeTypes: new Set(objectTypeParentTypes), + parentNodes, + }) +} +function computeRelevantNodeForComment(objectParent) { + let objectParentType = objectParent.type + switch (objectParentType) { + case AST_NODE_TYPES.TSInterfaceDeclaration: + case AST_NODE_TYPES.TSTypeAliasDeclaration: + case AST_NODE_TYPES.TSPropertySignature: + case AST_NODE_TYPES.PropertyDefinition: + return objectParent + case AST_NODE_TYPES.VariableDeclarator: + return objectParent.parent + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(objectParentType) + } +} +function buildNodeValuesComputer(sourceCode) { + return node => { + let nodeForComment = computeRelevantNodeForComment(node) + return sourceCode + .getCommentsBefore(nodeForComment) + .map(comment => comment.value.trim()) + } +} +export { passesDeclarationCommentMatchesFilter } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/passes-declaration-matches-pattern-filter.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/passes-declaration-matches-pattern-filter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..060d28044e30c91014240ea9c95b828a44821849 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/passes-declaration-matches-pattern-filter.d.ts @@ -0,0 +1,22 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { ScopedRegexOption } from '../../types/scoped-regex-option.js' +import { ObjectTypeParent } from './types.js' +/** + * Checks whether the parent node's name matches the given pattern. + * + * @param params - The parameters object. + * @param params.declarationMatchesPattern - The regex pattern to match against. + * @param params.parentNodes - The parent nodes to check. + * @param params.sourceCode - The source code object. + * @returns True if the parent node's name passes the pattern filter, false + * otherwise. + */ +export declare function passesDeclarationMatchesPatternFilter({ + declarationMatchesPattern, + parentNodes, + sourceCode, +}: { + declarationMatchesPattern: ScopedRegexOption | undefined + parentNodes: ObjectTypeParent[] + sourceCode: TSESLint.SourceCode +}): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/passes-declaration-matches-pattern-filter.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/passes-declaration-matches-pattern-filter.js new file mode 100644 index 0000000000000000000000000000000000000000..6c9033ae331a5a02aca7c80c235a568859fb7ea5 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/passes-declaration-matches-pattern-filter.js @@ -0,0 +1,29 @@ +import { objectTypeParentTypes } from './types.js' +import { matchesScopedExpressions } from '../../utils/scoped-regex/matches-scoped-expressions.js' +import { computeNodeParentName } from './compute-node-parent-name.js' +/** + * Checks whether the parent node's name matches the given pattern. + * + * @param params - The parameters object. + * @param params.declarationMatchesPattern - The regex pattern to match against. + * @param params.parentNodes - The parent nodes to check. + * @param params.sourceCode - The source code object. + * @returns True if the parent node's name passes the pattern filter, false + * otherwise. + */ +function passesDeclarationMatchesPatternFilter({ + declarationMatchesPattern, + parentNodes, + sourceCode, +}) { + return matchesScopedExpressions({ + nodeValuesComputer: buildNodeValuesComputer(sourceCode), + allowedNodeTypes: new Set(objectTypeParentTypes), + scopedRegexOption: declarationMatchesPattern, + parentNodes, + }) +} +function buildNodeValuesComputer(sourceCode) { + return node => [computeNodeParentName(node, sourceCode)] +} +export { passesDeclarationMatchesPatternFilter } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/sort-object-type-elements.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/sort-object-type-elements.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8b2ee8b72f744f499d7af28dbb81eb13a5678b6b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/sort-object-type-elements.d.ts @@ -0,0 +1,21 @@ +import { RuleContext } from '@typescript-eslint/utils/ts-eslint' +import { TSESTree } from '@typescript-eslint/types' +import { ObjectTypeParent, Options } from './types.js' +export declare function sortObjectTypeElements({ + availableMessageIds, + matchedAstSelectors, + parentNodes, + elements, + context, +}: { + availableMessageIds: { + missedSpacingBetweenMembers: MessageIds + extraSpacingBetweenMembers: MessageIds + unexpectedGroupOrder: MessageIds + unexpectedOrder: MessageIds + } + context: RuleContext + matchedAstSelectors: ReadonlySet + elements: TSESTree.TypeElement[] + parentNodes: ObjectTypeParent[] +}): void diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/sort-object-type-elements.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/sort-object-type-elements.js new file mode 100644 index 0000000000000000000000000000000000000000..31ac275a42fdf422feb1069e1147f3e4dff59bfb --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/sort-object-type-elements.js @@ -0,0 +1,182 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { validateNewlinesAndPartitionConfig } from '../../utils/validate-newlines-and-partition-config.js' +import { buildOptionsByGroupIndexComputer } from '../../utils/build-options-by-group-index-computer.js' +import { validateCustomSortConfig } from '../../utils/validate-custom-sort-config.js' +import { generatePredefinedGroups } from '../../utils/generate-predefined-groups.js' +import { getEslintDisabledLines } from '../../utils/get-eslint-disabled-lines.js' +import { doesCustomGroupMatch } from '../../utils/does-custom-group-match.js' +import { isNodeEslintDisabled } from '../../utils/is-node-eslint-disabled.js' +import { validateGroupsConfig } from '../../utils/validate-groups-config.js' +import { sortNodesByGroups } from '../../utils/sort-nodes-by-groups.js' +import { reportAllErrors } from '../../utils/report-all-errors.js' +import { shouldPartition } from '../../utils/should-partition.js' +import { computeGroup } from '../../utils/compute-group.js' +import { rangeToDiff } from '../../utils/range-to-diff.js' +import { getSettings } from '../../utils/get-settings.js' +import { isSortable } from '../../utils/is-sortable.js' +import { complete } from '../../utils/complete.js' +import { allModifiers, allSelectors } from './types.js' +import { computeNodeName } from './compute-node-name.js' +import { computeMatchedContextOptions } from './compute-matched-context-options.js' +import { comparatorByOptionsComputer } from './comparator-by-options-computer.js' +import { isNodeOnSingleLine } from '../../utils/is-node-on-single-line.js' +import { isNodeFunctionType } from './is-node-function-type.js' +import { isMemberOptional } from './is-member-optional.js' +import { defaultOptions } from '../sort-object-types.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Cache computed groups by modifiers and selectors for performance. + */ +var cachedGroupsByModifiersAndSelectors = /* @__PURE__ */ new Map() +function sortObjectTypeElements({ + availableMessageIds, + matchedAstSelectors, + parentNodes, + elements, + context, +}) { + if (!isSortable(elements)) { + return + } + let settings = getSettings(context.settings) + let { sourceCode, id } = context + let matchedContextOptions = computeMatchedContextOptions({ + matchedAstSelectors, + parentNodes, + sourceCode, + elements, + context, + }) + let options = complete(matchedContextOptions, settings, defaultOptions) + validateCustomSortConfig(options) + validateGroupsConfig({ + selectors: allSelectors, + modifiers: allModifiers, + options, + }) + validateNewlinesAndPartitionConfig(options) + let eslintDisabledLines = getEslintDisabledLines({ + ruleName: id, + sourceCode, + }) + let optionsByGroupIndexComputer = buildOptionsByGroupIndexComputer(options) + let formattedMembers = [[]] + for (let typeElement of elements) { + if ( + typeElement.type === AST_NODE_TYPES.TSCallSignatureDeclaration || + typeElement.type === AST_NODE_TYPES.TSConstructSignatureDeclaration + ) { + formattedMembers.push([]) + continue + } + let lastGroup = formattedMembers.at(-1) + let lastSortingNode = lastGroup?.at(-1) + let selectors = [] + let modifiers = [] + if (typeElement.type === AST_NODE_TYPES.TSIndexSignature) { + selectors.push('index-signature') + } + if (isNodeFunctionType(typeElement)) { + selectors.push('method') + } + if (!isNodeOnSingleLine(typeElement)) { + modifiers.push('multiline') + } + if ( + ['index-signature', 'method'].every( + selector => !selectors.includes(selector), + ) + ) { + selectors.push('property') + } + selectors.push('member') + if (isMemberOptional(typeElement)) { + modifiers.push('optional') + } else { + modifiers.push('required') + } + let name = computeNodeName({ + node: typeElement, + sourceCode, + }) + let value = null + if ( + typeElement.type === AST_NODE_TYPES.TSPropertySignature && + typeElement.typeAnnotation + ) { + value = sourceCode.getText(typeElement.typeAnnotation.typeAnnotation) + } + let predefinedGroups = generatePredefinedGroups({ + cache: cachedGroupsByModifiersAndSelectors, + selectors, + modifiers, + }) + let group = computeGroup({ + customGroupMatcher: customGroup => + doesCustomGroupMatch({ + elementValue: value, + elementName: name, + customGroup, + selectors, + modifiers, + }), + predefinedGroups, + options, + }) + let sortingNode = { + isEslintDisabled: isNodeEslintDisabled(typeElement, eslintDisabledLines), + size: rangeToDiff(typeElement, sourceCode), + addSafetySemicolonWhenInline: true, + value: value ?? '', + node: typeElement, + group, + name, + } + if ( + shouldPartition({ + lastSortingNode, + sortingNode, + sourceCode, + options, + }) + ) { + lastGroup = [] + formattedMembers.push(lastGroup) + } + lastGroup?.push({ + ...sortingNode, + partitionId: formattedMembers.length, + }) + } + let nodes = formattedMembers.flat() + reportAllErrors({ + sortNodesExcludingEslintDisabled, + availableMessageIds, + options, + context, + nodes, + }) + function sortNodesExcludingEslintDisabled(ignoreEslintDisabledNodes) { + return formattedMembers.flatMap(groupedNodes => + sortNodesByGroups({ + isNodeIgnoredForGroup: ({ groupOptions, node }) => { + switch (groupOptions.sortBy) { + case 'value': + return !node.value + case 'name': + return false + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(groupOptions.sortBy) + } + }, + optionsByGroupIndexComputer, + comparatorByOptionsComputer, + ignoreEslintDisabledNodes, + groups: options.groups, + nodes: groupedNodes, + }), + ) + } +} +export { sortObjectTypeElements } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bbdcc458574c08569d8486ce9d1d4934f5860747 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/types.d.ts @@ -0,0 +1,145 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +import { TSESTree } from '@typescript-eslint/types' +import { RegexOption, TypeOption } from '../../types/common-options.js' +import { ScopedRegexOption } from '../../types/scoped-regex-option.js' +import { AllCommonOptions } from '../../types/all-common-options.js' +import { SortingNode } from '../../types/sorting-node.js' +import { NodeOfType } from '../../types/node-of-type.js' +/** + * Configuration options for the sort-object-types rule. + * + * Controls how object type properties, methods, and index signatures are sorted + * within TypeScript type literals and interfaces. + */ +export type Options = Partial< + { + /** + * Conditional configuration based on pattern matching. Allows applying the + * rule only when specific conditions are met. + */ + useConfigurationIf: { + /** + * Regular expression pattern to match against the comment declaration. + * The rule is only applied to declaration comments with matching + * names. + */ + declarationCommentMatchesPattern?: ScopedRegexOption + /** + * Regular expression pattern to match against the type declaration + * name. The rule is only applied to declarations with matching names. + */ + declarationMatchesPattern?: ScopedRegexOption + /** + * Regular expression pattern to match against all member names. The + * rule is only applied when all member names match this pattern. + */ + allNamesMatchPattern?: RegexOption + /** + * Specifies whether to only match types that have exclusively numeric + * keys. + */ + hasNumericKeysOnly?: boolean + /** + * An ESLint AST selector to match against the node being sorted. The + * rule is only applied when the node matches this selector. + */ + matchesAstSelector?: string + } + } & AllCommonOptions< + TypeOption, + AdditionalSortOptions, + CustomGroupMatchOptions + > +>[] +/** + * Extended sorting node for object type members. + * + * Represents an object type member with additional metadata needed for sorting, + * including whether the member is optional/required and its type annotation + * value. + */ +export interface SortObjectTypesSortingNode extends SortingNode { + /** + * The string representation of the member's type annotation. Used when + * sorting by value instead of name. + */ + value: string +} +interface AdditionalSortOptions { + sortBy: SortByOption +} +export declare let objectTypeParentTypes: readonly [ + TSESTree.AST_NODE_TYPES.TSTypeAliasDeclaration, + TSESTree.AST_NODE_TYPES.TSInterfaceDeclaration, + TSESTree.AST_NODE_TYPES.TSPropertySignature, + TSESTree.AST_NODE_TYPES.VariableDeclarator, + TSESTree.AST_NODE_TYPES.PropertyDefinition, +] +export type ObjectTypeParentType = (typeof objectTypeParentTypes)[number] +export type ObjectTypeParent = NodeOfType +/** + * Union type of all available selectors for object type members. + * + * Selectors identify the type of object member for grouping and sorting + * purposes. + */ +export type Selector = (typeof allSelectors)[number] +/** + * Union type of all available modifiers for object type members. + * + * Modifiers provide additional context about member characteristics, such as + * whether they are optional, required, or span multiple lines. + */ +export type Modifier = (typeof allModifiers)[number] +/** + * Match options for a custom group. + */ +interface CustomGroupMatchOptions { + /** + * Regular expression pattern to match against the member's type annotation + * value. Only applicable to properties. + */ + elementValuePattern?: RegexOption + /** + * Array of modifiers that members must have to match this group. Only + * modifiers allowed for the specified selector type are valid. + */ + modifiers?: Modifier[] + /** + * The selector type this group matches. Determines what kind of object + * members belong to this group. + */ + selector?: Selector +} +/** + * Array of all available selectors for object type members. + * + * Used for validation and configuration in the ESLint rule. + */ +export declare let allSelectors: readonly [ + 'index-signature', + 'member', + 'method', + 'property', +] +/** + * Array of all available modifiers for object type members. + * + * Used for validation and configuration in the ESLint rule. + */ +export declare let allModifiers: readonly ['optional', 'required', 'multiline'] +declare const SORT_BY_OPTION: readonly ['name', 'value'] +type SortByOption = (typeof SORT_BY_OPTION)[number] +/** + * Additional sort options JSON schema, used by ESLint to validate rule options. + */ +export declare let additionalSortOptionsJsonSchema: Record +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +export declare let additionalCustomGroupMatchOptionsJsonSchema: Record< + string, + JSONSchema4 +> +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/types.js new file mode 100644 index 0000000000000000000000000000000000000000..5aa6fa3498dd58024daea8fd2bc6225dce4c1161 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-object-types/types.js @@ -0,0 +1,50 @@ +import { buildRegexJsonSchema } from '../../utils/json-schemas/common-json-schemas.js' +import { + buildCustomGroupModifiersJsonSchema, + buildCustomGroupSelectorJsonSchema, +} from '../../utils/json-schemas/common-groups-json-schemas.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var objectTypeParentTypes = [ + AST_NODE_TYPES.TSTypeAliasDeclaration, + AST_NODE_TYPES.TSInterfaceDeclaration, + AST_NODE_TYPES.TSPropertySignature, + AST_NODE_TYPES.VariableDeclarator, + AST_NODE_TYPES.PropertyDefinition, +] +/** + * Array of all available selectors for object type members. + * + * Used for validation and configuration in the ESLint rule. + */ +var allSelectors = ['index-signature', 'member', 'method', 'property'] +/** + * Array of all available modifiers for object type members. + * + * Used for validation and configuration in the ESLint rule. + */ +var allModifiers = ['optional', 'required', 'multiline'] +/** + * Additional sort options JSON schema, used by ESLint to validate rule options. + */ +var additionalSortOptionsJsonSchema = { + sortBy: { + enum: [...['name', 'value']], + type: 'string', + }, +} +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +var additionalCustomGroupMatchOptionsJsonSchema = { + modifiers: buildCustomGroupModifiersJsonSchema(allModifiers), + selector: buildCustomGroupSelectorJsonSchema(allSelectors), + elementValuePattern: buildRegexJsonSchema(), +} +export { + additionalCustomGroupMatchOptionsJsonSchema, + additionalSortOptionsJsonSchema, + allModifiers, + allSelectors, + objectTypeParentTypes, +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c951b1083d3e0789e201abd480a6eff0b14b663f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects.d.ts @@ -0,0 +1,12 @@ +import { MessageId, Options } from './sort-objects/types.js' +declare const _default: import('@typescript-eslint/utils/ts-eslint').RuleModule< + MessageId, + Options, + { + recommended?: boolean + }, + import('@typescript-eslint/utils/ts-eslint').RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects.js new file mode 100644 index 0000000000000000000000000000000000000000..9c3f70e5351b688ae398642a7c09e55df761a0b9 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects.js @@ -0,0 +1,112 @@ +import { + buildCommonJsonSchemas, + buildUseConfigIfJsonSchema, + matchesAstSelectorJsonSchema, + useExperimentalDependencyDetectionJsonSchema, +} from '../utils/json-schemas/common-json-schemas.js' +import { buildCommonGroupsJsonSchemas } from '../utils/json-schemas/common-groups-json-schemas.js' +import { + DEPENDENCY_ORDER_ERROR, + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { + partitionByCommentJsonSchema, + partitionByNewlineJsonSchema, +} from '../utils/json-schemas/common-partition-json-schemas.js' +import { buildAstListeners } from '../utils/build-ast-listeners.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { scopedRegexJsonSchema } from '../utils/json-schemas/scoped-regex-json-schema.js' +import { + DEPENDENCY_ORDER_ERROR_ID, + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + additionalCustomGroupMatchOptionsJsonSchema, + additionalSortOptionsJsonSchema, +} from './sort-objects/types.js' +import { defaultOptions, sortObject } from './sort-objects/sort-object.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var sort_objects_default = createEslintRule({ + meta: { + schema: { + items: { + properties: { + ...buildCommonJsonSchemas({ + additionalSortProperties: additionalSortOptionsJsonSchema, + }), + ...buildCommonGroupsJsonSchemas({ + additionalCustomGroupMatchProperties: + additionalCustomGroupMatchOptionsJsonSchema, + additionalSortProperties: additionalSortOptionsJsonSchema, + }), + useConfigurationIf: buildUseConfigIfJsonSchema({ + additionalProperties: { + objectType: { + description: + 'Specifies whether to only match destructured objects or regular objects.', + enum: ['destructured', 'non-destructured'], + type: 'string', + }, + hasNumericKeysOnly: { + description: + 'Specifies whether to only match objects that have exclusively numeric keys.', + type: 'boolean', + }, + declarationCommentMatchesPattern: scopedRegexJsonSchema, + callingFunctionNamePattern: scopedRegexJsonSchema, + matchesAstSelector: matchesAstSelectorJsonSchema, + declarationMatchesPattern: scopedRegexJsonSchema, + }, + }), + partitionByComputedKey: { + description: + 'Controls whether to partition objects by computed keys.', + type: 'boolean', + }, + styledComponents: { + description: 'Controls whether to sort styled components.', + type: 'boolean', + }, + useExperimentalDependencyDetection: + useExperimentalDependencyDetectionJsonSchema, + partitionByComment: partitionByCommentJsonSchema, + partitionByNewLine: partitionByNewlineJsonSchema, + }, + additionalProperties: false, + type: 'object', + }, + uniqueItems: true, + type: 'array', + }, + messages: { + [DEPENDENCY_ORDER_ERROR_ID]: DEPENDENCY_ORDER_ERROR, + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-objects', + description: 'Enforce sorted objects.', + recommended: true, + }, + type: 'suggestion', + fixable: 'code', + }, + create: context => + buildAstListeners({ + nodeTypes: [ + AST_NODE_TYPES.ObjectPattern, + AST_NODE_TYPES.ObjectExpression, + ], + sorter: sortObject, + context, + }), + defaultOptions: [defaultOptions], + name: 'sort-objects', +}) +export { sort_objects_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/comparator-by-options-computer.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/comparator-by-options-computer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9a9649be140aedf67d4e0bcd8c9e76a97b103f44 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/comparator-by-options-computer.d.ts @@ -0,0 +1,6 @@ +import { ComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +import { SortObjectsSortingNode, Options } from './types.js' +export declare let comparatorByOptionsComputer: ComparatorByOptionsComputer< + Required, + SortObjectsSortingNode +> diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/comparator-by-options-computer.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/comparator-by-options-computer.js new file mode 100644 index 0000000000000000000000000000000000000000..ed729dac04ed851780dd90ea00f5282403450181 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/comparator-by-options-computer.js @@ -0,0 +1,39 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { buildLineLengthComparator } from '../../utils/compare/build-line-length-comparator.js' +import { compareAlphabetically } from '../../utils/compare/compare-alphabetically.js' +import { compareByCustomSort } from '../../utils/compare/compare-by-custom-sort.js' +import { unsortedComparator } from '../../utils/compare/unsorted-comparator.js' +import { compareNaturally } from '../../utils/compare/compare-naturally.js' +import { defaultComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +var comparatorByOptionsComputer = options => { + switch (options.sortBy) { + case 'value': + return byValueComparatorComputer(options) + case 'name': + return defaultComparatorByOptionsComputer(options) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(options.sortBy) + } +} +var byValueComparatorComputer = options => { + switch (options.type) { + /* v8 ignore next 2 -- @preserve Untested for now as not a relevant sort for this rule. */ + case 'subgroup-order': + return defaultComparatorByOptionsComputer(options) + case 'alphabetical': + return (a, b) => compareAlphabetically(a.value, b.value, options) + case 'line-length': + return buildLineLengthComparator(options) + case 'unsorted': + return unsortedComparator + case 'natural': + return (a, b) => compareNaturally(a.value, b.value, options) + case 'custom': + return (a, b) => compareByCustomSort(a.value, b.value, options) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(options.type) + } +} +export { comparatorByOptionsComputer } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-dependencies.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-dependencies.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..da6079b478c2e315b39c04ded81c7bbbae287308 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-dependencies.d.ts @@ -0,0 +1,2 @@ +import { SortObjectsNode } from './types.js' +export declare function computeDependencies(node: SortObjectsNode): string[] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-dependencies.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-dependencies.js new file mode 100644 index 0000000000000000000000000000000000000000..20e0962c466c61c3ab9dc653b868739129f130f7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-dependencies.js @@ -0,0 +1,77 @@ +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +function computeDependencies(node) { + if (node.value.type !== AST_NODE_TYPES.AssignmentPattern) { + return [] + } + let dependencies = [] + traverseNode(node.value.right) + return dependencies + function checkNode(nodeValue) { + /** + * No need to check the body of functions and arrow functions. + */ + if ( + nodeValue.type === AST_NODE_TYPES.ArrowFunctionExpression || + nodeValue.type === AST_NODE_TYPES.FunctionExpression + ) { + return + } + if (nodeValue.type === AST_NODE_TYPES.Identifier) { + dependencies.push(nodeValue.name) + } + if (nodeValue.type === AST_NODE_TYPES.Property) { + traverseNode(nodeValue.key) + traverseNode(nodeValue.value) + } + if (nodeValue.type === AST_NODE_TYPES.ConditionalExpression) { + traverseNode(nodeValue.test) + traverseNode(nodeValue.consequent) + traverseNode(nodeValue.alternate) + } + if ( + 'expression' in nodeValue && + typeof nodeValue.expression !== 'boolean' + ) { + traverseNode(nodeValue.expression) + } + if ('object' in nodeValue) { + traverseNode(nodeValue.object) + } + if ('callee' in nodeValue) { + traverseNode(nodeValue.callee) + } + if ('left' in nodeValue) { + traverseNode(nodeValue.left) + } + if ('right' in nodeValue) { + traverseNode(nodeValue.right) + } + if ('elements' in nodeValue) { + traverseNode( + nodeValue.elements.filter(currentNode => currentNode !== null), + ) + } + if ('argument' in nodeValue && nodeValue.argument) { + traverseNode(nodeValue.argument) + } + if ('arguments' in nodeValue) { + traverseNode(nodeValue.arguments) + } + if ('properties' in nodeValue) { + traverseNode(nodeValue.properties) + } + if ('expressions' in nodeValue) { + traverseNode(nodeValue.expressions) + } + } + function traverseNode(nodeValue) { + if (Array.isArray(nodeValue)) { + for (let nodeItem of nodeValue) { + traverseNode(nodeItem) + } + } else { + checkNode(nodeValue) + } + } +} +export { computeDependencies } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-dependency-names.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-dependency-names.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a47f4431955d8952022055d115838c650e88682 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-dependency-names.d.ts @@ -0,0 +1,2 @@ +import { TSESTree } from '@typescript-eslint/types' +export declare function computeDependencyNames(pattern: TSESTree.Node): string[] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-dependency-names.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-dependency-names.js new file mode 100644 index 0000000000000000000000000000000000000000..4bd80e83187a3077bcffa6ad12f08fd70e66fe80 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-dependency-names.js @@ -0,0 +1,44 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +function computeDependencyNames(pattern) { + let currentPattern = pattern + while (currentPattern.type === AST_NODE_TYPES.AssignmentPattern) { + currentPattern = currentPattern.left + } + switch (currentPattern.type) { + case AST_NODE_TYPES.ObjectPattern: + return currentPattern.properties.flatMap( + extractNamesFromObjectPatternProperty, + ) + case AST_NODE_TYPES.ArrayPattern: + return currentPattern.elements.flatMap( + extractNamesFromArrayPatternElement, + ) + case AST_NODE_TYPES.Identifier: + return [currentPattern.name] + /* v8 ignore next 2 */ + default: + return [] + } + function extractNamesFromArrayPatternElement(element) { + if (!element) { + return [] + } + if (element.type === AST_NODE_TYPES.RestElement) { + return computeDependencyNames(element.argument) + } + return computeDependencyNames(element) + } + function extractNamesFromObjectPatternProperty(property) { + switch (property.type) { + case AST_NODE_TYPES.RestElement: + return computeDependencyNames(property.argument) + case AST_NODE_TYPES.Property: + return computeDependencyNames(property.value) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(property) + } + } +} +export { computeDependencyNames } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-matched-context-options.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-matched-context-options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0bc390c5468d04231b8d1341af6031e6216a536c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-matched-context-options.d.ts @@ -0,0 +1,28 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +import { MessageId, Options } from './types.js' +/** + * Computes the matched context options for a given object node. + * + * @param params - Parameters. + * @param params.isDestructuredObject - Whether the object is destructured. + * @param params.matchedAstSelectors - The matched AST selectors for an object + * node. + * @param params.sourceCode - The source code object. + * @param params.nodeObject - The object node to evaluate. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +export declare function computeMatchedContextOptions({ + isDestructuredObject, + matchedAstSelectors, + sourceCode, + nodeObject, + context, +}: { + nodeObject: TSESTree.ObjectExpression | TSESTree.ObjectPattern + context: TSESLint.RuleContext + matchedAstSelectors: ReadonlySet + sourceCode: TSESLint.SourceCode + isDestructuredObject: boolean +}): Options[number] | undefined diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-matched-context-options.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-matched-context-options.js new file mode 100644 index 0000000000000000000000000000000000000000..2b2807a2e5a2440c6c415bd38d7629b530d6039e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-matched-context-options.js @@ -0,0 +1,152 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { computeParentNodesWithTypes } from '../../utils/compute-parent-nodes-with-types.js' +import { passesAllNamesMatchPatternFilter } from '../../utils/context-matching/passes-all-names-match-pattern-filter.js' +import { passesAstSelectorFilter } from '../../utils/context-matching/passes-ast-selector-filter.js' +import { objectParentTypes } from './types.js' +import { computePropertyOrVariableDeclaratorName } from './compute-property-or-variable-declarator-name.js' +import { passesCallingFunctionNamePatternFilter } from './passes-calling-function-name-pattern-filter.js' +import { passesDeclarationMatchesPatternFilter } from './passes-declaration-matches-pattern-filter.js' +import { passesDeclarationCommentMatchesFilter } from './passes-declaration-comment-matches-filter.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the matched context options for a given object node. + * + * @param params - Parameters. + * @param params.isDestructuredObject - Whether the object is destructured. + * @param params.matchedAstSelectors - The matched AST selectors for an object + * node. + * @param params.sourceCode - The source code object. + * @param params.nodeObject - The object node to evaluate. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +function computeMatchedContextOptions({ + isDestructuredObject, + matchedAstSelectors, + sourceCode, + nodeObject, + context, +}) { + let nodeNames = nodeObject.properties + .filter( + property => + property.type !== AST_NODE_TYPES.SpreadElement && + property.type !== AST_NODE_TYPES.RestElement, + ) + .map(property => + computePropertyOrVariableDeclaratorName({ + node: property, + sourceCode, + }), + ) + let parentNodes = computeParentNodesWithTypes({ + allowedTypes: [...objectParentTypes], + consecutiveOnly: false, + node: nodeObject, + maxParent: null, + }) + return context.options.find(options => + isContextOptionMatching({ + isDestructuredObject, + matchedAstSelectors, + parentNodes, + sourceCode, + nodeObject, + nodeNames, + options, + }), + ) +} +function isContextOptionMatching({ + isDestructuredObject, + matchedAstSelectors, + parentNodes, + sourceCode, + nodeObject, + nodeNames, + options, +}) { + if (!options.useConfigurationIf) { + return true + } + return ( + passesAllNamesMatchPatternFilter({ + allNamesMatchPattern: options.useConfigurationIf.allNamesMatchPattern, + nodeNames, + }) && + passesObjectTypeFilter({ + objectType: options.useConfigurationIf.objectType, + isDestructuredObject, + }) && + passesCallingFunctionNamePatternFilter({ + callingFunctionNamePattern: + options.useConfigurationIf.callingFunctionNamePattern, + parentNodes, + sourceCode, + }) && + passesDeclarationMatchesPatternFilter({ + declarationMatchesPattern: + options.useConfigurationIf.declarationMatchesPattern, + parentNodes, + sourceCode, + }) && + passesHasNumericKeysOnlyFilter({ + hasNumericKeysOnlyFilter: options.useConfigurationIf.hasNumericKeysOnly, + object: nodeObject, + }) && + passesDeclarationCommentMatchesFilter({ + declarationCommentMatchesPattern: + options.useConfigurationIf.declarationCommentMatchesPattern, + parentNodes, + sourceCode, + }) && + passesAstSelectorFilter({ + matchesAstSelector: options.useConfigurationIf.matchesAstSelector, + matchedAstSelectors, + }) + ) +} +function passesHasNumericKeysOnlyFilter({ hasNumericKeysOnlyFilter, object }) { + let hasOnlyNumericKeys = hasNumericKeysOnly() + switch (hasNumericKeysOnlyFilter) { + case void 0: + return true + case false: + return !hasOnlyNumericKeys + case true: + return hasOnlyNumericKeys + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(hasNumericKeysOnlyFilter) + } + function hasNumericKeysOnly() { + switch (object.type) { + case AST_NODE_TYPES.ObjectExpression: + return object.properties.every( + property => + property.type === AST_NODE_TYPES.Property && + property.key.type === AST_NODE_TYPES.Literal && + typeof property.key.value === 'number', + ) + case AST_NODE_TYPES.ObjectPattern: + return false + /* v8 ignore next 2 */ + default: + throw new UnreachableCaseError(object) + } + } +} +function passesObjectTypeFilter({ isDestructuredObject, objectType }) { + switch (objectType) { + case 'non-destructured': + return !isDestructuredObject + case 'destructured': + return isDestructuredObject + case void 0: + return true + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(objectType) + } +} +export { computeMatchedContextOptions } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-node-value.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-node-value.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d6fc64d7e6fe95d1d4004483a9c2ebe717b626e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-node-value.d.ts @@ -0,0 +1,11 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +export declare function computeNodeValue({ + isDestructuredObject, + sourceCode, + property, +}: { + sourceCode: TSESLint.SourceCode + isDestructuredObject: boolean + property: TSESTree.Property +}): string | null diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-node-value.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-node-value.js new file mode 100644 index 0000000000000000000000000000000000000000..12b33e9fb8a3c24ff5e16003adc8c5e7f243f02e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-node-value.js @@ -0,0 +1,19 @@ +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +function computeNodeValue({ isDestructuredObject, sourceCode, property }) { + switch (property.value.type) { + case AST_NODE_TYPES.ArrowFunctionExpression: + case AST_NODE_TYPES.FunctionExpression: + return null + case AST_NODE_TYPES.AssignmentPattern: + switch (property.value.right.type) { + case AST_NODE_TYPES.ArrowFunctionExpression: + case AST_NODE_TYPES.FunctionExpression: + return null + default: + return sourceCode.getText(property.value.right) + } + default: + return isDestructuredObject ? null : sourceCode.getText(property.value) + } +} +export { computeNodeValue } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-property-or-variable-declarator-name.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-property-or-variable-declarator-name.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b66a335fe7f2a9f1bbbd4c22a4a6ba4cb031ab15 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-property-or-variable-declarator-name.d.ts @@ -0,0 +1,17 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +/** + * Compute the name for a property-like node. + * + * @param params - Parameters. + * @param params.node - Starting node to search from. + * @param params.sourceCode - The source code object. + * @returns The property or variable declaration name. + */ +export declare function computePropertyOrVariableDeclaratorName({ + sourceCode, + node, +}: { + node: TSESTree.VariableDeclarator | TSESTree.Property + sourceCode: TSESLint.SourceCode +}): string diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-property-or-variable-declarator-name.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-property-or-variable-declarator-name.js new file mode 100644 index 0000000000000000000000000000000000000000..36705b8435e85feb36610a8a07359f76df9a6451 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/compute-property-or-variable-declarator-name.js @@ -0,0 +1,38 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Compute the name for a property-like node. + * + * @param params - Parameters. + * @param params.node - Starting node to search from. + * @param params.sourceCode - The source code object. + * @returns The property or variable declaration name. + */ +function computePropertyOrVariableDeclaratorName({ sourceCode, node }) { + switch (node.type) { + case AST_NODE_TYPES.VariableDeclarator: + return computeIdentifierName({ + node: node.id, + sourceCode, + }) + case AST_NODE_TYPES.Property: + return computeIdentifierName({ + node: node.key, + sourceCode, + }) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(node) + } +} +function computeIdentifierName({ sourceCode, node }) { + switch (node.type) { + case AST_NODE_TYPES.Identifier: + return node.name + case AST_NODE_TYPES.Literal: + return String(node.value) + default: + return sourceCode.getText(node) + } +} +export { computePropertyOrVariableDeclaratorName } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/is-style-component.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/is-style-component.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..de9f1fbaf4fa37dabed86b37dbc1ad610d38355c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/is-style-component.d.ts @@ -0,0 +1,10 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Checks if a node represents a style component. + * + * @param node - The AST node to check. + * @returns True if the node is a style component, false otherwise. + */ +export declare function isStyleComponent( + node: TSESTree.ObjectExpression | TSESTree.ObjectPattern, +): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/is-style-component.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/is-style-component.js new file mode 100644 index 0000000000000000000000000000000000000000..1147a008e8f6b2bab463c852785c8468cffb850b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/is-style-component.js @@ -0,0 +1,61 @@ +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Checks if a node represents a style component. + * + * @param node - The AST node to check. + * @returns True if the node is a style component, false otherwise. + */ +function isStyleComponent(node) { + if (node.type === AST_NODE_TYPES.ObjectPattern) { + return false + } + let objectRoot = getRootObject(node) + if (isStyleNode(objectRoot.parent)) { + return true + } + return ( + objectRoot.parent.type === AST_NODE_TYPES.ArrowFunctionExpression && + isStyleNode(objectRoot.parent.parent) + ) +} +function isStyleNode(node) { + switch (node.type) { + case AST_NODE_TYPES.JSXExpressionContainer: + return ( + node.parent.type === AST_NODE_TYPES.JSXAttribute && + node.parent.name.name === 'style' + ) + case AST_NODE_TYPES.CallExpression: + return ( + isCssCallExpression(node.callee) || + (node.callee.type === AST_NODE_TYPES.MemberExpression && + isStyledCallExpression(node.callee.object)) || + (node.callee.type === AST_NODE_TYPES.CallExpression && + isStyledCallExpression(node.callee.callee)) + ) + default: + return false + } +} +function getRootObject(node) { + let objectRoot = node + while ( + objectRoot.parent.type === AST_NODE_TYPES.Property && + objectRoot.parent.parent.type === AST_NODE_TYPES.ObjectExpression + ) { + objectRoot = objectRoot.parent.parent + } + return objectRoot +} +function isStyledCallExpression(identifier) { + return ( + identifier.type === AST_NODE_TYPES.Identifier && + identifier.name === 'styled' + ) +} +function isCssCallExpression(identifier) { + return ( + identifier.type === AST_NODE_TYPES.Identifier && identifier.name === 'css' + ) +} +export { isStyleComponent } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/passes-calling-function-name-pattern-filter.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/passes-calling-function-name-pattern-filter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9f4ccea95f0aef352f145ee4fe70f7ade0565515 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/passes-calling-function-name-pattern-filter.d.ts @@ -0,0 +1,21 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { ScopedRegexOption } from '../../types/scoped-regex-option.js' +import { ObjectParent } from './types.js' +/** + * Checks if the object passes the calling function name pattern filter. + * + * @param params - Parameters. + * @param params.callingFunctionNamePattern - The pattern to evaluate. + * @param params.parentNodes - The parent nodes of the object. + * @param params.sourceCode - The source code object. + * @returns True if the object passes the filter, false otherwise. + */ +export declare function passesCallingFunctionNamePatternFilter({ + callingFunctionNamePattern, + parentNodes, + sourceCode, +}: { + callingFunctionNamePattern: ScopedRegexOption | undefined + sourceCode: TSESLint.SourceCode + parentNodes: ObjectParent[] +}): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/passes-calling-function-name-pattern-filter.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/passes-calling-function-name-pattern-filter.js new file mode 100644 index 0000000000000000000000000000000000000000..c3fad546bbce98eebbb7c7421dbbf83e59c96c74 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/passes-calling-function-name-pattern-filter.js @@ -0,0 +1,27 @@ +import { matchesScopedExpressions } from '../../utils/scoped-regex/matches-scoped-expressions.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Checks if the object passes the calling function name pattern filter. + * + * @param params - Parameters. + * @param params.callingFunctionNamePattern - The pattern to evaluate. + * @param params.parentNodes - The parent nodes of the object. + * @param params.sourceCode - The source code object. + * @returns True if the object passes the filter, false otherwise. + */ +function passesCallingFunctionNamePatternFilter({ + callingFunctionNamePattern, + parentNodes, + sourceCode, +}) { + return matchesScopedExpressions({ + allowedNodeTypes: /* @__PURE__ */ new Set([AST_NODE_TYPES.CallExpression]), + nodeValuesComputer: buildNodeValuesComputer(sourceCode), + scopedRegexOption: callingFunctionNamePattern, + parentNodes, + }) +} +function buildNodeValuesComputer(sourceCode) { + return node => [sourceCode.getText(node.callee)] +} +export { passesCallingFunctionNamePatternFilter } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/passes-declaration-comment-matches-filter.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/passes-declaration-comment-matches-filter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d29bc4643b66ba9c46c70489c9e00dd4d20b4bd9 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/passes-declaration-comment-matches-filter.d.ts @@ -0,0 +1,21 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { ScopedRegexOption } from '../../types/scoped-regex-option.js' +import { ObjectParent } from './types.js' +/** + * Checks if the object passes the declaration comment matches filter. + * + * @param params - Parameters. + * @param params.declarationCommentMatchesPattern - The pattern to evaluate. + * @param params.parentNodes - The parent nodes of the object. + * @param params.sourceCode - The source code object. + * @returns True if the object passes the filter, false otherwise. + */ +export declare function passesDeclarationCommentMatchesFilter({ + declarationCommentMatchesPattern, + parentNodes, + sourceCode, +}: { + declarationCommentMatchesPattern: ScopedRegexOption | undefined + sourceCode: TSESLint.SourceCode + parentNodes: ObjectParent[] +}): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/passes-declaration-comment-matches-filter.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/passes-declaration-comment-matches-filter.js new file mode 100644 index 0000000000000000000000000000000000000000..9e7017b8ee2ff3e2555fd5b8288a7de66b23ea5e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/passes-declaration-comment-matches-filter.js @@ -0,0 +1,55 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { matchesScopedExpressions } from '../../utils/scoped-regex/matches-scoped-expressions.js' +import { objectParentTypes } from './types.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Checks if the object passes the declaration comment matches filter. + * + * @param params - Parameters. + * @param params.declarationCommentMatchesPattern - The pattern to evaluate. + * @param params.parentNodes - The parent nodes of the object. + * @param params.sourceCode - The source code object. + * @returns True if the object passes the filter, false otherwise. + */ +function passesDeclarationCommentMatchesFilter({ + declarationCommentMatchesPattern, + parentNodes, + sourceCode, +}) { + return matchesScopedExpressions({ + nodeValuesComputer: buildNodeValuesComputer(sourceCode), + scopedRegexOption: declarationCommentMatchesPattern, + allowedNodeTypes: new Set(objectParentTypes), + parentNodes, + }) +} +function computeRelevantNodeForComment(objectParent) { + let objectParentType = objectParent.type + switch (objectParentType) { + case AST_NODE_TYPES.VariableDeclarator: { + let variableDeclaration = objectParent.parent + if ( + variableDeclaration.parent?.type === + AST_NODE_TYPES.ExportNamedDeclaration + ) { + return variableDeclaration.parent + } + return variableDeclaration + } + case AST_NODE_TYPES.CallExpression: + case AST_NODE_TYPES.Property: + return objectParent + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(objectParentType) + } +} +function buildNodeValuesComputer(sourceCode) { + return node => { + let nodeForComment = computeRelevantNodeForComment(node) + return sourceCode + .getCommentsBefore(nodeForComment) + .map(comment => comment.value.trim()) + } +} +export { passesDeclarationCommentMatchesFilter } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/passes-declaration-matches-pattern-filter.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/passes-declaration-matches-pattern-filter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..86233a3c8d0ce0fe93e5d7a6e38037b6d3aaf44a --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/passes-declaration-matches-pattern-filter.d.ts @@ -0,0 +1,22 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { ScopedRegexOption } from '../../types/scoped-regex-option.js' +import { ObjectParent } from './types.js' +/** + * Checks whether the node parent names match the given pattern. + * + * @param params - The parameters object. + * @param params.declarationMatchesPattern - The regex pattern to match against. + * @param params.parentNodes - The parent nodes to check. + * @param params.sourceCode - The source code object. + * @returns True if the parent node parent names passes the pattern filter, + * false otherwise. + */ +export declare function passesDeclarationMatchesPatternFilter({ + declarationMatchesPattern, + parentNodes, + sourceCode, +}: { + declarationMatchesPattern: ScopedRegexOption | undefined + sourceCode: TSESLint.SourceCode + parentNodes: ObjectParent[] +}): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/passes-declaration-matches-pattern-filter.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/passes-declaration-matches-pattern-filter.js new file mode 100644 index 0000000000000000000000000000000000000000..87e39954baadda1dc326ac389f2da0900417fd15 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/passes-declaration-matches-pattern-filter.js @@ -0,0 +1,35 @@ +import { matchesScopedExpressions } from '../../utils/scoped-regex/matches-scoped-expressions.js' +import { computePropertyOrVariableDeclaratorName } from './compute-property-or-variable-declarator-name.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var allowedTypes = [AST_NODE_TYPES.VariableDeclarator, AST_NODE_TYPES.Property] +/** + * Checks whether the node parent names match the given pattern. + * + * @param params - The parameters object. + * @param params.declarationMatchesPattern - The regex pattern to match against. + * @param params.parentNodes - The parent nodes to check. + * @param params.sourceCode - The source code object. + * @returns True if the parent node parent names passes the pattern filter, + * false otherwise. + */ +function passesDeclarationMatchesPatternFilter({ + declarationMatchesPattern, + parentNodes, + sourceCode, +}) { + return matchesScopedExpressions({ + nodeValuesComputer: buildNodeValuesComputer(sourceCode), + scopedRegexOption: declarationMatchesPattern, + allowedNodeTypes: new Set(allowedTypes), + parentNodes, + }) +} +function buildNodeValuesComputer(sourceCode) { + return node => [ + computePropertyOrVariableDeclaratorName({ + sourceCode, + node, + }), + ] +} +export { passesDeclarationMatchesPatternFilter } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/sort-object.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/sort-object.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..75270e15335d52af1afe888895f5fa8c02fe46a9 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/sort-object.d.ts @@ -0,0 +1,13 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +import { MessageId, Options } from './types.js' +export declare let defaultOptions: Required +export declare function sortObject({ + matchedAstSelectors, + context, + node, +}: { + context: Readonly> + node: TSESTree.ObjectExpression | TSESTree.ObjectPattern + matchedAstSelectors: ReadonlySet +}): void diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/sort-object.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/sort-object.js new file mode 100644 index 0000000000000000000000000000000000000000..950c4e1944851b9c51aba2775d1e1fa2fea8bc16 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/sort-object.js @@ -0,0 +1,222 @@ +import { computeDependenciesOutsideFunctionsBySortingNode } from '../../utils/compute-dependencies-outside-functions-by-sorting-node.js' +import { populateSortingNodeGroupsWithDependencies } from '../../utils/populate-sorting-node-groups-with-dependencies.js' +import { validateNewlinesAndPartitionConfig } from '../../utils/validate-newlines-and-partition-config.js' +import { buildOptionsByGroupIndexComputer } from '../../utils/build-options-by-group-index-computer.js' +import { validateCustomSortConfig } from '../../utils/validate-custom-sort-config.js' +import { generatePredefinedGroups } from '../../utils/generate-predefined-groups.js' +import { sortNodesByDependencies } from '../../utils/sort-nodes-by-dependencies.js' +import { getEslintDisabledLines } from '../../utils/get-eslint-disabled-lines.js' +import { doesCustomGroupMatch } from '../../utils/does-custom-group-match.js' +import { isNodeEslintDisabled } from '../../utils/is-node-eslint-disabled.js' +import { validateGroupsConfig } from '../../utils/validate-groups-config.js' +import { sortNodesByGroups } from '../../utils/sort-nodes-by-groups.js' +import { reportAllErrors } from '../../utils/report-all-errors.js' +import { shouldPartition } from '../../utils/should-partition.js' +import { computeGroup } from '../../utils/compute-group.js' +import { rangeToDiff } from '../../utils/range-to-diff.js' +import { getSettings } from '../../utils/get-settings.js' +import { isSortable } from '../../utils/is-sortable.js' +import { complete } from '../../utils/complete.js' +import { isNodeOnSingleLine } from '../../utils/is-node-on-single-line.js' +import { + DEPENDENCY_ORDER_ERROR_ID, + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + allModifiers, + allSelectors, +} from './types.js' +import { computePropertyOrVariableDeclaratorName } from './compute-property-or-variable-declarator-name.js' +import { computeMatchedContextOptions } from './compute-matched-context-options.js' +import { comparatorByOptionsComputer } from './comparator-by-options-computer.js' +import { computeDependencyNames } from './compute-dependency-names.js' +import { computeDependencies } from './compute-dependencies.js' +import { isStyleComponent } from './is-style-component.js' +import { computeNodeValue } from './compute-node-value.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Cache computed groups by modifiers and selectors for performance. + */ +var cachedGroupsByModifiersAndSelectors = /* @__PURE__ */ new Map() +var defaultOptions = { + useExperimentalDependencyDetection: true, + fallbackSort: { type: 'unsorted' }, + newlinesInside: 'newlinesBetween', + partitionByComputedKey: false, + partitionByNewLine: false, + partitionByComment: false, + newlinesBetween: 'ignore', + specialCharacters: 'keep', + styledComponents: true, + useConfigurationIf: {}, + type: 'alphabetical', + ignoreCase: true, + customGroups: [], + locales: 'en-US', + sortBy: 'name', + alphabet: '', + order: 'asc', + groups: [], +} +function sortObject({ matchedAstSelectors, context, node }) { + if (!isSortable(node.properties)) { + return + } + let { sourceCode, id } = context + let settings = getSettings(context.settings) + let isDestructuredObject = node.type === AST_NODE_TYPES.ObjectPattern + let matchedContextOptions = computeMatchedContextOptions({ + isDestructuredObject, + matchedAstSelectors, + nodeObject: node, + sourceCode, + context, + }) + let options = complete(matchedContextOptions, settings, defaultOptions) + validateCustomSortConfig(options) + validateGroupsConfig({ + selectors: allSelectors, + modifiers: allModifiers, + options, + }) + validateNewlinesAndPartitionConfig(options) + if (!options.styledComponents && isStyleComponent(node)) { + return + } + let eslintDisabledLines = getEslintDisabledLines({ + ruleName: id, + sourceCode, + }) + let optionsByGroupIndexComputer = buildOptionsByGroupIndexComputer(options) + let sortingNodeGroups = [[]] + for (let property of node.properties) { + if ( + property.type === AST_NODE_TYPES.SpreadElement || + property.type === AST_NODE_TYPES.RestElement + ) { + sortingNodeGroups.push([]) + continue + } + if ( + !isDestructuredObject && + options.partitionByComputedKey && + property.computed + ) { + sortingNodeGroups.push([]) + continue + } + let lastSortingNode = sortingNodeGroups.at(-1)?.at(-1) + let selectors = [] + let modifiers = [] + if ( + property.value.type === AST_NODE_TYPES.ArrowFunctionExpression || + property.value.type === AST_NODE_TYPES.FunctionExpression + ) { + selectors.push('method') + } else { + selectors.push('property') + } + selectors.push('member') + if (!isNodeOnSingleLine(property)) { + modifiers.push('multiline') + } + let name = computePropertyOrVariableDeclaratorName({ + node: property, + sourceCode, + }) + let dependencyNames = [name] + if (isDestructuredObject) { + dependencyNames = [...new Set(computeDependencyNames(property.value))] + } + let value = computeNodeValue({ + isDestructuredObject, + sourceCode, + property, + }) + let predefinedGroups = generatePredefinedGroups({ + cache: cachedGroupsByModifiersAndSelectors, + selectors, + modifiers, + }) + let group = computeGroup({ + customGroupMatcher: customGroup => + doesCustomGroupMatch({ + elementValue: value, + elementName: name, + customGroup, + selectors, + modifiers, + }), + predefinedGroups, + options, + }) + let sortingNode = { + dependencies: + options.useExperimentalDependencyDetection ? + [] + : computeDependencies(property), + isEslintDisabled: isNodeEslintDisabled(property, eslintDisabledLines), + size: rangeToDiff(property, sourceCode), + value: value ?? '', + dependencyNames, + node: property, + group, + name, + } + if ( + shouldPartition({ + lastSortingNode, + sortingNode, + sourceCode, + options, + }) + ) { + sortingNodeGroups.push([]) + } + sortingNodeGroups.at(-1).push({ + ...sortingNode, + partitionId: sortingNodeGroups.length, + }) + } + if (options.useExperimentalDependencyDetection) { + let dependenciesBySortingNode = + computeDependenciesOutsideFunctionsBySortingNode({ + sortingNodes: sortingNodeGroups.flat(), + sourceCode, + }) + sortingNodeGroups = populateSortingNodeGroupsWithDependencies({ + dependenciesBySortingNode, + sortingNodeGroups, + }) + } + let sortingNodes = sortingNodeGroups.flat() + reportAllErrors({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + unexpectedDependencyOrder: DEPENDENCY_ORDER_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + sortNodesExcludingEslintDisabled, + nodes: sortingNodes, + options, + context, + }) + function sortNodesExcludingEslintDisabled(ignoreEslintDisabledNodes) { + let nodesSortedByGroups = sortingNodeGroups.flatMap(nodes => + sortNodesByGroups({ + comparatorByOptionsComputer, + optionsByGroupIndexComputer, + ignoreEslintDisabledNodes, + groups: options.groups, + nodes, + }), + ) + return sortNodesByDependencies(nodesSortedByGroups, { + ignoreEslintDisabledNodes, + }) + } +} +export { defaultOptions, sortObject } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..daceac099d604b2d5b34c645490073fa83e11f43 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/types.d.ts @@ -0,0 +1,170 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +import { TSESTree } from '@typescript-eslint/types' +import { SortingNodeWithDependencies } from '../../utils/sort-nodes-by-dependencies.js' +import { RegexOption, TypeOption } from '../../types/common-options.js' +import { ScopedRegexOption } from '../../types/scoped-regex-option.js' +import { AllCommonOptions } from '../../types/all-common-options.js' +import { NodeOfType } from '../../types/node-of-type.js' +export type MessageId = + | typeof DEPENDENCY_ORDER_ERROR_ID + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +export declare const ORDER_ERROR_ID = 'unexpectedObjectsOrder' +export declare const GROUP_ORDER_ERROR_ID = 'unexpectedObjectsGroupOrder' +export declare const EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenObjectMembers' +export declare const MISSED_SPACING_ERROR_ID = + 'missedSpacingBetweenObjectMembers' +export declare const DEPENDENCY_ORDER_ERROR_ID = + 'unexpectedObjectsDependencyOrder' +/** + * Configuration options for the sort-objects rule. + * + * Controls how object properties and methods are sorted within object literals + * and object patterns in JavaScript/TypeScript. + */ +export type Options = Partial< + { + /** + * Conditional configuration based on pattern matching. Allows applying the + * rule only when specific conditions are met. + */ + useConfigurationIf: { + /** + * Regular expression pattern to match against the comment associated to + * the name of the object. + */ + declarationCommentMatchesPattern?: ScopedRegexOption + /** + * Specifies whether to only match destructured objects or regular + * objects. + */ + objectType?: 'non-destructured' | 'destructured' + /** + * Regular expression pattern to match against the name of the function + * that contains this object. Useful for applying different sorting + * rules to objects passed to specific functions. + */ + callingFunctionNamePattern?: ScopedRegexOption + /** + * Regular expression pattern to match against the object's declaration + * name. The rule is only applied to declarations with matching names. + */ + declarationMatchesPattern?: ScopedRegexOption + /** + * Regular expression pattern to match against all property names. The + * rule is only applied when all property names match this pattern. + */ + allNamesMatchPattern?: RegexOption + /** + * Specifies whether to only match objects that have exclusively numeric + * keys. + */ + hasNumericKeysOnly?: boolean + /** + * AST selector to match against ObjectExpression or ObjectPattern + * nodes. + */ + matchesAstSelector?: string + } + /** + * Enables experimental dependency detection. + */ + useExperimentalDependencyDetection: boolean + /** + * Whether to partition object members by computed keys. + */ + partitionByComputedKey: boolean + /** + * Whether to sort styled-components CSS properties. When true, sorts CSS + * properties within styled-components template literals. + * + * @default true + */ + styledComponents: boolean + } & AllCommonOptions< + TypeOption, + AdditionalSortOptions, + CustomGroupMatchOptions + > +>[] +export type SortObjectsSortingNode = { + /** + * The string representation of the property's value. Used when sorting by + * value instead of name. + */ + value: string +} & SortingNodeWithDependencies +export type SortObjectsNode = TSESTree.Property +interface AdditionalSortOptions { + sortBy: SortByOption +} +export declare let objectParentTypes: readonly [ + TSESTree.AST_NODE_TYPES.VariableDeclarator, + TSESTree.AST_NODE_TYPES.CallExpression, + TSESTree.AST_NODE_TYPES.Property, +] +export type ObjectParentType = (typeof objectParentTypes)[number] +export type ObjectParent = NodeOfType +/** + * Union type of all available modifiers for object members. + * + * Modifiers provide additional context about member characteristics, such as + * whether they are optional, required, or span multiple lines. + */ +export type Modifier = (typeof allModifiers)[number] +/** + * Union type of all available selectors for object members. + * + * Selectors identify the type of object member for grouping and sorting + * purposes. + */ +export type Selector = (typeof allSelectors)[number] +/** + * Match options for a custom group. + */ +interface CustomGroupMatchOptions { + /** + * Regular expression pattern to match against the member's value. Only + * applicable to properties with literal values. + */ + elementValuePattern?: RegexOption + /** + * Array of modifiers that members must have to match this group. Only + * modifiers allowed for the specified selector type are valid. + */ + modifiers?: Modifier[] + /** + * The selector type this group matches. Determines what kind of object + * members belong to this group. + */ + selector?: Selector +} +/** + * Array of all available selectors for object members. + * + * Used for validation and configuration in the ESLint rule. + */ +export declare let allSelectors: readonly ['member', 'method', 'property'] +/** + * Array of all available modifiers for object members. + * + * Used for validation and configuration in the ESLint rule. + */ +export declare let allModifiers: readonly ['multiline'] +declare const SORT_BY_OPTION: readonly ['name', 'value'] +type SortByOption = (typeof SORT_BY_OPTION)[number] +/** + * Additional sort options JSON schema, Used by ESLint to validate rule options. + */ +export declare let additionalSortOptionsJsonSchema: Record +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +export declare let additionalCustomGroupMatchOptionsJsonSchema: Record< + string, + JSONSchema4 +> +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/types.js new file mode 100644 index 0000000000000000000000000000000000000000..ae92ba15ee6c4216f53a7dc491d3e2f5788e11ca --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-objects/types.js @@ -0,0 +1,58 @@ +import { buildRegexJsonSchema } from '../../utils/json-schemas/common-json-schemas.js' +import { + buildCustomGroupModifiersJsonSchema, + buildCustomGroupSelectorJsonSchema, +} from '../../utils/json-schemas/common-groups-json-schemas.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var ORDER_ERROR_ID = 'unexpectedObjectsOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedObjectsGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenObjectMembers' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenObjectMembers' +var DEPENDENCY_ORDER_ERROR_ID = 'unexpectedObjectsDependencyOrder' +var objectParentTypes = [ + AST_NODE_TYPES.VariableDeclarator, + AST_NODE_TYPES.CallExpression, + AST_NODE_TYPES.Property, +] +/** + * Array of all available selectors for object members. + * + * Used for validation and configuration in the ESLint rule. + */ +var allSelectors = ['member', 'method', 'property'] +/** + * Array of all available modifiers for object members. + * + * Used for validation and configuration in the ESLint rule. + */ +var allModifiers = ['multiline'] +/** + * Additional sort options JSON schema, Used by ESLint to validate rule options. + */ +var additionalSortOptionsJsonSchema = { + sortBy: { + enum: [...['name', 'value']], + type: 'string', + }, +} +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +var additionalCustomGroupMatchOptionsJsonSchema = { + modifiers: buildCustomGroupModifiersJsonSchema(allModifiers), + selector: buildCustomGroupSelectorJsonSchema(allSelectors), + elementValuePattern: buildRegexJsonSchema(), +} +export { + DEPENDENCY_ORDER_ERROR_ID, + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + additionalCustomGroupMatchOptionsJsonSchema, + additionalSortOptionsJsonSchema, + allModifiers, + allSelectors, + objectParentTypes, +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-sets.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-sets.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ac3445f377b5d63e2a5a487af8d2d2f616caa23 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-sets.d.ts @@ -0,0 +1,20 @@ +declare const ORDER_ERROR_ID = 'unexpectedSetsOrder' +declare const GROUP_ORDER_ERROR_ID = 'unexpectedSetsGroupOrder' +declare const EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenSetsMembers' +declare const MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenSetsMembers' +type MessageId = + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +declare const _default: import('@typescript-eslint/utils/ts-eslint').RuleModule< + MessageId, + import('...js').SortArraysOptions, + { + recommended?: boolean + }, + import('@typescript-eslint/utils/ts-eslint').RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-sets.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-sets.js new file mode 100644 index 0000000000000000000000000000000000000000..f82c1da54f60b660b959c8219f543efe88d7109d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-sets.js @@ -0,0 +1,77 @@ +import { + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { buildAstListeners } from '../utils/build-ast-listeners.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { sortArray } from './sort-arrays/sort-array.js' +import { defaultOptions, jsonSchema } from './sort-array-includes.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Cache computed groups by modifiers and selectors for performance. + */ +var cachedGroupsByModifiersAndSelectors = /* @__PURE__ */ new Map() +var ORDER_ERROR_ID = 'unexpectedSetsOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedSetsGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenSetsMembers' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenSetsMembers' +var sort_sets_default = createEslintRule({ + meta: { + messages: { + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-sets', + description: 'Enforce sorted sets.', + recommended: true, + }, + schema: jsonSchema, + type: 'suggestion', + fixable: 'code', + }, + create: context => + buildAstListeners({ + nodeTypes: [AST_NODE_TYPES.NewExpression, AST_NODE_TYPES.ArrayExpression], + sorter: sortPotentiallyValidArray, + context, + }), + defaultOptions: [defaultOptions], + name: 'sort-sets', +}) +function sortPotentiallyValidArray({ matchedAstSelectors, context, node }) { + if (!isValidArray()) { + return + } + sortArray({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + mustHaveMatchedContextOptions: false, + cachedGroupsByModifiersAndSelectors, + matchedAstSelectors, + defaultOptions, + context, + node, + }) + function isValidArray() { + if (node.parent.type !== AST_NODE_TYPES.NewExpression) { + return false + } + if (node.parent.callee.type !== AST_NODE_TYPES.Identifier) { + return false + } + if (node.parent.callee.name !== 'Set') { + return false + } + return node.parent.arguments[0] === node + } +} +export { sort_sets_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-sets/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-sets/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c3335c8c0cd598be851c19c33d5bffb34f1c2c8e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-sets/types.d.ts @@ -0,0 +1,2 @@ +import { Options as SortArraysOptions } from '../sort-arrays/types.js' +export type Options = SortArraysOptions diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-switch-case.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-switch-case.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e11a454e7964a6326fe583cd88821da4129d633d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-switch-case.d.ts @@ -0,0 +1,13 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { Options } from './sort-switch-case/types.js' +declare const _default: TSESLint.RuleModule< + 'unexpectedSwitchCaseOrder', + Options, + { + recommended?: boolean + }, + TSESLint.RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-switch-case.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-switch-case.js new file mode 100644 index 0000000000000000000000000000000000000000..3b2369dd724d584ee8afb995e44c3e7d0eb939f5 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-switch-case.js @@ -0,0 +1,323 @@ +import { buildCommonJsonSchemas } from '../utils/json-schemas/common-json-schemas.js' +import { makeSingleNodeCommentAfterFixes } from '../utils/make-single-node-comment-after-fixes.js' +import { makeFixes } from '../utils/make-fixes.js' +import { + LEFT, + ORDER_ERROR, + RIGHT, + reportErrors, +} from '../utils/report-errors.js' +import { defaultComparatorByOptionsComputer } from '../utils/compare/default-comparator-by-options-computer.js' +import { validateCustomSortConfig } from '../utils/validate-custom-sort-config.js' +import { sortNodes } from '../utils/sort-nodes.js' +import { createNodeIndexMap } from '../utils/create-node-index-map.js' +import { pairwise } from '../utils/pairwise.js' +import { rangeToDiff } from '../utils/range-to-diff.js' +import { getSettings } from '../utils/get-settings.js' +import { isSortable } from '../utils/is-sortable.js' +import { complete } from '../utils/complete.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { isConditionExpression } from './sort-switch-case/is-condition-expression.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var ORDER_ERROR_ID = 'unexpectedSwitchCaseOrder' +var defaultOptions = { + fallbackSort: { type: 'unsorted' }, + specialCharacters: 'keep', + type: 'alphabetical', + ignoreCase: true, + locales: 'en-US', + alphabet: '', + order: 'asc', +} +var sort_switch_case_default = createEslintRule({ + create: context => ({ + SwitchStatement: switchNode => { + if (!isSortable(switchNode.cases)) { + return + } + let settings = getSettings(context.settings) + let options = complete(context.options.at(0), settings, defaultOptions) + let defaultComparator = defaultComparatorByOptionsComputer(options) + validateCustomSortConfig(options) + let { sourceCode } = context + if ( + isConditionExpression(switchNode.discriminant) || + switchNode.cases.some( + caseNode => + caseNode.test !== null && isConditionExpression(caseNode.test), + ) + ) { + return + } + let caseNameSortingNodeGroups = switchNode.cases.reduce( + (accumulator, caseNode, index) => { + if (caseNode.test) { + accumulator.at(-1).push({ + size: rangeToDiff(caseNode.test, sourceCode), + name: getCaseName(sourceCode, caseNode), + partitionId: accumulator.length, + isEslintDisabled: false, + node: caseNode.test, + group: 'unknown', + }) + } + if ( + caseNode.consequent.length > 0 && + index !== switchNode.cases.length - 1 + ) { + accumulator.push([]) + } + return accumulator + }, + [[]], + ) + let hasUnsortedNodes = false + for (let caseNodesSortingNodeGroup of caseNameSortingNodeGroups) { + let sortedCaseNameSortingNodes = sortNodes({ + comparatorByOptionsComputer: defaultComparatorByOptionsComputer, + nodes: caseNodesSortingNodeGroup, + ignoreEslintDisabledNodes: false, + options, + }) + hasUnsortedNodes ||= sortedCaseNameSortingNodes.some( + (node, index) => node !== caseNodesSortingNodeGroup[index], + ) + let nodeIndexMap = createNodeIndexMap(sortedCaseNameSortingNodes) + pairwise(caseNodesSortingNodeGroup, (left, right) => { + if (!left) { + return + } + if (nodeIndexMap.get(left) < nodeIndexMap.get(right)) { + return + } + reportErrors({ + sortedNodes: sortedCaseNameSortingNodes, + nodes: caseNodesSortingNodeGroup, + messageIds: [ORDER_ERROR_ID], + sourceCode, + context, + right, + left, + }) + }) + } + let sortingNodes = switchNode.cases.map(caseNode => ({ + size: caseNode.test ? rangeToDiff(caseNode.test, sourceCode) : 7, + name: getCaseName(sourceCode, caseNode), + addSafetySemicolonWhenInline: true, + isDefaultClause: !caseNode.test, + isEslintDisabled: false, + group: 'unknown', + partitionId: 0, + node: caseNode, + })) + let sortingNodesGroupWithDefault = reduceCaseSortingNodes( + sortingNodes, + caseNode => caseNode.node.consequent.length > 0, + ).find(caseNodeGroup => caseNodeGroup.some(node => node.isDefaultClause)) + if ( + sortingNodesGroupWithDefault && + !sortingNodesGroupWithDefault.at(-1).isDefaultClause + ) { + let defaultCase = sortingNodesGroupWithDefault.find( + node => node.isDefaultClause, + ) + let lastCase = sortingNodesGroupWithDefault.at(-1) + context.report({ + fix: fixer => { + let punctuatorAfterLastCase = sourceCode.getTokenAfter( + lastCase.node.test, + ) + let lastCaseRange = [ + lastCase.node.range[0], + punctuatorAfterLastCase.range[1], + ] + return [ + fixer.replaceText( + defaultCase.node, + sourceCode.text.slice(...lastCaseRange), + ), + fixer.replaceTextRange( + lastCaseRange, + sourceCode.getText(defaultCase.node), + ), + ...makeSingleNodeCommentAfterFixes({ + sortedNode: punctuatorAfterLastCase, + node: defaultCase.node, + sourceCode, + fixer, + }), + ...makeSingleNodeCommentAfterFixes({ + node: punctuatorAfterLastCase, + sortedNode: defaultCase.node, + sourceCode, + fixer, + }), + ] + }, + data: { + [LEFT]: defaultCase.name, + [RIGHT]: lastCase.name, + }, + messageId: ORDER_ERROR_ID, + node: defaultCase.node, + }) + } + let sortingNodeGroupsForBlockSort = reduceCaseSortingNodes( + sortingNodes, + caseNode => caseHasBreakOrReturn(caseNode.node), + ) + /** + * If the last case does not have a return/break, leave its group at its + * place. + */ + let lastNodeGroup = sortingNodeGroupsForBlockSort.at(-1) + let lastBlockCaseShouldStayInPlace = !caseHasBreakOrReturn( + lastNodeGroup.at(-1).node, + ) + let sortedSortingNodeGroupsForBlockSort = [ + ...sortingNodeGroupsForBlockSort, + ] + .toSorted((a, b) => { + if (lastBlockCaseShouldStayInPlace) { + if (a === lastNodeGroup) { + return 1 + } + /* v8 ignore if -- @preserve last element might never be b. */ + if (b === lastNodeGroup) { + return -1 + } + } + if (a.some(node => node.isDefaultClause)) { + return 1 + } + if (b.some(node => node.isDefaultClause)) { + return -1 + } + return defaultComparator(a.at(0), b.at(0)) + }) + .flat() + let sortingNodeGroupsForBlockSortFlat = + sortingNodeGroupsForBlockSort.flat() + pairwise(sortingNodeGroupsForBlockSortFlat, (left, right) => { + if (!left) { + return + } + if ( + sortedSortingNodeGroupsForBlockSort.indexOf(left) < + sortedSortingNodeGroupsForBlockSort.indexOf(right) + ) { + return + } + context.report({ + fix: fixer => + hasUnsortedNodes ? + [] + : makeFixes({ + sortedNodes: sortedSortingNodeGroupsForBlockSort, + nodes: sortingNodeGroupsForBlockSortFlat, + hasCommentAboveMissing: false, + sourceCode, + fixer, + }), + data: { + [RIGHT]: right.name, + [LEFT]: left.name, + }, + messageId: ORDER_ERROR_ID, + node: right.node, + }) + }) + }, + }), + meta: { + docs: { + url: 'https://perfectionist.dev/rules/sort-switch-case', + description: 'Enforce sorted switch cases.', + recommended: true, + }, + schema: [ + { + properties: buildCommonJsonSchemas(), + additionalProperties: false, + type: 'object', + }, + ], + messages: { [ORDER_ERROR_ID]: ORDER_ERROR }, + type: 'suggestion', + fixable: 'code', + }, + defaultOptions: [defaultOptions], + name: 'sort-switch-case', +}) +/** + * Groups consecutive switch case nodes into blocks for sorting. + * + * Creates partitions of case nodes where each partition ends when the + * `endsBlock` predicate returns true (typically when a case has a break or + * return statement). + * + * @param caseNodes - Array of switch case sorting nodes to partition. + * @param endsBlock - Predicate function that determines if a case ends a block. + * @returns A 2D array where each inner array is a sortable block of cases. + */ +function reduceCaseSortingNodes(caseNodes, endsBlock) { + return caseNodes.reduce( + (accumulator, caseNode, index) => { + accumulator.at(-1).push(caseNode) + if (endsBlock(caseNode) && index !== caseNodes.length - 1) { + accumulator.push([]) + } + return accumulator + }, + [[]], + ) +} +/** + * Extracts the name of a switch case for sorting purposes. + * + * For literal test values, returns the string representation of the value. For + * the default case (null test), returns 'default'. For other expressions, + * returns the source code text. + * + * @param sourceCode - The ESLint source code object. + * @param caseNode - The switch case AST node. + * @returns The name to use for sorting this case. + */ +function getCaseName(sourceCode, caseNode) { + if (caseNode.test?.type === AST_NODE_TYPES.Literal) { + return String(caseNode.test.value) + } + if (caseNode.test === null) { + return 'default' + } + return sourceCode.getText(caseNode.test) +} +/** + * Checks if a switch case contains a break or return statement. + * + * Examines the case's consequent statements, handling both direct statements + * and statements wrapped in a block. + * + * @param caseNode - The switch case AST node to check. + * @returns True if the case contains a break or return statement. + */ +function caseHasBreakOrReturn(caseNode) { + return ( + caseNode.consequent[0]?.type === AST_NODE_TYPES.BlockStatement ? + caseNode.consequent[0].body + : caseNode.consequent).some(statementIsBreakOrReturn) +} +/** + * Type guard that checks if a statement is a break or return statement. + * + * @param statement - The statement AST node to check. + * @returns True if the statement is a BreakStatement or ReturnStatement. + */ +function statementIsBreakOrReturn(statement) { + return ( + statement.type === AST_NODE_TYPES.BreakStatement || + statement.type === AST_NODE_TYPES.ReturnStatement + ) +} +export { sort_switch_case_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-switch-case/is-condition-expression.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-switch-case/is-condition-expression.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2e67080485998c52ef38533f36c142432ff30c24 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-switch-case/is-condition-expression.d.ts @@ -0,0 +1,15 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Checks if an expression is condition-shaped. + * + * Condition-shaped expressions are boolean literals, logical negations, binary + * expressions and logical expressions. Switch statements built on such + * expressions (e.g. `switch (true)`) encode their program logic in the case + * order, so sorting them is unsafe. + * + * @param node - The expression AST node to check. + * @returns True if the expression is condition-shaped. + */ +export declare function isConditionExpression( + node: TSESTree.Expression, +): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-switch-case/is-condition-expression.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-switch-case/is-condition-expression.js new file mode 100644 index 0000000000000000000000000000000000000000..d17aaf0ddee32dcfc61039a12f2ea42751dac92a --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-switch-case/is-condition-expression.js @@ -0,0 +1,26 @@ +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Checks if an expression is condition-shaped. + * + * Condition-shaped expressions are boolean literals, logical negations, binary + * expressions and logical expressions. Switch statements built on such + * expressions (e.g. `switch (true)`) encode their program logic in the case + * order, so sorting them is unsafe. + * + * @param node - The expression AST node to check. + * @returns True if the expression is condition-shaped. + */ +function isConditionExpression(node) { + switch (node.type) { + case AST_NODE_TYPES.LogicalExpression: + case AST_NODE_TYPES.BinaryExpression: + return true + case AST_NODE_TYPES.UnaryExpression: + return node.operator === '!' + case AST_NODE_TYPES.Literal: + return typeof node.value === 'boolean' + default: + return false + } +} +export { isConditionExpression } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-switch-case/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-switch-case/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a63e69586ffe8e4c253a90a8f0459df6619e6485 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-switch-case/types.d.ts @@ -0,0 +1,2 @@ +import { CommonOptions, TypeOption } from '../../types/common-options.js' +export type Options = [Partial>] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/build-json-schema.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/build-json-schema.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b5bf82a60be6b07e57cbde8d615b2dbda52f3606 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/build-json-schema.d.ts @@ -0,0 +1,6 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +export declare function buildJsonSchema({ + ignoreCallableTypes, +}: { + ignoreCallableTypes: boolean +}): JSONSchema4 diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/build-json-schema.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/build-json-schema.js new file mode 100644 index 0000000000000000000000000000000000000000..8282dc540396eeb0d6ffa2d2e0901b673aa20e07 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/build-json-schema.js @@ -0,0 +1,39 @@ +import { + buildCommonJsonSchemas, + buildUseConfigIfJsonSchema, + matchesAstSelectorJsonSchema, +} from '../../utils/json-schemas/common-json-schemas.js' +import { buildCommonGroupsJsonSchemas } from '../../utils/json-schemas/common-groups-json-schemas.js' +import { + partitionByCommentJsonSchema, + partitionByNewlineJsonSchema, +} from '../../utils/json-schemas/common-partition-json-schemas.js' +import { additionalCustomGroupMatchOptionsJsonSchema } from '../sort-union-types/types.js' +function buildJsonSchema({ ignoreCallableTypes }) { + return { + items: { + properties: { + ...buildCommonJsonSchemas(), + ...buildCommonGroupsJsonSchemas({ + additionalCustomGroupMatchProperties: + additionalCustomGroupMatchOptionsJsonSchema, + }), + useConfigurationIf: buildUseConfigIfJsonSchema({ + additionalProperties: { + matchesAstSelector: matchesAstSelectorJsonSchema, + }, + }), + partitionByComment: partitionByCommentJsonSchema, + partitionByNewLine: partitionByNewlineJsonSchema, + ...(ignoreCallableTypes && { + ignoreCallableTypes: { type: 'boolean' }, + }), + }, + additionalProperties: false, + type: 'object', + }, + uniqueItems: true, + type: 'array', + } +} +export { buildJsonSchema } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/compute-matched-context-options.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/compute-matched-context-options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..248561695563e0191ef696aa877be7a71ba9594b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/compute-matched-context-options.d.ts @@ -0,0 +1,25 @@ +import { RuleContext } from '@typescript-eslint/utils/ts-eslint' +import { TSESTree } from '@typescript-eslint/types' +import { Options } from '../sort-intersection-types/types.js' +/** + * Computes the matched context options for a given union/intersection type + * node. + * + * @param params - Parameters. + * @param params.matchedAstSelectors - The matched AST selectors for the + * union/intersection type node. + * @param params.members - The type members to compute the context options for. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +export declare function computeMatchedContextOptions< + MessageIds extends string, +>({ + matchedAstSelectors, + members, + context, +}: { + context: Readonly> + matchedAstSelectors: ReadonlySet + members: TSESTree.TypeNode[] +}): Options[number] | undefined diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/compute-matched-context-options.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/compute-matched-context-options.js new file mode 100644 index 0000000000000000000000000000000000000000..44733377fb6cfbc6e5db1786bd39ae4129ef23cc --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/compute-matched-context-options.js @@ -0,0 +1,49 @@ +import { passesAllNamesMatchPatternFilter } from '../../utils/context-matching/passes-all-names-match-pattern-filter.js' +import { passesAstSelectorFilter } from '../../utils/context-matching/passes-ast-selector-filter.js' +import { computeNodeName } from './compute-node-name.js' +/** + * Computes the matched context options for a given union/intersection type + * node. + * + * @param params - Parameters. + * @param params.matchedAstSelectors - The matched AST selectors for the + * union/intersection type node. + * @param params.members - The type members to compute the context options for. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +function computeMatchedContextOptions({ + matchedAstSelectors, + members, + context, +}) { + let nodeNames = members.map(member => + computeNodeName({ + sourceCode: context.sourceCode, + type: member, + }), + ) + return context.options.find(options => + isContextOptionMatching({ + matchedAstSelectors, + nodeNames, + options, + }), + ) +} +function isContextOptionMatching({ matchedAstSelectors, nodeNames, options }) { + if (!options.useConfigurationIf) { + return true + } + return ( + passesAllNamesMatchPatternFilter({ + allNamesMatchPattern: options.useConfigurationIf.allNamesMatchPattern, + nodeNames, + }) && + passesAstSelectorFilter({ + matchesAstSelector: options.useConfigurationIf.matchesAstSelector, + matchedAstSelectors, + }) + ) +} +export { computeMatchedContextOptions } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/compute-node-name.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/compute-node-name.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d2cca21b507739ec7cf3c32ef17d705ad337100d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/compute-node-name.d.ts @@ -0,0 +1,21 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +/** + * Computes the name of a union/intersection member. + * + * Multi-line parenthesized unions/intersections can include leading `|` or `&` + * in raw source text, while formatter output often omits them. To keep sorting + * stable across both forms, the leading separator prefix is normalized. + * + * @param params - Parameters object. + * @param params.sourceCode - ESLint source code object for text extraction. + * @param params.type - Type node represented by the member text. + * @returns Normalized member text used for sorting and matching. + */ +export declare function computeNodeName({ + sourceCode, + type, +}: { + sourceCode: TSESLint.SourceCode + type: TSESTree.TypeNode +}): string diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/compute-node-name.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/compute-node-name.js new file mode 100644 index 0000000000000000000000000000000000000000..3d547f8d57a48ab1038edd6cf9980be0239b22e3 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/compute-node-name.js @@ -0,0 +1,24 @@ +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the name of a union/intersection member. + * + * Multi-line parenthesized unions/intersections can include leading `|` or `&` + * in raw source text, while formatter output often omits them. To keep sorting + * stable across both forms, the leading separator prefix is normalized. + * + * @param params - Parameters object. + * @param params.sourceCode - ESLint source code object for text extraction. + * @param params.type - Type node represented by the member text. + * @returns Normalized member text used for sorting and matching. + */ +function computeNodeName({ sourceCode, type }) { + let name = sourceCode.getText(type) + if ( + type.type !== AST_NODE_TYPES.TSUnionType && + type.type !== AST_NODE_TYPES.TSIntersectionType + ) { + return name + } + return name.replace(/^\s*[&|]\s*/u, '') +} +export { computeNodeName } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/sort-union-or-intersection-types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/sort-union-or-intersection-types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ff8ac19d701f356e1c184135487ec172fd55ef41 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/sort-union-or-intersection-types.d.ts @@ -0,0 +1,27 @@ +import { RuleContext } from '@typescript-eslint/utils/ts-eslint' +import { TSESTree } from '@typescript-eslint/types' +import { Options } from '../sort-intersection-types/types.js' +export declare function sortUnionOrIntersectionTypes< + MessageIds extends string, +>({ + cachedGroupsByModifiersAndSelectors, + tokenValueToIgnoreBefore, + matchedAstSelectors, + availableMessageIds, + defaultOptions, + context, + node, +}: { + availableMessageIds: { + missedSpacingBetweenMembers: MessageIds + extraSpacingBetweenMembers: MessageIds + unexpectedGroupOrder: MessageIds + unexpectedOrder: MessageIds + } + cachedGroupsByModifiersAndSelectors: Map + node: TSESTree.TSIntersectionType | TSESTree.TSUnionType + context: Readonly> + defaultOptions: Required + matchedAstSelectors: ReadonlySet + tokenValueToIgnoreBefore: string +}): void diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/sort-union-or-intersection-types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/sort-union-or-intersection-types.js new file mode 100644 index 0000000000000000000000000000000000000000..70728334a5b6bb0acfd55bd5247b188ad4b8b552 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/sort-union-or-intersection-types.js @@ -0,0 +1,187 @@ +import { defaultComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +import { validateNewlinesAndPartitionConfig } from '../../utils/validate-newlines-and-partition-config.js' +import { buildOptionsByGroupIndexComputer } from '../../utils/build-options-by-group-index-computer.js' +import { validateCustomSortConfig } from '../../utils/validate-custom-sort-config.js' +import { generatePredefinedGroups } from '../../utils/generate-predefined-groups.js' +import { getEslintDisabledLines } from '../../utils/get-eslint-disabled-lines.js' +import { doesCustomGroupMatch } from '../../utils/does-custom-group-match.js' +import { isNodeEslintDisabled } from '../../utils/is-node-eslint-disabled.js' +import { validateGroupsConfig } from '../../utils/validate-groups-config.js' +import { sortNodesByGroups } from '../../utils/sort-nodes-by-groups.js' +import { reportAllErrors } from '../../utils/report-all-errors.js' +import { shouldPartition } from '../../utils/should-partition.js' +import { computeGroup } from '../../utils/compute-group.js' +import { rangeToDiff } from '../../utils/range-to-diff.js' +import { getSettings } from '../../utils/get-settings.js' +import { complete } from '../../utils/complete.js' +import { allSelectors } from '../sort-union-types/types.js' +import { computeNodeName } from './compute-node-name.js' +import { computeMatchedContextOptions } from './compute-matched-context-options.js' +import { typeContainsCallableType } from './type-contains-callable-type.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +function sortUnionOrIntersectionTypes({ + cachedGroupsByModifiersAndSelectors, + tokenValueToIgnoreBefore, + matchedAstSelectors, + availableMessageIds, + defaultOptions, + context, + node, +}) { + let settings = getSettings(context.settings) + let matchedContextOptions = computeMatchedContextOptions({ + members: node.types, + matchedAstSelectors, + context, + }) + let options = complete(matchedContextOptions, settings, defaultOptions) + validateCustomSortConfig(options) + validateGroupsConfig({ + selectors: allSelectors, + modifiers: [], + options, + }) + validateNewlinesAndPartitionConfig(options) + if ( + options.ignoreCallableTypes && + node.types.some(typeContainsCallableType) + ) { + return + } + let { sourceCode, id } = context + let eslintDisabledLines = getEslintDisabledLines({ + ruleName: id, + sourceCode, + }) + let optionsByGroupIndexComputer = buildOptionsByGroupIndexComputer(options) + let formattedMembers = node.types.reduce( + (accumulator, type) => { + let selectors = [] + switch (type.type) { + case AST_NODE_TYPES.TSTemplateLiteralType: + case AST_NODE_TYPES.TSLiteralType: + selectors.push('literal') + break + case AST_NODE_TYPES.TSIndexedAccessType: + case AST_NODE_TYPES.TSTypeReference: + case AST_NODE_TYPES.TSQualifiedName: + case AST_NODE_TYPES.TSArrayType: + case AST_NODE_TYPES.TSInferType: + selectors.push('named') + break + case AST_NODE_TYPES.TSIntersectionType: + selectors.push('intersection') + break + case AST_NODE_TYPES.TSUndefinedKeyword: + case AST_NODE_TYPES.TSNullKeyword: + case AST_NODE_TYPES.TSVoidKeyword: + selectors.push('nullish') + break + case AST_NODE_TYPES.TSConditionalType: + selectors.push('conditional') + break + case AST_NODE_TYPES.TSConstructorType: + case AST_NODE_TYPES.TSFunctionType: + selectors.push('function') + break + case AST_NODE_TYPES.TSBooleanKeyword: + case AST_NODE_TYPES.TSUnknownKeyword: + case AST_NODE_TYPES.TSBigIntKeyword: + case AST_NODE_TYPES.TSNumberKeyword: + case AST_NODE_TYPES.TSObjectKeyword: + case AST_NODE_TYPES.TSStringKeyword: + case AST_NODE_TYPES.TSSymbolKeyword: + case AST_NODE_TYPES.TSNeverKeyword: + case AST_NODE_TYPES.TSAnyKeyword: + case AST_NODE_TYPES.TSThisType: + selectors.push('keyword') + break + case AST_NODE_TYPES.TSTypeOperator: + case AST_NODE_TYPES.TSTypeQuery: + selectors.push('operator') + break + case AST_NODE_TYPES.TSTypeLiteral: + case AST_NODE_TYPES.TSMappedType: + selectors.push('object') + break + case AST_NODE_TYPES.TSImportType: + selectors.push('import') + break + case AST_NODE_TYPES.TSTupleType: + selectors.push('tuple') + break + case AST_NODE_TYPES.TSUnionType: + selectors.push('union') + } + let name = computeNodeName({ + sourceCode, + type, + }) + let predefinedGroups = generatePredefinedGroups({ + cache: cachedGroupsByModifiersAndSelectors, + modifiers: [], + selectors, + }) + let group = computeGroup({ + customGroupMatcher: customGroup => + doesCustomGroupMatch({ + elementName: name, + modifiers: [], + customGroup, + selectors, + }), + predefinedGroups, + options, + }) + let lastGroup = accumulator.at(-1) + let lastSortingNode = lastGroup?.at(-1) + let sortingNode = { + isEslintDisabled: isNodeEslintDisabled(type, eslintDisabledLines), + size: rangeToDiff(type, sourceCode), + node: type, + group, + name, + } + if ( + shouldPartition({ + tokenValueToIgnoreBefore, + lastSortingNode, + sortingNode, + sourceCode, + options, + }) + ) { + lastGroup = [] + accumulator.push(lastGroup) + } + lastGroup?.push({ + ...sortingNode, + partitionId: accumulator.length, + }) + return accumulator + }, + [[]], + ) + for (let nodes of formattedMembers) { + reportAllErrors({ + sortNodesExcludingEslintDisabled: + createSortNodesExcludingEslintDisabled(nodes), + availableMessageIds, + options, + context, + nodes, + }) + } + function createSortNodesExcludingEslintDisabled(sortingNodes) { + return function (ignoreEslintDisabledNodes) { + return sortNodesByGroups({ + comparatorByOptionsComputer: defaultComparatorByOptionsComputer, + optionsByGroupIndexComputer, + ignoreEslintDisabledNodes, + groups: options.groups, + nodes: sortingNodes, + }) + } + } +} +export { sortUnionOrIntersectionTypes } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/type-contains-callable-type.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/type-contains-callable-type.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a000bf85ee309d7c057318362b42c0b1fd687ffc --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/type-contains-callable-type.d.ts @@ -0,0 +1,10 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Checks if a type node contains a callable type (function or constructor). + * + * @param typeNode - The type node to check. + * @returns True if the type node contains a callable type, false otherwise. + */ +export declare function typeContainsCallableType( + typeNode: TSESTree.TypeNode, +): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/type-contains-callable-type.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/type-contains-callable-type.js new file mode 100644 index 0000000000000000000000000000000000000000..db6f128c0a8c68a79f377ede8733447ebfa03537 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-or-intersection-types/type-contains-callable-type.js @@ -0,0 +1,38 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Checks if a type node contains a callable type (function or constructor). + * + * @param typeNode - The type node to check. + * @returns True if the type node contains a callable type, false otherwise. + */ +function typeContainsCallableType(typeNode) { + switch (typeNode.type) { + case AST_NODE_TYPES.TSConstructorType: + case AST_NODE_TYPES.TSFunctionType: + return true + case AST_NODE_TYPES.TSTypeLiteral: + return typeNode.members.some(typeElementContainsCallableType) + default: + return false + } + function typeElementContainsCallableType(member) { + switch (member.type) { + case AST_NODE_TYPES.TSConstructSignatureDeclaration: + case AST_NODE_TYPES.TSIndexSignature: + return false + case AST_NODE_TYPES.TSCallSignatureDeclaration: + case AST_NODE_TYPES.TSMethodSignature: + return true + case AST_NODE_TYPES.TSPropertySignature: + return !!( + member.typeAnnotation && + typeContainsCallableType(member.typeAnnotation.typeAnnotation) + ) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(member) + } + } +} +export { typeContainsCallableType } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..25ed32a1ce2d6c19fb45b14bffd7cbaff38d0401 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-types.d.ts @@ -0,0 +1,21 @@ +import { Options } from './sort-union-types/types.js' +declare const ORDER_ERROR_ID = 'unexpectedUnionTypesOrder' +declare const GROUP_ORDER_ERROR_ID = 'unexpectedUnionTypesGroupOrder' +declare const EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenUnionTypes' +declare const MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenUnionTypes' +type MessageId = + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +declare const _default: import('@typescript-eslint/utils/ts-eslint').RuleModule< + MessageId, + Options, + { + recommended?: boolean + }, + import('@typescript-eslint/utils/ts-eslint').RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-types.js new file mode 100644 index 0000000000000000000000000000000000000000..a18fa14eb6215905b4ef18f9a198c93fbfaa3ddf --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-types.js @@ -0,0 +1,81 @@ +import { + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { buildAstListeners } from '../utils/build-ast-listeners.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { sortUnionOrIntersectionTypes } from './sort-union-or-intersection-types/sort-union-or-intersection-types.js' +import { buildJsonSchema } from './sort-union-or-intersection-types/build-json-schema.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Cache computed groups by modifiers and selectors for performance. + */ +var cachedGroupsByModifiersAndSelectors = /* @__PURE__ */ new Map() +var ORDER_ERROR_ID = 'unexpectedUnionTypesOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedUnionTypesGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenUnionTypes' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenUnionTypes' +var defaultOptions = { + fallbackSort: { type: 'unsorted' }, + newlinesInside: 'newlinesBetween', + specialCharacters: 'keep', + newlinesBetween: 'ignore', + partitionByNewLine: false, + partitionByComment: false, + useConfigurationIf: {}, + type: 'alphabetical', + ignoreCase: true, + locales: 'en-US', + customGroups: [], + alphabet: '', + order: 'asc', + groups: [], +} +var sort_union_types_default = createEslintRule({ + meta: { + messages: { + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-union-types', + description: 'Enforce sorted union types.', + recommended: true, + }, + schema: buildJsonSchema({ ignoreCallableTypes: false }), + type: 'suggestion', + fixable: 'code', + }, + create: context => + buildAstListeners({ + nodeTypes: [AST_NODE_TYPES.TSUnionType], + sorter: sortUnionType, + context, + }), + defaultOptions: [defaultOptions], + name: 'sort-union-types', +}) +function sortUnionType({ matchedAstSelectors, context, node }) { + sortUnionOrIntersectionTypes({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + defaultOptions: { + ...defaultOptions, + ignoreCallableTypes: false, + }, + cachedGroupsByModifiersAndSelectors, + tokenValueToIgnoreBefore: '|', + matchedAstSelectors, + context, + node, + }) +} +export { sort_union_types_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-types/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-types/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2ccb4a792263b681eefae97a93598ab9472ed385 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-types/types.d.ts @@ -0,0 +1,80 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +import { TSESTree } from '@typescript-eslint/types' +import { RegexOption, TypeOption } from '../../types/common-options.js' +import { AllCommonOptions } from '../../types/all-common-options.js' +import { SortingNode } from '../../types/sorting-node.js' +/** + * Configuration options for the sort-union-types rule. + * + * Controls how TypeScript union type members are sorted. + */ +export type Options = Partial< + { + /** + * Conditional configuration based on pattern matching. + */ + useConfigurationIf: { + /** + * Regular expression pattern to match against all member names. The + * rule is only applied when all member names match this pattern. + */ + allNamesMatchPattern?: RegexOption + /** + * AST selector to match against TSUnionType or TSIntersectionType + * nodes. + */ + matchesAstSelector?: string + } + } & AllCommonOptions< + TypeOption, + AdditionalSortOptions, + CustomGroupMatchOptions + > +>[] +export type SortUnionOrIntersectionSortingNode = SortingNode +/** + * Union type of all available selectors for union type members. + * + * Selectors categorize different kinds of TypeScript types that can appear in a + * union, enabling fine-grained control over sorting. + */ +export type Selector = (typeof allSelectors)[number] +/** + * Match options for a custom group. + */ +interface CustomGroupMatchOptions { + /** + * The selector type this group matches. Determines what kind of type + * members belong to this group. + */ + selector?: Selector +} +type AdditionalSortOptions = object +/** + * Array of all available selectors for union type members. + * + * Used for validation and configuration in the ESLint rule. + */ +export declare let allSelectors: readonly [ + 'intersection', + 'conditional', + 'function', + 'operator', + 'keyword', + 'literal', + 'nullish', + 'import', + 'object', + 'named', + 'tuple', + 'union', +] +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +export declare let additionalCustomGroupMatchOptionsJsonSchema: Record< + string, + JSONSchema4 +> +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-types/types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-types/types.js new file mode 100644 index 0000000000000000000000000000000000000000..a448abca03c096755f6359317990944d8555d115 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-union-types/types.js @@ -0,0 +1,28 @@ +import { buildCustomGroupSelectorJsonSchema } from '../../utils/json-schemas/common-groups-json-schemas.js' +/** + * Array of all available selectors for union type members. + * + * Used for validation and configuration in the ESLint rule. + */ +var allSelectors = [ + 'intersection', + 'conditional', + 'function', + 'operator', + 'keyword', + 'literal', + 'nullish', + 'import', + 'object', + 'named', + 'tuple', + 'union', +] +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +var additionalCustomGroupMatchOptionsJsonSchema = { + selector: buildCustomGroupSelectorJsonSchema(allSelectors), +} +export { additionalCustomGroupMatchOptionsJsonSchema, allSelectors } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3a14e36c5104af3bd96a3329475034d206002d72 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations.d.ts @@ -0,0 +1,12 @@ +import { MessageId, Options } from './sort-variable-declarations/types.js' +declare const _default: import('@typescript-eslint/utils/ts-eslint').RuleModule< + MessageId, + Options, + { + recommended?: boolean + }, + import('@typescript-eslint/utils/ts-eslint').RuleListener +> & { + name: string +} +export default _default diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations.js new file mode 100644 index 0000000000000000000000000000000000000000..6e5ef6b495ec6eba2e8f428ec8524e4e363fbacd --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations.js @@ -0,0 +1,84 @@ +import { + buildCommonJsonSchemas, + buildUseConfigIfJsonSchema, + matchesAstSelectorJsonSchema, + useExperimentalDependencyDetectionJsonSchema, +} from '../utils/json-schemas/common-json-schemas.js' +import { buildCommonGroupsJsonSchemas } from '../utils/json-schemas/common-groups-json-schemas.js' +import { + DEPENDENCY_ORDER_ERROR_ID, + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + additionalCustomGroupMatchOptionsJsonSchema, +} from './sort-variable-declarations/types.js' +import { + DEPENDENCY_ORDER_ERROR, + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, +} from '../utils/report-errors.js' +import { + partitionByCommentJsonSchema, + partitionByNewlineJsonSchema, +} from '../utils/json-schemas/common-partition-json-schemas.js' +import { + defaultOptions, + sortVariableDeclaration, +} from './sort-variable-declarations/sort-variable-declaration.js' +import { buildAstListeners } from '../utils/build-ast-listeners.js' +import { createEslintRule } from '../utils/create-eslint-rule.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +var sort_variable_declarations_default = createEslintRule({ + meta: { + schema: { + items: { + properties: { + ...buildCommonJsonSchemas(), + ...buildCommonGroupsJsonSchemas({ + additionalCustomGroupMatchProperties: + additionalCustomGroupMatchOptionsJsonSchema, + }), + useConfigurationIf: buildUseConfigIfJsonSchema({ + additionalProperties: { + matchesAstSelector: matchesAstSelectorJsonSchema, + }, + }), + useExperimentalDependencyDetection: + useExperimentalDependencyDetectionJsonSchema, + partitionByComment: partitionByCommentJsonSchema, + partitionByNewLine: partitionByNewlineJsonSchema, + }, + additionalProperties: false, + type: 'object', + }, + uniqueItems: true, + type: 'array', + }, + messages: { + [DEPENDENCY_ORDER_ERROR_ID]: DEPENDENCY_ORDER_ERROR, + [MISSED_SPACING_ERROR_ID]: MISSED_SPACING_ERROR, + [EXTRA_SPACING_ERROR_ID]: EXTRA_SPACING_ERROR, + [GROUP_ORDER_ERROR_ID]: GROUP_ORDER_ERROR, + [ORDER_ERROR_ID]: ORDER_ERROR, + }, + docs: { + url: 'https://perfectionist.dev/rules/sort-variable-declarations', + description: 'Enforce sorted variable declarations.', + recommended: true, + }, + type: 'suggestion', + fixable: 'code', + }, + create: context => + buildAstListeners({ + nodeTypes: [AST_NODE_TYPES.VariableDeclaration], + sorter: sortVariableDeclaration, + context, + }), + name: 'sort-variable-declarations', + defaultOptions: [defaultOptions], +}) +export { sort_variable_declarations_default as default } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/compute-dependencies.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/compute-dependencies.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..98bed3b16c1b6484f41a43f564922b38715869a8 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/compute-dependencies.d.ts @@ -0,0 +1,12 @@ +import { SortVariableDeclarationsNode } from './types.js' +/** + * Computes the dependencies of a variable declaration node. + * + * @deprecated - To remove when experimental dependency detection is the only + * option. + * @param node - The AST node to analyze. + * @returns The names of the dependencies. + */ +export declare function computeDependencies( + node: SortVariableDeclarationsNode, +): string[] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/compute-dependencies.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/compute-dependencies.js new file mode 100644 index 0000000000000000000000000000000000000000..1bfb9fc53a9fda1ff9e1f21cda3b9374ff8ea021 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/compute-dependencies.js @@ -0,0 +1,94 @@ +import { isNodeImmediatelyCalled } from '../../utils/is-node-immediately-called.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the dependencies of a variable declaration node. + * + * @deprecated - To remove when experimental dependency detection is the only + * option. + * @param node - The AST node to analyze. + * @returns The names of the dependencies. + */ +function computeDependencies(node) { + return [ + ...computeExpressionDependencies(node.id), + ...(node.init ? computeExpressionDependencies(node.init) : []), + ] +} +function computeExpressionDependencies(expression) { + let dependencies = [] + checkNode(expression) + return dependencies + function checkNode(node) { + switch (node.type) { + /** + * No need to check the body of functions and arrow functions, unless they + * are immediately called. + */ + case AST_NODE_TYPES.ArrowFunctionExpression: + case AST_NODE_TYPES.FunctionExpression: + if (!isNodeImmediatelyCalled(node)) { + return + } + checkNode(node.body) + return + case AST_NODE_TYPES.ConditionalExpression: + checkNode(node.test) + checkNode(node.consequent) + checkNode(node.alternate) + break + case AST_NODE_TYPES.BlockStatement: + for (let statement of node.body) { + checkNode(statement) + } + break + case AST_NODE_TYPES.Identifier: + dependencies.push(node.name) + break + case AST_NODE_TYPES.Property: + if (node.computed) { + checkNode(node.key) + } + checkNode(node.value) + } + if ('expression' in node && typeof node.expression !== 'boolean') { + checkNode(node.expression) + } + if ('object' in node) { + checkNode(node.object) + } + if ('callee' in node) { + checkNode(node.callee) + } + if ('left' in node) { + checkNode(node.left) + } + if ('right' in node) { + checkNode(node.right) + } + if ('elements' in node) { + let elements = node.elements.filter(currentNode => currentNode !== null) + for (let element of elements) { + checkNode(element) + } + } + if ('argument' in node && node.argument) { + checkNode(node.argument) + } + if ('arguments' in node) { + for (let argument of node.arguments) { + checkNode(argument) + } + } + if ('properties' in node) { + for (let property of node.properties) { + checkNode(property) + } + } + if ('expressions' in node) { + for (let nodeExpression of node.expressions) { + checkNode(nodeExpression) + } + } + } +} +export { computeDependencies } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/compute-matched-context-options.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/compute-matched-context-options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..26a440cc8a6103e128ccb4f105082cdd5447bf17 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/compute-matched-context-options.d.ts @@ -0,0 +1,27 @@ +import { RuleContext } from '@typescript-eslint/utils/ts-eslint' +import { TSESLint } from '@typescript-eslint/utils' +import { TSESTree } from '@typescript-eslint/types' +import { MessageId, Options } from './types.js' +/** + * Computes the matched context options for a given variable declaration node. + * + * @param params - Parameters. + * @param params.node - The variable declaration node to compute the context + * options for. + * @param params.matchedAstSelectors - The matched AST selectors for an object + * node. + * @param params.sourceCode - The ESLint source code object. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +export declare function computeMatchedContextOptions({ + matchedAstSelectors, + sourceCode, + context, + node, +}: { + context: Readonly> + matchedAstSelectors: ReadonlySet + node: TSESTree.VariableDeclaration + sourceCode: TSESLint.SourceCode +}): Options[number] | undefined diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/compute-matched-context-options.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/compute-matched-context-options.js new file mode 100644 index 0000000000000000000000000000000000000000..a747ca1ed6c1359ccd38f0781ce595aca657a94f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/compute-matched-context-options.js @@ -0,0 +1,51 @@ +import { passesAllNamesMatchPatternFilter } from '../../utils/context-matching/passes-all-names-match-pattern-filter.js' +import { passesAstSelectorFilter } from '../../utils/context-matching/passes-ast-selector-filter.js' +import { computeNodeName } from './compute-node-name.js' +/** + * Computes the matched context options for a given variable declaration node. + * + * @param params - Parameters. + * @param params.node - The variable declaration node to compute the context + * options for. + * @param params.matchedAstSelectors - The matched AST selectors for an object + * node. + * @param params.sourceCode - The ESLint source code object. + * @param params.context - The rule context. + * @returns The matched context options or undefined if none match. + */ +function computeMatchedContextOptions({ + matchedAstSelectors, + sourceCode, + context, + node, +}) { + let nodeNames = node.declarations.map(declaration => + computeNodeName({ + node: declaration, + sourceCode, + }), + ) + return context.options.find(options => + isContextOptionMatching({ + matchedAstSelectors, + nodeNames, + options, + }), + ) +} +function isContextOptionMatching({ matchedAstSelectors, nodeNames, options }) { + if (!options.useConfigurationIf) { + return true + } + return ( + passesAllNamesMatchPatternFilter({ + allNamesMatchPattern: options.useConfigurationIf.allNamesMatchPattern, + nodeNames, + }) && + passesAstSelectorFilter({ + matchesAstSelector: options.useConfigurationIf.matchesAstSelector, + matchedAstSelectors, + }) + ) +} +export { computeMatchedContextOptions } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/compute-node-name.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/compute-node-name.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5e513f1d3d4d3c3e440ea7ce28d08e641e543382 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/compute-node-name.d.ts @@ -0,0 +1,17 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { SortVariableDeclarationsNode } from './types.js' +/** + * Computes the name of a variable declaration. + * + * @param props - The parameters object. + * @param props.sourceCode - ESLint source code object for text extraction. + * @param props.node - The AST node representing a variable declaration node. + * @returns The name of the variable declaration node. + */ +export declare function computeNodeName({ + sourceCode, + node, +}: { + node: SortVariableDeclarationsNode + sourceCode: TSESLint.SourceCode +}): string diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/compute-node-name.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/compute-node-name.js new file mode 100644 index 0000000000000000000000000000000000000000..783093d4d8a77b001ede90c97c19f1b0381d62ff --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/compute-node-name.js @@ -0,0 +1,23 @@ +import { UnreachableCaseError } from '../../utils/unreachable-case-error.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Computes the name of a variable declaration. + * + * @param props - The parameters object. + * @param props.sourceCode - ESLint source code object for text extraction. + * @param props.node - The AST node representing a variable declaration node. + * @returns The name of the variable declaration node. + */ +function computeNodeName({ sourceCode, node }) { + switch (node.id.type) { + case AST_NODE_TYPES.ObjectPattern: + case AST_NODE_TYPES.ArrayPattern: + return sourceCode.text.slice(...node.id.range) + case AST_NODE_TYPES.Identifier: + return node.id.name + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(node.id) + } +} +export { computeNodeName } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/sort-variable-declaration.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/sort-variable-declaration.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..57474b316e71d7816d16f8c5ae41e002ddf94bd0 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/sort-variable-declaration.d.ts @@ -0,0 +1,13 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { TSESTree } from '@typescript-eslint/types' +import { MessageId, Options } from './types.js' +export declare let defaultOptions: Required +export declare function sortVariableDeclaration({ + matchedAstSelectors, + context, + node, +}: { + context: TSESLint.RuleContext + matchedAstSelectors: ReadonlySet + node: TSESTree.VariableDeclaration +}): void diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/sort-variable-declaration.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/sort-variable-declaration.js new file mode 100644 index 0000000000000000000000000000000000000000..ecdfa4db898f69003bdf7121c24b1a4042dfd94d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/sort-variable-declaration.js @@ -0,0 +1,174 @@ +import { + DEPENDENCY_ORDER_ERROR_ID, + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + allSelectors, +} from './types.js' +import { computeDependenciesOutsideFunctionsBySortingNode } from '../../utils/compute-dependencies-outside-functions-by-sorting-node.js' +import { populateSortingNodeGroupsWithDependencies } from '../../utils/populate-sorting-node-groups-with-dependencies.js' +import { defaultComparatorByOptionsComputer } from '../../utils/compare/default-comparator-by-options-computer.js' +import { validateNewlinesAndPartitionConfig } from '../../utils/validate-newlines-and-partition-config.js' +import { buildOptionsByGroupIndexComputer } from '../../utils/build-options-by-group-index-computer.js' +import { validateCustomSortConfig } from '../../utils/validate-custom-sort-config.js' +import { generatePredefinedGroups } from '../../utils/generate-predefined-groups.js' +import { computeNodeName } from './compute-node-name.js' +import { computeMatchedContextOptions } from './compute-matched-context-options.js' +import { sortNodesByDependencies } from '../../utils/sort-nodes-by-dependencies.js' +import { getEslintDisabledLines } from '../../utils/get-eslint-disabled-lines.js' +import { doesCustomGroupMatch } from '../../utils/does-custom-group-match.js' +import { isNodeEslintDisabled } from '../../utils/is-node-eslint-disabled.js' +import { validateGroupsConfig } from '../../utils/validate-groups-config.js' +import { sortNodesByGroups } from '../../utils/sort-nodes-by-groups.js' +import { reportAllErrors } from '../../utils/report-all-errors.js' +import { shouldPartition } from '../../utils/should-partition.js' +import { computeDependencies } from './compute-dependencies.js' +import { computeGroup } from '../../utils/compute-group.js' +import { rangeToDiff } from '../../utils/range-to-diff.js' +import { getSettings } from '../../utils/get-settings.js' +import { isSortable } from '../../utils/is-sortable.js' +import { complete } from '../../utils/complete.js' +/** + * Cache computed groups by modifiers and selectors for performance. + */ +var cachedGroupsByModifiersAndSelectors = /* @__PURE__ */ new Map() +var defaultOptions = { + useExperimentalDependencyDetection: true, + fallbackSort: { type: 'unsorted' }, + newlinesInside: 'newlinesBetween', + specialCharacters: 'keep', + partitionByNewLine: false, + partitionByComment: false, + newlinesBetween: 'ignore', + useConfigurationIf: {}, + type: 'alphabetical', + customGroups: [], + ignoreCase: true, + locales: 'en-US', + alphabet: '', + order: 'asc', + groups: [], +} +function sortVariableDeclaration({ matchedAstSelectors, context, node }) { + if (!isSortable(node.declarations)) { + return + } + let { sourceCode, id } = context + let settings = getSettings(context.settings) + let matchedContextOptions = computeMatchedContextOptions({ + matchedAstSelectors, + sourceCode, + context, + node, + }) + let options = complete(matchedContextOptions, settings, defaultOptions) + validateCustomSortConfig(options) + validateNewlinesAndPartitionConfig(options) + validateGroupsConfig({ + selectors: allSelectors, + modifiers: [], + options, + }) + let eslintDisabledLines = getEslintDisabledLines({ + ruleName: id, + sourceCode, + }) + let optionsByGroupIndexComputer = buildOptionsByGroupIndexComputer(options) + let sortingNodeGroups = node.declarations.reduce( + (accumulator, declaration) => { + let name = computeNodeName({ + node: declaration, + sourceCode, + }) + let selector = declaration.init ? 'initialized' : 'uninitialized' + let predefinedGroups = generatePredefinedGroups({ + cache: cachedGroupsByModifiersAndSelectors, + selectors: [selector], + modifiers: [], + }) + let lastSortingNode = accumulator.at(-1)?.at(-1) + let sortingNode = { + group: computeGroup({ + customGroupMatcher: customGroup => + doesCustomGroupMatch({ + selectors: [selector], + elementName: name, + modifiers: [], + customGroup, + }), + predefinedGroups, + options, + }), + dependencies: + options.useExperimentalDependencyDetection ? + [] + : computeDependencies(declaration), + isEslintDisabled: isNodeEslintDisabled( + declaration, + eslintDisabledLines, + ), + size: rangeToDiff(declaration, sourceCode), + dependencyNames: [name], + node: declaration, + name, + } + if ( + shouldPartition({ + lastSortingNode, + sortingNode, + sourceCode, + options, + }) + ) { + accumulator.push([]) + } + accumulator.at(-1)?.push({ + ...sortingNode, + partitionId: accumulator.length, + }) + return accumulator + }, + [[]], + ) + if (options.useExperimentalDependencyDetection) { + let dependenciesBySortingNode = + computeDependenciesOutsideFunctionsBySortingNode({ + sortingNodes: sortingNodeGroups.flat(), + sourceCode, + }) + sortingNodeGroups = populateSortingNodeGroupsWithDependencies({ + dependenciesBySortingNode, + sortingNodeGroups, + }) + } + let sortingNodes = sortingNodeGroups.flat() + reportAllErrors({ + availableMessageIds: { + missedSpacingBetweenMembers: MISSED_SPACING_ERROR_ID, + unexpectedDependencyOrder: DEPENDENCY_ORDER_ERROR_ID, + extraSpacingBetweenMembers: EXTRA_SPACING_ERROR_ID, + unexpectedGroupOrder: GROUP_ORDER_ERROR_ID, + unexpectedOrder: ORDER_ERROR_ID, + }, + sortNodesExcludingEslintDisabled, + nodes: sortingNodes, + options, + context, + }) + function sortNodesExcludingEslintDisabled(ignoreEslintDisabledNodes) { + let nodesSortedByGroups = sortingNodeGroups.flatMap(sortingNodeGroup => + sortNodesByGroups({ + comparatorByOptionsComputer: defaultComparatorByOptionsComputer, + optionsByGroupIndexComputer, + ignoreEslintDisabledNodes, + nodes: sortingNodeGroup, + groups: options.groups, + }), + ) + return sortNodesByDependencies(nodesSortedByGroups, { + ignoreEslintDisabledNodes, + }) + } +} +export { defaultOptions, sortVariableDeclaration } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ef34323a7e5f522aa07d3a7f77956a790e62e9fd --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/types.d.ts @@ -0,0 +1,88 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +import { TSESTree } from '@typescript-eslint/types' +import { SortingNodeWithDependencies } from '../../utils/sort-nodes-by-dependencies.js' +import { RegexOption, TypeOption } from '../../types/common-options.js' +import { AllCommonOptions } from '../../types/all-common-options.js' +export type MessageId = + | typeof DEPENDENCY_ORDER_ERROR_ID + | typeof MISSED_SPACING_ERROR_ID + | typeof EXTRA_SPACING_ERROR_ID + | typeof GROUP_ORDER_ERROR_ID + | typeof ORDER_ERROR_ID +export declare const ORDER_ERROR_ID = 'unexpectedVariableDeclarationsOrder' +export declare const GROUP_ORDER_ERROR_ID = + 'unexpectedVariableDeclarationsGroupOrder' +export declare const EXTRA_SPACING_ERROR_ID = + 'extraSpacingBetweenVariableDeclarationsMembers' +export declare const MISSED_SPACING_ERROR_ID = + 'missedSpacingBetweenVariableDeclarationsMembers' +export declare const DEPENDENCY_ORDER_ERROR_ID = + 'unexpectedVariableDeclarationsDependencyOrder' +/** + * Configuration options for the sort-variable-declarations rule. + * + * Controls how multiple variable declarations in a single statement are sorted, + * such as `const a = 1, b, c = 3;`. + */ +export type Options = Partial< + { + /** + * Conditional configuration based on pattern matching. + */ + useConfigurationIf: { + /** + * Regular expression pattern to match against all variable declarator + * names. The rule is only applied when all names match this pattern. + */ + allNamesMatchPattern?: RegexOption + /** + * AST selector to match against VariableDeclaration nodes. + */ + matchesAstSelector?: string + } + /** + * Enables experimental dependency detection. + */ + useExperimentalDependencyDetection: boolean + } & AllCommonOptions< + TypeOption, + AdditionalSortOptions, + CustomGroupMatchOptions + > +>[] +export type SortVariableDeclarationsSortingNode = + SortingNodeWithDependencies +export type SortVariableDeclarationsNode = + TSESTree.VariableDeclaration['declarations'][number] +/** + * Union type of all available selectors for variable declarations. + * + * Distinguishes between variables with and without initial values. + */ +export type Selector = (typeof allSelectors)[number] +/** + * Match options for a custom group. + */ +interface CustomGroupMatchOptions { + /** + * The selector type this group matches. Can be 'initialized' for variables + * with values or 'uninitialized' for variables without. + */ + selector?: Selector +} +type AdditionalSortOptions = object +/** + * Array of all available selectors for variable declarations. + * + * Used for validation and configuration in the ESLint rule. + */ +export declare let allSelectors: readonly ['initialized', 'uninitialized'] +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +export declare let additionalCustomGroupMatchOptionsJsonSchema: Record< + string, + JSONSchema4 +> +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/types.js new file mode 100644 index 0000000000000000000000000000000000000000..f309b954d0206eedd6dc2f46d0f9976d22c2f756 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/rules/sort-variable-declarations/types.js @@ -0,0 +1,28 @@ +import { buildCustomGroupSelectorJsonSchema } from '../../utils/json-schemas/common-groups-json-schemas.js' +var ORDER_ERROR_ID = 'unexpectedVariableDeclarationsOrder' +var GROUP_ORDER_ERROR_ID = 'unexpectedVariableDeclarationsGroupOrder' +var EXTRA_SPACING_ERROR_ID = 'extraSpacingBetweenVariableDeclarationsMembers' +var MISSED_SPACING_ERROR_ID = 'missedSpacingBetweenVariableDeclarationsMembers' +var DEPENDENCY_ORDER_ERROR_ID = 'unexpectedVariableDeclarationsDependencyOrder' +/** + * Array of all available selectors for variable declarations. + * + * Used for validation and configuration in the ESLint rule. + */ +var allSelectors = ['initialized', 'uninitialized'] +/** + * Additional custom group match options JSON schema. Used by ESLint to validate + * rule options at configuration time. + */ +var additionalCustomGroupMatchOptionsJsonSchema = { + selector: buildCustomGroupSelectorJsonSchema(allSelectors), +} +export { + DEPENDENCY_ORDER_ERROR_ID, + EXTRA_SPACING_ERROR_ID, + GROUP_ORDER_ERROR_ID, + MISSED_SPACING_ERROR_ID, + ORDER_ERROR_ID, + additionalCustomGroupMatchOptionsJsonSchema, + allSelectors, +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/all-common-options.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/all-common-options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..625efb51c0ab60f509e0a4c39d10cd32d0a701e4 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/all-common-options.d.ts @@ -0,0 +1,14 @@ +import { CommonPartitionOptions } from './common-partition-options.js' +import { CommonGroupsOptions } from './common-groups-options.js' +import { CommonOptions } from './common-options.js' +export type AllCommonOptions< + CustomTypeOption extends string, + AdditionalSortOptions, + CustomGroupMatchOptions, +> = CommonGroupsOptions< + CustomTypeOption, + AdditionalSortOptions, + CustomGroupMatchOptions +> & + CommonOptions & + CommonPartitionOptions diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/common-groups-options.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/common-groups-options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c9bbedb605e25ec5d51d2ba942e2053f908ee9ad --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/common-groups-options.d.ts @@ -0,0 +1,250 @@ +import { CommonOptions, RegexOption } from './common-options.js' +export interface CommonGroupsOptions< + CustomTypeOption extends string, + AdditionalSortOptions, + AdditionalCustomGroupMatchOptions, +> { + /** + * Specify the exact number of newlines required between elements of groups. + */ + newlinesInside: + | NewlinesInsideOption + /** + * @deprecated The `newlinesBetween` value is deprecated and will be removed + * in V6. + */ + | 'newlinesBetween' + /** + * Custom groups for organizing nodes. + */ + customGroups: CustomGroupsOption< + CustomTypeOption, + AdditionalSortOptions, + AdditionalCustomGroupMatchOptions + > + /** + * Defines the order and grouping of nodes. Nodes are sorted within their + * groups and groups are ordered as specified. + */ + groups: GroupsOptions + /** + * Specify the exact number of newlines required between groups. + */ + newlinesBetween: NewlinesBetweenOption +} +/** + * Configuration for custom groups with sorting and newline options. + * + * Defines custom groups that can override global sorting settings and specify + * how elements should be organized. Each custom group can have its own sorting + * algorithm, order, and newline handling behavior. + * + * @example + * + * ```ts + * const customGroups: CustomGroupsOption = [ + * { + * groupName: 'react', + * anyOf: ['react', 'react-*'], + * type: 'alphabetical', + * order: 'asc', + * newlinesInside: 1, + * }, + * { + * groupName: 'lodash', + * anyOf: ['lodash', 'lodash/*'], + * fallbackSort: { type: 'natural' }, + * }, + * ] + * ``` + * + * @template AdditionalMatchOptions - Options for matching elements to the + * custom group. + * @template AdditionalSortOptions - Additional sort options that extend the + * base configuration. + */ +export type CustomGroupsOption< + CustomTypeOption extends string, + AdditionalSortOptions, + AdditionalMatchOptions, +> = ({ + /** + * Specify the exact number of newlines required between elements of groups. + */ + newlinesInside?: NewlinesInsideOption + /** + * Regular expression pattern to match the element's name. Elements matching + * this pattern will be included in this custom group. + */ + elementNamePattern?: RegexOption + /** + * Name identifier for the custom group. Used to reference this group in the + * groups configuration array. + */ + groupName: string +} & Partial< + Pick< + CommonOptions, + 'fallbackSort' | 'order' | 'type' + > +> & + (AnyOfCustomGroup | Partial) & + Partial)[] +/** + * Configuration for groups with overriding settings. + * + * @example + * + * ```ts + * const groups = [ + * 'imports', + * { group: 'group', commentAbove: '// Component Definitions' }, + * 'components', + * ] + * ``` + */ +export type GroupWithOverridesOption< + CustomTypeOption extends string, + AdditionalSortOptions, +> = { + /** + * Specify the exact number of newlines required inside the group. + */ + newlinesInside?: NewlinesInsideOption + /** + * Name of the group or array of group names for subgroups. + */ + group: string[] | string + /** + * Text of the comment to insert above the group. The comment will be + * formatted as a line comment (// ...). + */ + commentAbove?: string +} & Partial< + Pick< + CommonOptions, + 'fallbackSort' | 'order' | 'type' + > +> & + Partial +/** + * Configuration for matching multiple patterns in custom groups. + * + * Allows a custom group to match elements based on any of several patterns, + * providing flexibility in how elements are categorized. + * + * @example + * + * ```ts + * const customGroup: AnyOfCustomGroup = { + * anyOf: ['react', 'react-*', '@react/*'], + * } + * ``` + * + * @template MatchOptions - Options for matching elements to the custom group. + */ +export interface AnyOfCustomGroup { + /** + * Regular expression pattern to match the element's name. Elements matching + * this pattern will be included in this custom group. + */ + elementNamePattern?: RegexOption + /** + * Array of patterns where matching any single pattern includes the element + * in the group. Provides OR logic for group membership. + */ + anyOf: Partial[] +} +/** + * Configuration for managing newlines between sorted elements. + * + * Controls how blank lines are handled between elements, either preserving, + * enforcing, or removing them based on the configuration. + * + * @example + * + * ```ts + * // Always require one blank line between elements + * const newlines: NewlinesBetweenOption = 1 + * ``` + * + * @example + * + * ```ts + * // Require exactly 2 blank lines + * const newlines: NewlinesBetweenOption = 2 + * ``` + */ +export type NewlinesBetweenOption = + /** + * Preserve existing newlines without modification. The plugin will not add or + * remove blank lines. + */ + | 'ignore' + /** + * Require exactly this number of blank lines between elements. Enforces + * consistent spacing with the specified line count. + */ + | number +/** + * Configuration for organizing elements into groups with optional formatting. + * + * Supports flexible group definitions including simple group names, arrays of + * group names for subgroups, and special configuration objects for controlling + * newlines and comments between groups. + * + * @example + * + * ```ts + * const groups: GroupsOptions<'imports' | 'types' | 'components'> = [ + * 'imports', + * { newlinesBetween: 1 }, + * 'types', + * { group: 'components', commentAbove: '// Components' }, // Object-based group + * ['services', 'hooks'], // Subgroup + * { newlinesBetween: 2 }, + * 'utils', + * ] + * ``` + */ +export type GroupsOptions< + CustomTypeOption extends string = string, + AdditionalSortOptions = object, +> = ( + | GroupWithOverridesOption + | GroupNewlinesBetweenOption + | string[] + | string +)[] +/** + * Configuration for controlling newlines between groups. + * + * Placed between group names in the groups array to specify how many blank + * lines should separate adjacent groups in the sorted output. + * + * @example + * + * ```ts + * const groups = [ + * 'imports', + * { newlinesBetween: 1 }, // One newline after imports + * 'types', + * ] + * ``` + */ +export interface GroupNewlinesBetweenOption { + /** + * Specifies the newline requirement between adjacent groups. This option is + * placed between group names to control their spacing. + */ + newlinesBetween: NewlinesBetweenOption +} +export type NewlinesInsideOption = + /** + * Preserve existing newlines without modification. + */ + | 'ignore' + /** + * Require exactly this number of blank lines between elements of a group. + */ + | number diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/common-options.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/common-options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8a26454daa637a5e8ad050fa4b30cde1bc80b7c8 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/common-options.d.ts @@ -0,0 +1,285 @@ +/** + * Core sorting configuration options used across all Perfectionist rules. + * + * Provides a comprehensive set of options to control how elements are sorted, + * including the sorting algorithm, character handling, locale settings, and + * sort direction. These options form the foundation for all sorting operations + * in the plugin. + * + * @example + * + * ```ts + * const options: CommonOptions = { + * type: 'natural', + * order: 'asc', + * ignoreCase: true, + * alphabet: '', + * locales: 'en-US', + * specialCharacters: 'keep', + * fallbackSort: { + * type: 'alphabetical', + * order: 'asc', + * }, + * } + * ``` + */ +export type CommonOptions< + CustomTypeOption extends string = string, + AdditionalSortOptions = object, +> = { + /** + * Secondary sorting method applied when primary comparison returns equal. + * Ensures stable and predictable sorting when elements have identical + * primary values. + */ + fallbackSort: FallbackSortOption + /** + * Specifies how to handle special characters during sorting. + * + * - 'keep': Preserve special characters in their original positions + * - 'trim': Remove leading special characters before sorting + * - 'remove': Remove all special characters before sorting. + */ + specialCharacters: SpecialCharactersOption + /** + * Locale(s) to use for locale-aware string comparison. Affects how + * characters are ordered according to language-specific rules. Can be a + * string locale code or array of locale codes for fallback behavior. + */ + locales: NonNullable + /** + * Sorting algorithm to use for ordering elements. Each algorithm has + * different behavior for handling numbers and special characters. + */ + type: CustomTypeOption + /** + * Determines whether to perform case-insensitive comparison. When true, 'a' + * and 'A' are treated as equivalent during sorting. + */ + ignoreCase: boolean + /** + * Sort direction for ordering elements. + * + * - 'asc': Ascending order (A to Z, 0 to 9) + * - 'desc': Descending order (Z to A, 9 to 0). + */ + order: OrderOption + /** + * Custom alphabet string for 'custom' sort type. Defines the exact + * character order to use when type is 'custom'. Characters not in the + * alphabet are sorted after those in the alphabet. + */ + alphabet: string +} & AdditionalSortOptions +/** + * Sorting algorithm type that determines how elements are ordered. + * + * Each algorithm has specific characteristics for handling different types of + * content and use cases. + * + * @example + * + * ```ts + * // Natural sorting for version numbers + * const type: TypeOption = 'natural' + * // Sorts: ['v1.0', 'v2.0', 'v10.0'] (not ['v1.0', 'v10.0', 'v2.0']) + * ``` + * + * @example + * + * ```ts + * // Line length for visual hierarchy + * const type: TypeOption = 'line-length' + * // Shorter lines appear before longer lines + * ``` + */ +export type TypeOption = + /** + * Sort by the subgroup order defined in `groups` arrays. Useful as a fallback + * when elements are equal under the primary comparison. + */ + | 'subgroup-order' + /** + * Traditional alphabetical sorting using locale-aware comparison. Best for + * standard text sorting where consistency is important. + */ + | 'alphabetical' + /** + * Sort by the character length of each line. Useful for creating visual + * hierarchies or grouping by complexity. + */ + | 'line-length' + /** + * Preserves the original order without sorting. Used when you want to apply + * other features (like grouping) without reordering. + */ + | 'unsorted' + /** + * Natural order sorting that handles numbers intelligently. Treats numeric + * portions as numbers rather than strings (e.g., 'item2' before 'item10'). + */ + | 'natural' + /** + * Uses a user-defined alphabet for determining sort order. Requires the + * 'alphabet' option to specify character precedence. + */ + | 'custom' +/** + * Regular expression pattern configuration for matching strings. + * + * Supports multiple formats for flexibility in pattern definition, from simple + * string patterns to complex regular expressions with flags. + * + * @example + * + * ```ts + * // Simple string pattern + * const pattern: RegexOption = '^TODO:' + * ``` + * + * @example + * + * ```ts + * // Pattern with flags + * const pattern: RegexOption = { + * pattern: '^(TODO|FIXME):', + * flags: 'i', + * } + * ``` + * + * @example + * + * ```ts + * // Multiple patterns (OR logic) + * const patterns: RegexOption = [ + * '^TODO:', + * { pattern: '^FIXME:', flags: 'i' }, + * ] + * ``` + */ +export type RegexOption = + | SingleRegexOption[] + | SingleRegexOption +/** + * Configuration for handling special characters during string comparison. + * + * Determines how non-alphanumeric characters are processed when sorting, + * allowing control over whether special characters affect sort order. + * + * @example + * + * ```ts + * // With 'remove': '_abc' and 'abc' are treated as identical + * const option: SpecialCharactersOption = 'remove' + * ``` + * + * @example + * + * ```ts + * // With 'trim': '_abc' becomes 'abc', but 'a_bc' stays 'a_bc' + * const option: SpecialCharactersOption = 'trim' + * ``` + */ +type SpecialCharactersOption = + /** + * Remove all special characters before comparison. Only alphanumeric characters + * are considered for sorting. + */ + | 'remove' + /** + * Remove leading special characters only. Useful for sorting names that may + * have underscore or other prefixes. + */ + | 'trim' + /** + * Keep all special characters in their original positions. Special characters + * participate in the sort comparison. + */ + | 'keep' +/** + * Single regular expression pattern configuration. + * + * Can be either a simple string pattern or an object with pattern and flags for + * more complex matching requirements. + * + * @internal + */ +type SingleRegexOption = + | ({ + /** + * The regular expression pattern string. Will be compiled into a RegExp for + * matching. + */ + pattern: string + /** + * Optional RegExp flags to modify pattern matching behavior. Common flags: + * 'i' (case-insensitive), 'g' (global), 'm' (multiline). + */ + flags?: string + } & AdditionalProperties) + | string +/** + * Configuration for fallback sorting when primary comparison returns equal. + * + * Provides a secondary sorting method to ensure stable and predictable ordering + * when elements have identical values according to the primary sort algorithm. + * Commonly used to sort by declaration order or another algorithm as a + * tiebreaker. + * + * @example + * + * ```ts + * const fallback: FallbackSortOption = { + * type: 'alphabetical', + * order: 'asc', + * } + * ``` + */ +type FallbackSortOption< + CustomTypeOption extends string, + AdditionalProperties, +> = { + /** + * Sorting algorithm to use as the fallback method. Applied only when the + * primary sort comparison returns equal. + */ + type: CustomTypeOption + /** + * Sort direction for the fallback comparison. If not specified, inherits + * from the primary sort order. + */ + order?: OrderOption +} & Partial +/** + * Sort direction that determines the ordering of elements. + * + * Controls whether elements are arranged from smallest to largest (ascending) + * or largest to smallest (descending) according to the chosen sorting + * algorithm. + * + * @example + * + * ```ts + * // Ascending: A → Z, 0 → 9 + * const order: OrderOption = 'asc' + * ``` + * + * @example + * + * ```ts + * // Descending: Z → A, 9 → 0 + * const order: OrderOption = 'desc' + * ``` + */ +type OrderOption = + /** + * Descending order - from largest to smallest. Letters: Z to A, Numbers: 9 to + * 0, Length: longest to shortest. + */ + | 'desc' + /** + * Ascending order - from smallest to largest. Letters: A to Z, Numbers: 0 to 9, + * Length: shortest to longest. + */ + | 'asc' +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/common-partition-options.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/common-partition-options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e4c2f004a1caaa4f6e89acb3b22078fb35ef9710 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/common-partition-options.d.ts @@ -0,0 +1,67 @@ +import { RegexOption } from './common-options.js' +/** + * Configuration for partition comments that create independent sorting + * sections. + * + * Partitions divide code into separate blocks that are sorted independently, + * preventing elements from being moved across partition boundaries. This + * preserves logical groupings and intentional code organization. + * + * @example + * + * ```ts + * // Boolean: Enable/disable partition comments + * const partitionOption: PartitionByCommentOption = true + * ``` + * + * @example + * + * ```ts + * // String pattern: Comments matching this pattern create partitions + * const partitionOption: PartitionByCommentOption = 'Section:' + * ``` + * + * @example + * + * ```ts + * // Array of patterns: Any matching pattern creates a partition + * const partitionOption: PartitionByCommentOption = ['Section:', 'Part:'] + * ``` + * + * @example + * + * ```ts + * // Object: Different patterns for block and line comments + * const partitionOption: PartitionByCommentOption = { + * block: ['Section:', 'Chapter:'], + * line: 'Part:', + * } + * ``` + */ +export type PartitionByCommentOption = + | { + /** + * Pattern(s) for block comments that create partitions. Block comments are + * multi-line comments. + */ + block?: RegexOption | boolean + /** + * Pattern(s) for line comments that create partitions. Line comments are + * single-line comments (// ...). + */ + line?: RegexOption | boolean + } + | RegexOption + | boolean +export interface CommonPartitionOptions { + /** + * Partition nodes by comment delimiters. Nodes separated by specific + * comments are sorted independently. + */ + partitionByComment: PartitionByCommentOption + /** + * Whether to partition nodes by newlines. When true, nodes separated by + * empty lines are sorted independently. + */ + partitionByNewLine: boolean +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/node-of-type.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/node-of-type.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5fcbbb3fd68f84cb3e3ff01e256141849f6dba70 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/node-of-type.d.ts @@ -0,0 +1,7 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Helper type for a node with a specific AST node type. + */ +export type NodeOfType = { + type: Type +} & TSESTree.Node diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/scoped-regex-option.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/scoped-regex-option.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9bf1bbc91877efcb9589008f759a8831b12ace2d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/scoped-regex-option.d.ts @@ -0,0 +1,4 @@ +import { RegexOption } from './common-options.js' +export type Scope = (typeof regexScopes)[number] +export type ScopedRegexOption = RegexOption +export declare let regexScopes: readonly ['shallow', 'deep'] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/scoped-regex-option.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/scoped-regex-option.js new file mode 100644 index 0000000000000000000000000000000000000000..b8916759d3e89512da0ec0b6868425ea80d2c5f5 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/scoped-regex-option.js @@ -0,0 +1,2 @@ +var regexScopes = ['shallow', 'deep'] +export { regexScopes } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/sorting-node.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/sorting-node.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e49473f63fe06a9ac60cee19656d9f31aa9adc0f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/types/sorting-node.d.ts @@ -0,0 +1,106 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Core data structure representing a sortable element in the AST. + * + * This interface wraps AST nodes with metadata required for sorting operations. + * Every element that needs to be sorted (imports, properties, class members, + * etc.) is transformed into a SortingNode, providing a uniform interface for + * all sorting algorithms across the plugin. + * + * The SortingNode abstraction allows the sorting logic to be decoupled from the + * specific AST node types, making the sorting algorithms reusable across + * different rule implementations. + * + * @template Node - Type of the underlying AST node, defaults to any + * TSESTree.Node. + */ +export interface SortingNode { + /** + * Decorators associated with this node that are not directly accessible via + * the AST node's own `decorators` property. + * + * Used in contexts where decorators are tracked separately from their + * decorated node. When provided, these decorators override the node's own + * `decorators` in range calculations, ensuring they are included when the + * node is moved during sorting fixes. + */ + implicitDecorators?: TSESTree.Decorator[] + /** + * Indicates whether a safety semicolon should be added when the node is + * moved inline. + * + * Used to prevent Automatic Semicolon Insertion (ASI) issues when + * reordering statements. For example, when moving a statement that starts + * with `[` or `(` after another statement without a semicolon, a safety + * semicolon is added to prevent the two statements from being incorrectly + * interpreted as one. + */ + addSafetySemicolonWhenInline?: boolean + /** + * Whether ESLint rules are disabled for this node via comments. + * + * When true, the node maintains its original position during sorting to + * respect explicit disable directives like `eslint-disable-line` or + * `eslint-disable-next-line`. This ensures that intentionally unsorted + * elements remain in their specified positions. + */ + isEslintDisabled: boolean + /** + * Identifier for the partition (independent sorting section) this node + * belongs to. + * + * Partitions divide code into separate blocks that are sorted + * independently. Nodes with different partition IDs are never moved across + * partition boundaries, preserving logical code organization. Common + * partition boundaries include: + * + * - Blank lines (when partitionByNewLine is enabled) + * - Special comments (when partitionByComment is configured) + * - Different code sections (e.g., imports vs code). + */ + partitionId: number + /** + * The group identifier this node belongs to within the sorting + * configuration. + * + * Groups determine the high-level ordering of elements. Nodes are first + * organized by group (e.g., 'external' imports before 'internal' imports), + * then sorted within each group according to the sorting algorithm. The + * group can be a predefined group, custom group, or 'unknown' for + * uncategorized elements. + */ + group: string + /** + * The string representation used for sorting comparisons. + * + * This is the primary value used when comparing nodes during sorting. The + * exact content depends on the node type and rule implementation: + * + * - For imports: the module specifier ('react', './utils', etc.) + * - For properties: the property key name + * - For class members: the member name + * - For union types: the type literal or identifier. + * + * The sorting algorithm uses this value for alphabetical, natural, or + * custom sorting comparisons. + */ + name: string + /** + * The size metric used for line-length sorting. + * + * Typically represents the character count of the node's source code, + * excluding trailing punctuation like commas or semicolons. Used when the + * sort type is 'line-length' to order elements from shortest to longest (or + * vice versa based on order setting). + */ + size: number + /** + * The underlying AST node from the TypeScript ESLint parser. + * + * Preserves the complete AST node information, allowing access to location + * data, parent references, and type-specific properties. This is used when + * generating fixes to know exactly what text to move and where it's located + * in the source code. + */ + node: Node +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/alphabet.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/alphabet.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a1a2e08ea2603f20267f838b1768fdf6ff6a8598 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/alphabet.d.ts @@ -0,0 +1,219 @@ +/** + * Manages a customizable alphabet for sorting operations. + * + * Provides methods to generate, modify, and sort alphabets based on various + * criteria including Unicode ranges, case prioritization, and locale-specific + * ordering. Used by the 'custom' sort type to define character precedence. + * + * The class supports: + * + * - Generating alphabets from strings or Unicode ranges + * - Case prioritization and manipulation + * - Character positioning and removal + * - Multiple sorting strategies (natural, locale, char code). + * + * @example + * + * ```ts + * // Create a custom alphabet with specific character order + * const alphabet = Alphabet.generateFrom('aAbBcC') + * .prioritizeCase('uppercase') + * .getCharacters() + * // Returns: 'AaBbCc' + * ``` + */ +export declare class Alphabet { + private characters + private constructor() + /** + * Generates an alphabet from the given characters. + * + * @param values - The characters to generate the alphabet from. + * @returns - The wrapped alphabet. + */ + static generateFrom(values: string[] | string): Alphabet + /** + * Generates an alphabet containing relevant characters from the Unicode + * standard. Contains the Unicode planes 0 and 1. + * + * @returns - The generated alphabet. + */ + static generateRecommendedAlphabet(): Alphabet + /** + * Generates an alphabet containing all characters from the Unicode standard + * except for irrelevant Unicode planes. Contains the Unicode planes 0, 1, 2 + * and 3. + * + * @returns - The generated alphabet. + */ + static generateCompleteAlphabet(): Alphabet + private static getCharactersWithCase + /** + * Generates an alphabet containing relevant characters from the Unicode + * standard. + * + * @param maxCodePoint - The maximum code point to generate the alphabet to. + * @returns - The generated alphabet. + */ + private static generateAlphabetToRange + /** + * For each character with a lower and upper case, permutes the two cases so + * that the alphabet is ordered by the case priority entered. + * + * @example + * + * ```ts + * Alphabet.generateFrom('aAbBcdCD').prioritizeCase('uppercase') // Returns 'AaBbCDcd'. + * ``` + * + * @param casePriority - The case to prioritize. + * @returns - The same alphabet instance with the cases prioritized. + */ + prioritizeCase(casePriority: 'lowercase' | 'uppercase'): this + /** + * Adds specific characters to the end of the alphabet. + * + * @example + * + * ```ts + * Alphabet.generateFrom('ab').pushCharacters('cd') + * // Returns 'abcd' + * ``` + * + * @param values - The characters to push to the alphabet. + * @returns - The same alphabet instance without the specified characters. + */ + pushCharacters(values: string[] | string): this + /** + * Permutes characters with cases so that all characters with the entered + * case are put before the other characters. + * + * @param caseToComeFirst - The case to put before the other characters. + * @returns - The same alphabet instance with all characters with case + * before all the characters with the other case. + */ + placeAllWithCaseBeforeAllWithOtherCase( + caseToComeFirst: 'uppercase' | 'lowercase', + ): this + /** + * Places a specific character right before another character in the + * alphabet. + * + * @example + * + * ```ts + * Alphabet.generateFrom('ab-cd/').placeCharacterBefore({ + * characterBefore: '/', + * characterAfter: '-', + * }) + * // Returns 'ab/-cd' + * ``` + * + * @param params - The parameters for the operation. + * @param params.characterBefore - The character to come before + * characterAfter. + * @param params.characterAfter - The target character. + * @returns - The same alphabet instance with the specific character + * prioritized. + */ + placeCharacterBefore({ + characterBefore, + characterAfter, + }: { + characterBefore: string + characterAfter: string + }): this + /** + * Places a specific character right after another character in the + * alphabet. + * + * @example + * + * ```ts + * Alphabet.generateFrom('ab-cd/').placeCharacterAfter({ + * characterBefore: '/', + * characterAfter: '-', + * }) + * // Returns 'abcd/-' + * ``` + * + * @param params - The parameters for the operation. + * @param params.characterBefore - The target character. + * @param params.characterAfter - The character to come after + * characterBefore. + * @returns - The same alphabet instance with the specific character + * prioritized. + */ + placeCharacterAfter({ + characterBefore, + characterAfter, + }: { + characterBefore: string + characterAfter: string + }): this + /** + * Removes specific characters from the alphabet by their range. + * + * @param range - The Unicode range to remove characters from. + * @param range.start - The starting Unicode codepoint. + * @param range.end - The ending Unicode codepoint. + * @returns - The same alphabet instance without the characters from the + * specified range. + */ + removeUnicodeRange({ start, end }: { start: number; end: number }): this + /** + * Sorts the alphabet by the sorting function provided. + * + * @param sortingFunction - The sorting function to use. + * @returns - The same alphabet instance sorted by the sorting function + * provided. + */ + sortBy( + sortingFunction: (characterA: string, characterB: string) => number, + ): this + /** + * Sorts the alphabet by the natural order of the characters using + * `natural-orderby`. + * + * @param locale - The locale to use for sorting. + * @returns - The same alphabet instance sorted by the natural order of the + * characters. + */ + sortByNaturalSort(locale?: string): this + /** + * Removes specific characters from the alphabet. + * + * @example + * + * ```ts + * Alphabet.generateFrom('abcd').removeCharacters('dcc') + * // Returns 'ab' + * ``` + * + * @param values - The characters to remove from the alphabet. + * @returns - The same alphabet instance without the specified characters. + */ + removeCharacters(values: string[] | string): this + /** + * Sorts the alphabet by the character code point. + * + * @returns - The same alphabet instance sorted by the character code point. + */ + sortByCharCodeAt(): this + /** + * Sorts the alphabet by the locale order of the characters. + * + * @param locales - The locales to use for sorting. + * @returns - The same alphabet instance sorted by the locale order of the + * characters. + */ + sortByLocaleCompare(locales?: Intl.LocalesArgument): this + /** + * Retrieves the characters from the alphabet. + * + * @returns The characters from the alphabet. + */ + getCharacters(): string + private placeCharacterBeforeOrAfter + private getCharactersWithCase +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/alphabet.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/alphabet.js new file mode 100644 index 0000000000000000000000000000000000000000..7e4f265e4f4e804d2238f537ec07ad4ffc64b822 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/alphabet.js @@ -0,0 +1,397 @@ +import { convertBooleanToSign } from './convert-boolean-to-sign.js' +import { compare } from 'natural-orderby' +/** + * Manages a customizable alphabet for sorting operations. + * + * Provides methods to generate, modify, and sort alphabets based on various + * criteria including Unicode ranges, case prioritization, and locale-specific + * ordering. Used by the 'custom' sort type to define character precedence. + * + * The class supports: + * + * - Generating alphabets from strings or Unicode ranges + * - Case prioritization and manipulation + * - Character positioning and removal + * - Multiple sorting strategies (natural, locale, char code). + * + * @example + * + * ```ts + * // Create a custom alphabet with specific character order + * const alphabet = Alphabet.generateFrom('aAbBcC') + * .prioritizeCase('uppercase') + * .getCharacters() + * // Returns: 'AaBbCc' + * ``` + */ +var Alphabet = class Alphabet { + characters = [] + constructor(characters) { + this.characters = characters + } + /** + * Generates an alphabet from the given characters. + * + * @param values - The characters to generate the alphabet from. + * @returns - The wrapped alphabet. + */ + static generateFrom(values) { + let arrayValues = typeof values === 'string' ? [...values] : values + let uniqueValues = new Set(arrayValues) + if (arrayValues.length !== uniqueValues.size) { + throw new Error('The alphabet must not contain repeated characters') + } + if (arrayValues.some(value => value.length !== 1)) { + throw new Error('The alphabet must contain single characters') + } + return new Alphabet( + arrayValues.map(value => + Alphabet.getCharactersWithCase(value.codePointAt(0)), + ), + ) + } + /** + * Generates an alphabet containing relevant characters from the Unicode + * standard. Contains the Unicode planes 0 and 1. + * + * @returns - The generated alphabet. + */ + static generateRecommendedAlphabet() { + return Alphabet.generateAlphabetToRange(131072) + } + /** + * Generates an alphabet containing all characters from the Unicode standard + * except for irrelevant Unicode planes. Contains the Unicode planes 0, 1, 2 + * and 3. + * + * @returns - The generated alphabet. + */ + static generateCompleteAlphabet() { + return Alphabet.generateAlphabetToRange(262144) + } + static getCharactersWithCase(codePoint) { + let character = String.fromCodePoint(codePoint) + let lowercaseCharacter = character.toLowerCase() + let uppercaseCharacter = character.toUpperCase() + return { + value: character, + codePoint, + ...(lowercaseCharacter !== character && { + lowercaseCharacterCodePoint: lowercaseCharacter.codePointAt(0), + }), + ...(uppercaseCharacter !== character && { + uppercaseCharacterCodePoint: uppercaseCharacter.codePointAt(0), + }), + } + } + /** + * Generates an alphabet containing relevant characters from the Unicode + * standard. + * + * @param maxCodePoint - The maximum code point to generate the alphabet to. + * @returns - The generated alphabet. + */ + static generateAlphabetToRange(maxCodePoint) { + let totalCharacters = Array.from({ length: maxCodePoint }, (_, i) => + Alphabet.getCharactersWithCase(i), + ) + return new Alphabet(totalCharacters) + } + /** + * For each character with a lower and upper case, permutes the two cases so + * that the alphabet is ordered by the case priority entered. + * + * @example + * + * ```ts + * Alphabet.generateFrom('aAbBcdCD').prioritizeCase('uppercase') // Returns 'AaBbCDcd'. + * ``` + * + * @param casePriority - The case to prioritize. + * @returns - The same alphabet instance with the cases prioritized. + */ + prioritizeCase(casePriority) { + let charactersWithCase = this.getCharactersWithCase() + let parsedIndexes = /* @__PURE__ */ new Set() + let indexByCodePoints = this.characters.reduce( + (indexByCodePoint, character, index) => { + indexByCodePoint[character.codePoint] = index + return indexByCodePoint + }, + {}, + ) + for (let { character, index } of charactersWithCase) { + if (parsedIndexes.has(index)) { + continue + } + parsedIndexes.add(index) + let otherCharacterIndex = + indexByCodePoints[ + character.uppercaseCharacterCodePoint ?? + character.lowercaseCharacterCodePoint + ] + if (otherCharacterIndex === void 0) { + continue + } + parsedIndexes.add(otherCharacterIndex) + if (!character.uppercaseCharacterCodePoint) { + if ( + (casePriority === 'uppercase' && index < otherCharacterIndex) || + (casePriority === 'lowercase' && index > otherCharacterIndex) + ) { + continue + } + } else if ( + (casePriority === 'uppercase' && index > otherCharacterIndex) || + (casePriority === 'lowercase' && index < otherCharacterIndex) + ) { + continue + } + this.characters[index] = this.characters[otherCharacterIndex] + this.characters[otherCharacterIndex] = character + } + return this + } + /** + * Adds specific characters to the end of the alphabet. + * + * @example + * + * ```ts + * Alphabet.generateFrom('ab').pushCharacters('cd') + * // Returns 'abcd' + * ``` + * + * @param values - The characters to push to the alphabet. + * @returns - The same alphabet instance without the specified characters. + */ + pushCharacters(values) { + let arrayValues = typeof values === 'string' ? [...values] : values + let valuesSet = new Set(arrayValues) + let valuesAlreadyExisting = this.characters.filter(({ value }) => + valuesSet.has(value), + ) + if (valuesAlreadyExisting.length > 0) { + throw new Error( + `The alphabet already contains the characters ${valuesAlreadyExisting + .slice(0, 5) + .map(({ value }) => value) + .join(', ')}`, + ) + } + if (arrayValues.some(value => value.length !== 1)) { + throw new Error('Only single characters may be pushed') + } + this.characters.push( + ...[...valuesSet].map(value => + Alphabet.getCharactersWithCase(value.codePointAt(0)), + ), + ) + return this + } + /** + * Permutes characters with cases so that all characters with the entered case + * are put before the other characters. + * + * @param caseToComeFirst - The case to put before the other characters. + * @returns - The same alphabet instance with all characters with case before + * all the characters with the other case. + */ + placeAllWithCaseBeforeAllWithOtherCase(caseToComeFirst) { + let otherCaseKey = + caseToComeFirst === 'uppercase' ? + 'uppercaseCharacterCodePoint' + : 'lowercaseCharacterCodePoint' + let keep = [] + let move = [] + for (let character of this.characters) { + ;(character[otherCaseKey] === void 0 ? keep : move).push(character) + } + this.characters = [...keep, ...move] + return this + } + /** + * Places a specific character right before another character in the alphabet. + * + * @example + * + * ```ts + * Alphabet.generateFrom('ab-cd/').placeCharacterBefore({ + * characterBefore: '/', + * characterAfter: '-', + * }) + * // Returns 'ab/-cd' + * ``` + * + * @param params - The parameters for the operation. + * @param params.characterBefore - The character to come before + * characterAfter. + * @param params.characterAfter - The target character. + * @returns - The same alphabet instance with the specific character + * prioritized. + */ + placeCharacterBefore({ characterBefore, characterAfter }) { + return this.placeCharacterBeforeOrAfter({ + characterBefore, + characterAfter, + type: 'before', + }) + } + /** + * Places a specific character right after another character in the alphabet. + * + * @example + * + * ```ts + * Alphabet.generateFrom('ab-cd/').placeCharacterAfter({ + * characterBefore: '/', + * characterAfter: '-', + * }) + * // Returns 'abcd/-' + * ``` + * + * @param params - The parameters for the operation. + * @param params.characterBefore - The target character. + * @param params.characterAfter - The character to come after characterBefore. + * @returns - The same alphabet instance with the specific character + * prioritized. + */ + placeCharacterAfter({ characterBefore, characterAfter }) { + return this.placeCharacterBeforeOrAfter({ + characterBefore, + characterAfter, + type: 'after', + }) + } + /** + * Removes specific characters from the alphabet by their range. + * + * @param range - The Unicode range to remove characters from. + * @param range.start - The starting Unicode codepoint. + * @param range.end - The ending Unicode codepoint. + * @returns - The same alphabet instance without the characters from the + * specified range. + */ + removeUnicodeRange({ start, end }) { + this.characters = this.characters.filter( + ({ codePoint }) => codePoint < start || codePoint > end, + ) + return this + } + /** + * Sorts the alphabet by the sorting function provided. + * + * @param sortingFunction - The sorting function to use. + * @returns - The same alphabet instance sorted by the sorting function + * provided. + */ + sortBy(sortingFunction) { + this.characters.sort((a, b) => sortingFunction(a.value, b.value)) + return this + } + /** + * Sorts the alphabet by the natural order of the characters using + * `natural-orderby`. + * + * @param locale - The locale to use for sorting. + * @returns - The same alphabet instance sorted by the natural order of the + * characters. + */ + sortByNaturalSort(locale) { + let naturalCompare = compare({ locale }) + return this.sortBy((a, b) => naturalCompare(a, b)) + } + /** + * Removes specific characters from the alphabet. + * + * @example + * + * ```ts + * Alphabet.generateFrom('abcd').removeCharacters('dcc') + * // Returns 'ab' + * ``` + * + * @param values - The characters to remove from the alphabet. + * @returns - The same alphabet instance without the specified characters. + */ + removeCharacters(values) { + this.characters = this.characters.filter( + ({ value }) => !values.includes(value), + ) + return this + } + /** + * Sorts the alphabet by the character code point. + * + * @returns - The same alphabet instance sorted by the character code point. + */ + sortByCharCodeAt() { + return this.sortBy((a, b) => + convertBooleanToSign(a.charCodeAt(0) > b.charCodeAt(0)), + ) + } + /** + * Sorts the alphabet by the locale order of the characters. + * + * @param locales - The locales to use for sorting. + * @returns - The same alphabet instance sorted by the locale order of the + * characters. + */ + sortByLocaleCompare(locales) { + return this.sortBy((a, b) => a.localeCompare(b, locales)) + } + /** + * Retrieves the characters from the alphabet. + * + * @returns The characters from the alphabet. + */ + getCharacters() { + return this.characters.map(({ value }) => value).join('') + } + placeCharacterBeforeOrAfter({ characterBefore, characterAfter, type }) { + let indexOfCharacterAfter = this.characters.findIndex( + ({ value }) => value === characterAfter, + ) + if (indexOfCharacterAfter === -1) { + throw new Error(`Character ${characterAfter} not found in alphabet`) + } + let indexOfCharacterBefore = this.characters.findIndex( + ({ value }) => value === characterBefore, + ) + if (indexOfCharacterBefore === -1) { + throw new Error(`Character ${characterBefore} not found in alphabet`) + } + if (indexOfCharacterBefore <= indexOfCharacterAfter) { + return this + } + this.characters.splice( + type === 'before' ? indexOfCharacterAfter : indexOfCharacterBefore + 1, + 0, + this.characters[ + type === 'before' ? indexOfCharacterBefore : indexOfCharacterAfter + ], + ) + this.characters.splice( + type === 'before' ? indexOfCharacterBefore + 1 : indexOfCharacterAfter, + 1, + ) + return this + } + getCharactersWithCase() { + return this.characters + .map((character, index) => { + if ( + !character.uppercaseCharacterCodePoint && + !character.lowercaseCharacterCodePoint + ) { + return null + } + return { + character, + index, + } + }) + .filter(element => element !== null) + } +} +export { Alphabet } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/assert-is-never.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/assert-is-never.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3e6cfcfd669d4ed5e58113e67d790b6bafbedd23 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/assert-is-never.d.ts @@ -0,0 +1,7 @@ +/** + * Assert that the given member is of type `never`. This is useful for + * exhaustive checks in switch statements or conditional logic. + * + * @param _member - The member to check, which should be of type `never`. + */ +export declare function assertIsNever(_member: never): void diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/assert-is-never.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/assert-is-never.js new file mode 100644 index 0000000000000000000000000000000000000000..6d93ac98483df3ed10aa314c3e5e1f7ef2441a14 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/assert-is-never.js @@ -0,0 +1,8 @@ +/** + * Assert that the given member is of type `never`. This is useful for + * exhaustive checks in switch statements or conditional logic. + * + * @param _member - The member to check, which should be of type `never`. + */ +function assertIsNever(_member) {} +export { assertIsNever } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/build-ast-listeners.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/build-ast-listeners.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6705e7d20eb3aed646cdcb409a35e5ca86557673 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/build-ast-listeners.d.ts @@ -0,0 +1,46 @@ +import { RuleContext } from '@typescript-eslint/utils/ts-eslint' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +import { NodeOfType } from '../types/node-of-type.js' +type Sorter< + MessageId extends string, + Options extends BaseOptions[], + NodeTypes extends AST_NODE_TYPES, +> = (parameters: { + context: Readonly> + matchedAstSelectors: ReadonlySet + node: NodeOfType +}) => void +type AstListeners = Record< + string, + (node: NodeOfType) => void +> +interface BaseOptions { + useConfigurationIf?: { + matchesAstSelector?: string + } +} +/** + * Builds the AST listeners for the rule based on the provided node types, + * context, and sorter function. + * + * @param params - The parameters object. + * @param params.nodeTypes - The AST node types to listen for. + * @param params.context - The rule context. + * @param params.sorter - The function that sorts the nodes based on the + * provided parameters. + * @returns An object containing the AST listeners for the specified node types. + */ +export declare function buildAstListeners< + MessageId extends string, + Options extends BaseOptions[], + NodeTypes extends AST_NODE_TYPES, +>({ + nodeTypes, + context, + sorter, +}: { + sorter: Sorter> + context: Readonly> + nodeTypes: NodeTypes[] +}): AstListeners +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/build-ast-listeners.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/build-ast-listeners.js new file mode 100644 index 0000000000000000000000000000000000000000..fb5f8d06f5efd6a33819eaf00264a6663e6288dc --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/build-ast-listeners.js @@ -0,0 +1,67 @@ +/** + * Builds the AST listeners for the rule based on the provided node types, + * context, and sorter function. + * + * @param params - The parameters object. + * @param params.nodeTypes - The AST node types to listen for. + * @param params.context - The rule context. + * @param params.sorter - The function that sorts the nodes based on the + * provided parameters. + * @returns An object containing the AST listeners for the specified node types. + */ +function buildAstListeners({ nodeTypes, context, sorter }) { + let emptyMatchedAstSelectors = /* @__PURE__ */ new Set() + let matchedAstSelectorsByNode = /* @__PURE__ */ new WeakMap() + let allAstSelectorMatchers = [ + ...new Set( + context.options + .map(option => option.useConfigurationIf?.matchesAstSelector) + .filter(matchesAstSelector => matchesAstSelector !== void 0), + ), + ].map(astSelector => [ + astSelector, + buildMatchedAstSelectorsCollector({ + matchedAstSelectorsByNode, + astSelector, + nodeTypes, + }), + ]) + return { + ...Object.fromEntries(allAstSelectorMatchers), + ...Object.fromEntries(nodeTypes.map(buildNodeTypeExitListener)), + } + function buildNodeTypeExitListener(nodeType) { + return [ + `${nodeType}:exit`, + node => + sorter({ + matchedAstSelectors: + matchedAstSelectorsByNode.get(node) ?? emptyMatchedAstSelectors, + context, + node, + }), + ] + } +} +function buildMatchedAstSelectorsCollector({ + matchedAstSelectorsByNode, + astSelector, + nodeTypes, +}) { + return collectMatchedAstSelectors + function collectMatchedAstSelectors(node) { + if (!isNodeOfType(node)) { + return + } + let matchedAstSelectors = matchedAstSelectorsByNode.get(node) + if (!matchedAstSelectors) { + matchedAstSelectors = /* @__PURE__ */ new Set() + matchedAstSelectorsByNode.set(node, matchedAstSelectors) + } + matchedAstSelectors.add(astSelector) + } + function isNodeOfType(node) { + return nodeTypes.includes(node.type) + } +} +export { buildAstListeners } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/build-options-by-group-index-computer.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/build-options-by-group-index-computer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..922a004e1825454b48454a6ddb627a0d090ee13b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/build-options-by-group-index-computer.d.ts @@ -0,0 +1,31 @@ +import { OptionsByGroupIndexComputer } from './sort-nodes-by-groups.js' +import { CommonGroupsOptions } from '../types/common-groups-options.js' +import { CommonOptions } from '../types/common-options.js' +type Options = Pick< + CommonGroupsOptions, + 'customGroups' | 'groups' +> & + CommonOptions +/** + * Creates a function that retrieves overridden options for a specific group + * index. + * + * Returns a closure that captures the options and provides a convenient way to + * get overridden options for any group index. This is used in sorting + * algorithms that need to apply different sorting rules to different groups. + * + * @example + * + * ```ts + * const getOverriddenOptions = buildOptionsByGroupIndexComputer(options) + * const group1Options = getOverriddenOptions(0) + * const group2Options = getOverriddenOptions(1) + * ``` + * + * @param options - Base sorting options with group configuration. + * @returns Function that takes a group index and returns overridden options. + */ +export declare function buildOptionsByGroupIndexComputer( + options: T, +): OptionsByGroupIndexComputer +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/build-options-by-group-index-computer.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/build-options-by-group-index-computer.js new file mode 100644 index 0000000000000000000000000000000000000000..41803fe8d54b6d9b2be7d7b7ffaa01ec8c0b1d02 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/build-options-by-group-index-computer.js @@ -0,0 +1,24 @@ +import { computeOverriddenOptionsByGroupIndex } from './compute-overridden-options-by-group-index.js' +/** + * Creates a function that retrieves overridden options for a specific group + * index. + * + * Returns a closure that captures the options and provides a convenient way to + * get overridden options for any group index. This is used in sorting + * algorithms that need to apply different sorting rules to different groups. + * + * @example + * + * ```ts + * const getOverriddenOptions = buildOptionsByGroupIndexComputer(options) + * const group1Options = getOverriddenOptions(0) + * const group2Options = getOverriddenOptions(1) + * ``` + * + * @param options - Base sorting options with group configuration. + * @returns Function that takes a group index and returns overridden options. + */ +function buildOptionsByGroupIndexComputer(options) { + return groupIndex => computeOverriddenOptionsByGroupIndex(options, groupIndex) +} +export { buildOptionsByGroupIndexComputer } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/build-sorting-node-by-node-map.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/build-sorting-node-by-node-map.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e3c655cf036f869963c6725b4f0245291a2c3e2e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/build-sorting-node-by-node-map.d.ts @@ -0,0 +1,10 @@ +import { SortingNode } from '../types/sorting-node.js' +/** + * Builds a map from nodes to their corresponding sorting nodes. + * + * @param sortingNodes - An array of sorting nodes. + * @returns A map where each key is a node and the value is its sorting node. + */ +export declare function buildSortingNodeByNodeMap< + T extends Pick, +>(sortingNodes: T[]): Map diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/build-sorting-node-by-node-map.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/build-sorting-node-by-node-map.js new file mode 100644 index 0000000000000000000000000000000000000000..ad8f1b3cffe2549fab558bcc5aabd5af67a90b66 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/build-sorting-node-by-node-map.js @@ -0,0 +1,14 @@ +/** + * Builds a map from nodes to their corresponding sorting nodes. + * + * @param sortingNodes - An array of sorting nodes. + * @returns A map where each key is a node and the value is its sorting node. + */ +function buildSortingNodeByNodeMap(sortingNodes) { + let sortingNodeByNode = /* @__PURE__ */ new Map() + for (let sortingNode of sortingNodes) { + sortingNodeByNode.set(sortingNode.node, sortingNode) + } + return sortingNodeByNode +} +export { buildSortingNodeByNodeMap } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/build-line-length-comparator.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/build-line-length-comparator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c4dbb1f46b7a039f4fa0ad3ae5786ed34453694 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/build-line-length-comparator.d.ts @@ -0,0 +1,13 @@ +import { Comparator } from './default-comparator-by-options-computer.js' +import { CommonOptions } from '../../types/common-options.js' +import { SortingNode } from '../../types/sorting-node.js' +/** + * Creates a comparator function that sorts nodes by their line length. + * + * @param options - Options containing the sort order. + * @param options.order - The order direction ('asc' or 'desc'). + * @returns A comparator function that compares two sorting nodes by their size. + */ +export declare function buildLineLengthComparator({ + order, +}: Pick): Comparator diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/build-line-length-comparator.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/build-line-length-comparator.js new file mode 100644 index 0000000000000000000000000000000000000000..2dfb9d713763096d661b585c0411681d82914f82 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/build-line-length-comparator.js @@ -0,0 +1,15 @@ +import { computeOrderedValue } from './compute-ordered-value.js' +/** + * Creates a comparator function that sorts nodes by their line length. + * + * @param options - Options containing the sort order. + * @param options.order - The order direction ('asc' or 'desc'). + * @returns A comparator function that compares two sorting nodes by their size. + */ +function buildLineLengthComparator({ order }) { + return (a, b) => { + let result = a.size - b.size + return computeOrderedValue(result, order) + } +} +export { buildLineLengthComparator } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/build-string-formatter.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/build-string-formatter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2bbdee990fd2207a30ae5749d06682f74d8c4d18 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/build-string-formatter.d.ts @@ -0,0 +1,28 @@ +import { CommonOptions } from '../../types/common-options.js' +/** + * Creates a function that formats strings for comparison. + * + * Applies transformations based on the provided options: + * + * - Case normalization (lowercase if ignoreCase is true) + * - Special character handling (keep, trim, or remove) + * - Whitespace removal (always applied). + * + * @param params - Parameters for string formatting. + * @param params.ignoreCase - Whether to convert strings to lowercase. + * @param params.specialCharacters - How to handle special characters: + * + * - 'keep': Keep all characters as-is + * - 'trim': Remove leading special characters + * - 'remove': Remove all special characters. + * + * @returns Function that formats a string for comparison. + * @throws {UnreachableCaseError} If an unknown special characters option is + * specified. + */ +export declare function buildStringFormatter({ + specialCharacters, + ignoreCase, +}: Pick): ( + value: string, +) => string diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/build-string-formatter.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/build-string-formatter.js new file mode 100644 index 0000000000000000000000000000000000000000..58b067dcc57a164e55b2cf1c826736829db0d950 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/build-string-formatter.js @@ -0,0 +1,51 @@ +import { UnreachableCaseError } from '../unreachable-case-error.js' +/** + * Creates a function that formats strings for comparison. + * + * Applies transformations based on the provided options: + * + * - Case normalization (lowercase if ignoreCase is true) + * - Special character handling (keep, trim, or remove) + * - Whitespace removal (always applied). + * + * @param params - Parameters for string formatting. + * @param params.ignoreCase - Whether to convert strings to lowercase. + * @param params.specialCharacters - How to handle special characters: + * + * - 'keep': Keep all characters as-is + * - 'trim': Remove leading special characters + * - 'remove': Remove all special characters. + * + * @returns Function that formats a string for comparison. + * @throws {UnreachableCaseError} If an unknown special characters option is + * specified. + */ +function buildStringFormatter({ specialCharacters, ignoreCase }) { + return value => { + let valueToCompare = value + if (ignoreCase) { + valueToCompare = valueToCompare.toLowerCase() + } + switch (specialCharacters) { + case 'remove': + valueToCompare = valueToCompare.replaceAll( + /[^a-z\u{C0}-\u{24F}\u{1E00}-\u{1EFF}]+/giu, + '', + ) + break + case 'trim': + valueToCompare = valueToCompare.replaceAll( + /^[^a-z\u{C0}-\u{24F}\u{1E00}-\u{1EFF}]+/giu, + '', + ) + break + case 'keep': + break + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(specialCharacters) + } + return valueToCompare.replaceAll(/\s/gu, '') + } +} +export { buildStringFormatter } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/build-subgroup-order-comparator.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/build-subgroup-order-comparator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c95649bab640b6ab156a53eb50b7ffe5787304e3 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/build-subgroup-order-comparator.d.ts @@ -0,0 +1,10 @@ +import { Comparator } from './default-comparator-by-options-computer.js' +import { AllCommonOptions } from '../../types/all-common-options.js' +import { SortingNode } from '../../types/sorting-node.js' +export declare function buildSubgroupOrderComparator({ + groups, + order, +}: Pick< + AllCommonOptions, + 'groups' | 'order' +>): Comparator diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/build-subgroup-order-comparator.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/build-subgroup-order-comparator.js new file mode 100644 index 0000000000000000000000000000000000000000..6388820e060f3fe3765635c98004fa904cc3bf6a --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/build-subgroup-order-comparator.js @@ -0,0 +1,51 @@ +import { isGroupWithOverridesOption } from '../is-group-with-overrides-option.js' +import { isNewlinesBetweenOption } from '../is-newlines-between-option.js' +import { UnreachableCaseError } from '../unreachable-case-error.js' +import { computeOrderedValue } from './compute-ordered-value.js' +function buildSubgroupOrderComparator({ groups, order }) { + return (a, b) => { + let subgroupContainingA = computeSubgroupContainingNode(a, groups) + let subgroupContainingB = computeSubgroupContainingNode(b, groups) + if ( + !subgroupContainingA || + !subgroupContainingB || + subgroupContainingA !== subgroupContainingB + ) { + return 0 + } + let result = + subgroupContainingA.indexOf(a.group) - + subgroupContainingB.indexOf(b.group) + return computeOrderedValue(result, order) + } +} +function computeSubgroupContainingNode(sortingNode, groups) { + for (let group of groups) { + if (isNewlinesBetweenOption(group)) { + continue + } + if (typeof group === 'string' || Array.isArray(group)) { + if (doesStringSubgroupContainsNode(sortingNode, group)) { + return group + } + continue + } + /* v8 ignore else -- @preserve Exhaustive guard for unsupported group option. */ + if (isGroupWithOverridesOption(group)) { + if (doesStringSubgroupContainsNode(sortingNode, group.group)) { + return group.group + } + continue + } + /* v8 ignore next -- @preserve Exhaustive guard for unsupported group option. */ + throw new UnreachableCaseError(group) + } + return null +} +function doesStringSubgroupContainsNode(sortingNode, subgroup) { + if (typeof subgroup === 'string') { + return false + } + return subgroup.includes(sortingNode.group) +} +export { buildSubgroupOrderComparator } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compare-alphabetically.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compare-alphabetically.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..59f2081e8c1aba9511d9ada3ce674edbc9ea049a --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compare-alphabetically.d.ts @@ -0,0 +1,29 @@ +import { CommonOptions } from '../../types/common-options.js' +/** + * Compares two strings alphabetically using locale-aware comparison. + * + * Applies string formatting based on options (case sensitivity, special + * characters handling) before performing the comparison. + * + * @param a - The first string to compare. + * @param b - The second string to compare. + * @param options - Comparison options. + * @param options.specialCharacters - How to handle special characters. + * @param options.ignoreCase - Whether to ignore case differences. + * @param options.locales - The locale(s) to use for comparison. + * @param options.order - The order direction ('asc' or 'desc'). + * @returns A negative number if a < b, positive if a > b, or 0 if equal. + */ +export declare function compareAlphabetically( + a: string, + b: string, + { + specialCharacters, + ignoreCase, + locales, + order, + }: Pick< + CommonOptions, + 'specialCharacters' | 'ignoreCase' | 'locales' | 'order' + >, +): number diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compare-alphabetically.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compare-alphabetically.js new file mode 100644 index 0000000000000000000000000000000000000000..c59a6d0247ad5a6a4e4f19845cd08a298d119b38 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compare-alphabetically.js @@ -0,0 +1,30 @@ +import { computeOrderedValue } from './compute-ordered-value.js' +import { buildStringFormatter } from './build-string-formatter.js' +/** + * Compares two strings alphabetically using locale-aware comparison. + * + * Applies string formatting based on options (case sensitivity, special + * characters handling) before performing the comparison. + * + * @param a - The first string to compare. + * @param b - The second string to compare. + * @param options - Comparison options. + * @param options.specialCharacters - How to handle special characters. + * @param options.ignoreCase - Whether to ignore case differences. + * @param options.locales - The locale(s) to use for comparison. + * @param options.order - The order direction ('asc' or 'desc'). + * @returns A negative number if a < b, positive if a > b, or 0 if equal. + */ +function compareAlphabetically( + a, + b, + { specialCharacters, ignoreCase, locales, order }, +) { + let formatString = buildStringFormatter({ + specialCharacters, + ignoreCase, + }) + let result = formatString(a).localeCompare(formatString(b), locales) + return computeOrderedValue(result, order) +} +export { compareAlphabetically } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compare-by-custom-sort.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compare-by-custom-sort.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e7c74d44cf6e78010cc42d2a180d65c89f6baf3 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compare-by-custom-sort.d.ts @@ -0,0 +1,14 @@ +import { CommonOptions } from '../../types/common-options.js' +export declare function compareByCustomSort( + a: string, + b: string, + { + specialCharacters, + ignoreCase, + alphabet, + order, + }: Pick< + CommonOptions, + 'specialCharacters' | 'ignoreCase' | 'alphabet' | 'order' + >, +): number diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compare-by-custom-sort.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compare-by-custom-sort.js new file mode 100644 index 0000000000000000000000000000000000000000..2e5340f241666935afe0a84b2d155ba1ac4bdd58 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compare-by-custom-sort.js @@ -0,0 +1,51 @@ +import { computeOrderedValue } from './compute-ordered-value.js' +import { buildStringFormatter } from './build-string-formatter.js' +import { convertBooleanToSign } from '../convert-boolean-to-sign.js' +/** + * Cache for pre-computed character index maps to avoid recalculating for the + * same custom alphabets across multiple comparisons. + */ +var alphabetCache = /* @__PURE__ */ new Map() +function compareByCustomSort( + a, + b, + { specialCharacters, ignoreCase, alphabet, order }, +) { + let formatString = buildStringFormatter({ + specialCharacters, + ignoreCase, + }) + let indexByCharacters = alphabetCache.get(alphabet) + if (!indexByCharacters) { + indexByCharacters = /* @__PURE__ */ new Map() + for (let [index, character] of [...alphabet].entries()) { + indexByCharacters.set(character, index) + } + alphabetCache.set(alphabet, indexByCharacters) + } + let aValue = formatString(a) + let bValue = formatString(b) + let minLength = Math.min(aValue.length, bValue.length) + for (let i = 0; i < minLength; i++) { + let aCharacter = aValue[i] + let bCharacter = bValue[i] + let indexOfA = indexByCharacters.get(aCharacter) + let indexOfB = indexByCharacters.get(bCharacter) + indexOfA ??= Infinity + indexOfB ??= Infinity + if (indexOfA !== indexOfB) { + return computeOrderedValue( + convertBooleanToSign(indexOfA > indexOfB), + order, + ) + } + } + if (aValue.length === bValue.length) { + return 0 + } + return computeOrderedValue( + convertBooleanToSign(aValue.length > bValue.length), + order, + ) +} +export { compareByCustomSort } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compare-naturally.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compare-naturally.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..de8a17cd7028e1ab29e068868a008c308d917202 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compare-naturally.d.ts @@ -0,0 +1,30 @@ +import { CommonOptions } from '../../types/common-options.js' +/** + * Compares two strings using natural sort order. + * + * Natural sorting handles embedded numbers intelligently, so "item2" comes + * before "item10". Applies string formatting based on options before performing + * the comparison. + * + * @param a - The first string to compare. + * @param b - The second string to compare. + * @param options - Comparison options. + * @param options.specialCharacters - How to handle special characters. + * @param options.ignoreCase - Whether to ignore case differences. + * @param options.locales - The locale(s) to use for comparison. + * @param options.order - The order direction ('asc' or 'desc'). + * @returns A negative number if a < b, positive if a > b, or 0 if equal. + */ +export declare function compareNaturally( + a: string, + b: string, + { + specialCharacters, + ignoreCase, + locales, + order, + }: Pick< + CommonOptions, + 'specialCharacters' | 'ignoreCase' | 'locales' | 'order' + >, +): number diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compare-naturally.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compare-naturally.js new file mode 100644 index 0000000000000000000000000000000000000000..e0d266fae9e4d2877b913851661d0f7f49253942 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compare-naturally.js @@ -0,0 +1,33 @@ +import { computeOrderedValue } from './compute-ordered-value.js' +import { buildStringFormatter } from './build-string-formatter.js' +import { compare } from 'natural-orderby' +/** + * Compares two strings using natural sort order. + * + * Natural sorting handles embedded numbers intelligently, so "item2" comes + * before "item10". Applies string formatting based on options before performing + * the comparison. + * + * @param a - The first string to compare. + * @param b - The second string to compare. + * @param options - Comparison options. + * @param options.specialCharacters - How to handle special characters. + * @param options.ignoreCase - Whether to ignore case differences. + * @param options.locales - The locale(s) to use for comparison. + * @param options.order - The order direction ('asc' or 'desc'). + * @returns A negative number if a < b, positive if a > b, or 0 if equal. + */ +function compareNaturally( + a, + b, + { specialCharacters, ignoreCase, locales, order }, +) { + let naturalCompare = compare({ locale: locales.toString() }) + let formatString = buildStringFormatter({ + specialCharacters, + ignoreCase, + }) + let result = naturalCompare(formatString(a), formatString(b)) + return computeOrderedValue(result, order) +} +export { compareNaturally } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compute-comparators.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compute-comparators.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..58d94ad4bf149966601488ddb934dbf77dd063a0 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compute-comparators.d.ts @@ -0,0 +1,25 @@ +import { + ComparatorByOptionsComputer, + Comparator, +} from './default-comparator-by-options-computer.js' +import { CommonOptions } from '../../types/common-options.js' +import { SortingNode } from '../../types/sorting-node.js' +/** + * Computes the array of comparators to use for sorting based on options. + * + * Returns an array containing the main comparator and a fallback comparator. If + * the main comparator is the unsorted comparator, returns an empty array since + * no sorting should be performed. + * + * @param comparatorByOptionsComputer - Function that creates a comparator from + * options. + * @param options - The sorting options including fallback sort configuration. + * @returns An array of comparators, or empty array if sorting is disabled. + */ +export declare function computeComparators< + Options extends Pick, + T extends SortingNode, +>( + comparatorByOptionsComputer: ComparatorByOptionsComputer, + options: Options, +): Comparator[] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compute-comparators.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compute-comparators.js new file mode 100644 index 0000000000000000000000000000000000000000..3c683494d6649ed179e5e229b976ce6fee92cc70 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compute-comparators.js @@ -0,0 +1,27 @@ +import { unsortedComparator } from './unsorted-comparator.js' +/** + * Computes the array of comparators to use for sorting based on options. + * + * Returns an array containing the main comparator and a fallback comparator. If + * the main comparator is the unsorted comparator, returns an empty array since + * no sorting should be performed. + * + * @param comparatorByOptionsComputer - Function that creates a comparator from + * options. + * @param options - The sorting options including fallback sort configuration. + * @returns An array of comparators, or empty array if sorting is disabled. + */ +function computeComparators(comparatorByOptionsComputer, options) { + let mainComparator = comparatorByOptionsComputer(options) + if (mainComparator === unsortedComparator) { + return [] + } + return [ + mainComparator, + comparatorByOptionsComputer({ + ...options, + ...options.fallbackSort, + }), + ] +} +export { computeComparators } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compute-ordered-value.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compute-ordered-value.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d85da8df3c72d846ca0387d5a28e6794d7e7c780 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compute-ordered-value.d.ts @@ -0,0 +1,15 @@ +import { CommonOptions } from '../../types/common-options.js' +/** + * Adjusts a comparison result value based on the specified sort order. + * + * For ascending order, returns the value unchanged. For descending order, + * negates the value to reverse the sort direction. + * + * @param value - The comparison result value to adjust. + * @param order - The order direction ('asc' or 'desc'). + * @returns The adjusted comparison value. + */ +export declare function computeOrderedValue( + value: number, + order: CommonOptions['order'], +): number diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compute-ordered-value.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compute-ordered-value.js new file mode 100644 index 0000000000000000000000000000000000000000..8145c6c487911d06e44e873486e6b9a9cf58687b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/compute-ordered-value.js @@ -0,0 +1,23 @@ +import { UnreachableCaseError } from '../unreachable-case-error.js' +/** + * Adjusts a comparison result value based on the specified sort order. + * + * For ascending order, returns the value unchanged. For descending order, + * negates the value to reverse the sort direction. + * + * @param value - The comparison result value to adjust. + * @param order - The order direction ('asc' or 'desc'). + * @returns The adjusted comparison value. + */ +function computeOrderedValue(value, order) { + switch (order) { + case 'desc': + return -value + case 'asc': + return value + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(order) + } +} +export { computeOrderedValue } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/default-comparator-by-options-computer.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/default-comparator-by-options-computer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..72cb64c3c6e4a2a63b88f1e8ca682df7158f5550 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/default-comparator-by-options-computer.d.ts @@ -0,0 +1,19 @@ +import { CommonOptions, TypeOption } from '../../types/common-options.js' +import { GroupsOptions } from '../../types/common-groups-options.js' +import { SortingNode } from '../../types/sorting-node.js' +export type ComparatorByOptionsComputer = ( + options: S, +) => Comparator +export type Comparator = (a: T, b: T) => number +type Options = Pick< + CommonOptions, + 'specialCharacters' | 'ignoreCase' | 'alphabet' | 'locales' | 'order' | 'type' +> & + Pick & { + groups?: GroupsOptions + } +export declare let defaultComparatorByOptionsComputer: ComparatorByOptionsComputer< + Options, + SortingNode +> +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/default-comparator-by-options-computer.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/default-comparator-by-options-computer.js new file mode 100644 index 0000000000000000000000000000000000000000..351e1d4c6cd6702c55ff61d1901261ced46f2950 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/default-comparator-by-options-computer.js @@ -0,0 +1,33 @@ +import { UnreachableCaseError } from '../unreachable-case-error.js' +import { buildSubgroupOrderComparator } from './build-subgroup-order-comparator.js' +import { buildLineLengthComparator } from './build-line-length-comparator.js' +import { compareAlphabetically } from './compare-alphabetically.js' +import { compareByCustomSort } from './compare-by-custom-sort.js' +import { unsortedComparator } from './unsorted-comparator.js' +import { compareNaturally } from './compare-naturally.js' +var defaultComparatorByOptionsComputer = options => { + switch (options.type) { + case 'subgroup-order': + if (!options.groups) { + return unsortedComparator + } + return buildSubgroupOrderComparator({ + ...options, + groups: options.groups, + }) + case 'alphabetical': + return (a, b) => compareAlphabetically(a.name, b.name, options) + case 'line-length': + return buildLineLengthComparator(options) + case 'unsorted': + return unsortedComparator + case 'natural': + return (a, b) => compareNaturally(a.name, b.name, options) + case 'custom': + return (a, b) => compareByCustomSort(a.name, b.name, options) + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError(options.type) + } +} +export { defaultComparatorByOptionsComputer } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/unsorted-comparator.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/unsorted-comparator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d8ab24a8913aeffef8a95fc22cb0a7098ac5e6a4 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/unsorted-comparator.d.ts @@ -0,0 +1,3 @@ +import { Comparator } from './default-comparator-by-options-computer.js' +import { SortingNode } from '../../types/sorting-node.js' +export declare let unsortedComparator: Comparator diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/unsorted-comparator.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/unsorted-comparator.js new file mode 100644 index 0000000000000000000000000000000000000000..a1cf8ffdd46b7f219b217b8ea4650dd0c4eff115 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compare/unsorted-comparator.js @@ -0,0 +1,2 @@ +var unsortedComparator = () => 0 +export { unsortedComparator } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/complete.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/complete.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ff57ce09c8ad773f1b0d57bcfccfdecdc1d134a --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/complete.d.ts @@ -0,0 +1,36 @@ +import { Settings } from './get-settings.js' +/** + * Merges configuration options with settings and defaults in priority order. + * + * Combines three levels of configuration with increasing priority: + * + * 1. Default values (lowest priority) + * 2. Global settings from ESLint configuration. + * 3. Rule-specific options (highest priority). + * + * This ensures that user-provided options always override settings, and + * settings always override defaults. + * + * @example + * + * ```ts + * const finalOptions = complete( + * { type: 'natural' }, // User options (highest priority) + * { order: 'asc' }, // Global settings + * { type: 'alphabetical', order: 'desc' }, // Defaults (lowest priority) + * ) + * // Returns: { type: 'natural', order: 'asc' } + * ``` + * + * @template T - Type of the configuration object. + * @param options - Rule-specific options provided by the user (highest + * priority). + * @param settings - Global settings from ESLint configuration. + * @param defaults - Default values for the configuration (lowest priority). + * @returns Merged configuration object with all three levels combined. + */ +export declare function complete>( + options?: Partial, + settings?: Settings, + defaults?: T, +): T diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/complete.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/complete.js new file mode 100644 index 0000000000000000000000000000000000000000..f39ea415ac7825dcd559775676da134bb1ab1a60 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/complete.js @@ -0,0 +1,38 @@ +/** + * Merges configuration options with settings and defaults in priority order. + * + * Combines three levels of configuration with increasing priority: + * + * 1. Default values (lowest priority) + * 2. Global settings from ESLint configuration. + * 3. Rule-specific options (highest priority). + * + * This ensures that user-provided options always override settings, and + * settings always override defaults. + * + * @example + * + * ```ts + * const finalOptions = complete( + * { type: 'natural' }, // User options (highest priority) + * { order: 'asc' }, // Global settings + * { type: 'alphabetical', order: 'desc' }, // Defaults (lowest priority) + * ) + * // Returns: { type: 'natural', order: 'asc' } + * ``` + * + * @template T - Type of the configuration object. + * @param options - Rule-specific options provided by the user (highest + * priority). + * @param settings - Global settings from ESLint configuration. + * @param defaults - Default values for the configuration (lowest priority). + * @returns Merged configuration object with all three levels combined. + */ +function complete(options = {}, settings = {}, defaults = {}) { + return { + ...defaults, + ...settings, + ...options, + } +} +export { complete } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-deep-scope-references.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-deep-scope-references.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..af4e56ec87a7976321994b4c69e693c126b5dde9 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-deep-scope-references.d.ts @@ -0,0 +1,13 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { TSESTree } from '@typescript-eslint/types' +/** + * Recursively computes all scope references deeply for a given node. + * + * @param node - The AST node. + * @param sourceCode - The source code object. + * @returns The list of scope references. + */ +export declare function computeDeepScopeReferences( + node: TSESTree.Node, + sourceCode: TSESLint.SourceCode, +): TSESLint.Scope.Reference[] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-deep-scope-references.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-deep-scope-references.js new file mode 100644 index 0000000000000000000000000000000000000000..4af7b563854161207dfa8aa73972a3e919c11b19 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-deep-scope-references.js @@ -0,0 +1,17 @@ +/** + * Recursively computes all scope references deeply for a given node. + * + * @param node - The AST node. + * @param sourceCode - The source code object. + * @returns The list of scope references. + */ +function computeDeepScopeReferences(node, sourceCode) { + return computeScopeReference(sourceCode.getScope(node)) + function computeScopeReference(scope) { + return [ + ...scope.references, + ...scope.childScopes.flatMap(computeScopeReference), + ] + } +} +export { computeDeepScopeReferences } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-dependencies-by-sorting-node.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-dependencies-by-sorting-node.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..581cc5221aaf2c1ce1d01d70a5f0b73e8ee81e23 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-dependencies-by-sorting-node.d.ts @@ -0,0 +1,42 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +import { SortingNodeWithDependencies } from './sort-nodes-by-dependencies.js' +export type ShouldIgnoreIdentifierComputer = (parameters: { + identifier: TSESTree.JSXIdentifier | TSESTree.Identifier + referencingSortingNode: T +}) => boolean +export type AdditionalIdentifierDependenciesComputer = (parameters: { + reference: TSESLint.Scope.Reference + referencingSortingNode: T +}) => T[] +export type ShouldIgnoreSortingNodeComputer = (sortingNode: T) => boolean +/** + * Compute the list of dependencies for each sorting node. + * + * @param params - The parameters object. + * @param params.additionalIdentifierDependenciesComputer - A function to + * compute additional dependencies for an identifier. + * @param params.shouldIgnoreSortingNodeComputer - A function to determine if a + * sorting node should be ignored. + * @param params.shouldIgnoreIdentifierComputer - A function to determine if an + * identifier should be ignored. + * @param params.sortingNodes - The sorting nodes to compute dependencies for. + * @param params.sourceCode - The source code object. + * @returns A map of sorting nodes to their dependencies. + */ +export declare function computeDependenciesBySortingNode< + Node extends TSESTree.Node, + T extends Pick, 'dependencyNames' | 'node'>, +>({ + additionalIdentifierDependenciesComputer, + shouldIgnoreSortingNodeComputer, + shouldIgnoreIdentifierComputer, + sortingNodes, + sourceCode, +}: { + additionalIdentifierDependenciesComputer?: AdditionalIdentifierDependenciesComputer + shouldIgnoreSortingNodeComputer?: ShouldIgnoreSortingNodeComputer + shouldIgnoreIdentifierComputer?: ShouldIgnoreIdentifierComputer + sourceCode: TSESLint.SourceCode + sortingNodes: T[] +}): Map diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-dependencies-by-sorting-node.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-dependencies-by-sorting-node.js new file mode 100644 index 0000000000000000000000000000000000000000..b27255648dbecfd81fe01ef317b7bdffb2e91c1c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-dependencies-by-sorting-node.js @@ -0,0 +1,103 @@ +import { computeDeepScopeReferences } from './compute-deep-scope-references.js' +import { rangeContainsRange } from './range-contains-range.js' +/** + * Compute the list of dependencies for each sorting node. + * + * @param params - The parameters object. + * @param params.additionalIdentifierDependenciesComputer - A function to + * compute additional dependencies for an identifier. + * @param params.shouldIgnoreSortingNodeComputer - A function to determine if a + * sorting node should be ignored. + * @param params.shouldIgnoreIdentifierComputer - A function to determine if an + * identifier should be ignored. + * @param params.sortingNodes - The sorting nodes to compute dependencies for. + * @param params.sourceCode - The source code object. + * @returns A map of sorting nodes to their dependencies. + */ +function computeDependenciesBySortingNode({ + additionalIdentifierDependenciesComputer, + shouldIgnoreSortingNodeComputer, + shouldIgnoreIdentifierComputer, + sortingNodes, + sourceCode, +}) { + let returnValue = /* @__PURE__ */ new Map() + let references = sortingNodes.flatMap(sortingNode => + computeDeepScopeReferences(sortingNode.node, sourceCode), + ) + let uniqueReferences = new Set(references) + for (let reference of uniqueReferences) { + let { identifier, resolved } = reference + if (!resolved) { + continue + } + let referencingSortingNode = findSortingNodeContainingIdentifier( + sortingNodes, + identifier, + ) + if (!referencingSortingNode) { + continue + } + if (shouldIgnoreSortingNodeComputer?.(referencingSortingNode)) { + continue + } + let referencedNodes = returnValue.get(referencingSortingNode) ?? [] + returnValue.set(referencingSortingNode, referencedNodes) + referencedNodes.push( + ...computeMainIdentifierDependencies({ + shouldIgnoreSortingNodeComputer, + shouldIgnoreIdentifierComputer, + referencingSortingNode, + sortingNodes, + identifier, + resolved, + }), + ...(additionalIdentifierDependenciesComputer?.({ + referencingSortingNode, + reference, + }) ?? []), + ) + } + return returnValue +} +function computeMainIdentifierDependencies({ + shouldIgnoreSortingNodeComputer, + shouldIgnoreIdentifierComputer, + referencingSortingNode, + sortingNodes, + identifier, + resolved, +}) { + if ( + shouldIgnoreIdentifierComputer?.({ + referencingSortingNode, + identifier, + }) + ) { + return [] + } + let [firstIdentifier] = resolved.identifiers + if (!firstIdentifier) { + return [] + } + let referencedSortingNode = findSortingNodeContainingIdentifier( + sortingNodes, + firstIdentifier, + ) + if (!referencedSortingNode) { + return [] + } + if (shouldIgnoreSortingNodeComputer?.(referencedSortingNode)) { + return [] + } + if (referencedSortingNode === referencingSortingNode) { + return [] + } + return [referencedSortingNode] +} +function findSortingNodeContainingIdentifier(sortingNodes, identifier) { + return sortingNodes.find(sortingNode => + rangeContainsRange(sortingNode.node.range, identifier.range), + ) +} +export { computeDependenciesBySortingNode } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-dependencies-outside-functions-by-sorting-node.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-dependencies-outside-functions-by-sorting-node.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..debadb761f6ecfb784f57bf4f679061c5c09338e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-dependencies-outside-functions-by-sorting-node.d.ts @@ -0,0 +1,13 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +import { SortingNodeWithDependencies } from './sort-nodes-by-dependencies.js' +export declare function computeDependenciesOutsideFunctionsBySortingNode< + Node extends TSESTree.Node, + T extends Pick, 'dependencyNames' | 'node'>, +>({ + sortingNodes, + sourceCode, +}: { + sourceCode: TSESLint.SourceCode + sortingNodes: T[] +}): Map diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-dependencies-outside-functions-by-sorting-node.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-dependencies-outside-functions-by-sorting-node.js new file mode 100644 index 0000000000000000000000000000000000000000..83b7b1345b219cf0c72d8124854b7a897f5a654f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-dependencies-outside-functions-by-sorting-node.js @@ -0,0 +1,30 @@ +import { computeDependenciesBySortingNode } from './compute-dependencies-by-sorting-node.js' +import { computeParentNodesWithTypes } from './compute-parent-nodes-with-types.js' +import { isNodeImmediatelyCalled } from './is-node-immediately-called.js' +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +function computeDependenciesOutsideFunctionsBySortingNode({ + sortingNodes, + sourceCode, +}) { + return computeDependenciesBySortingNode({ + shouldIgnoreIdentifierComputer: buildShouldIgnoreIdentifierComputer(), + sortingNodes, + sourceCode, + }) + function buildShouldIgnoreIdentifierComputer() { + return ({ referencingSortingNode, identifier }) => { + return computeParentNodesWithTypes({ + allowedTypes: [ + AST_NODE_TYPES.FunctionExpression, + AST_NODE_TYPES.ArrowFunctionExpression, + ], + maxParent: referencingSortingNode.node, + consecutiveOnly: false, + node: identifier, + }).some( + functionParentNode => !isNodeImmediatelyCalled(functionParentNode), + ) + } + } +} +export { computeDependenciesOutsideFunctionsBySortingNode } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-group-name.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-group-name.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..73c5789d04d68a11f45de1a924a3215948ff3b18 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-group-name.d.ts @@ -0,0 +1,13 @@ +import { GroupsOptions } from '../types/common-groups-options.js' +/** + * Computes the name of a group based on the provided group object. + * + * @param group - The group object. + * @returns A string if: + * + * - The group is a string. + * - The group is a commentAbove option with a string group. + */ +export declare function computeGroupName( + group: GroupsOptions[number], +): string | null diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-group-name.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-group-name.js new file mode 100644 index 0000000000000000000000000000000000000000..e22e388c897ab13b863f630e7cf208d2cd8b827d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-group-name.js @@ -0,0 +1,33 @@ +import { isGroupWithOverridesOption } from './is-group-with-overrides-option.js' +import { isNewlinesBetweenOption } from './is-newlines-between-option.js' +import { UnreachableCaseError } from './unreachable-case-error.js' +/** + * Computes the name of a group based on the provided group object. + * + * @param group - The group object. + * @returns A string if: + * + * - The group is a string. + * - The group is a commentAbove option with a string group. + */ +function computeGroupName(group) { + if (typeof group === 'string' || Array.isArray(group)) { + return computeStringGroupName(group) + } + if (isGroupWithOverridesOption(group)) { + return computeStringGroupName(group.group) + } + /* v8 ignore else -- @preserve Exhaustive guard for unsupported group option. */ + if (isNewlinesBetweenOption(group)) { + return null + } + /* v8 ignore next -- @preserve Exhaustive guard for unsupported group option. */ + throw new UnreachableCaseError(group) +} +function computeStringGroupName(group) { + if (typeof group === 'string') { + return group + } + return null +} +export { computeGroupName } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-group.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-group.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..10c2edde404663143f6bac377a6c0723ea06d8a8 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-group.d.ts @@ -0,0 +1,72 @@ +import { + CommonGroupsOptions, + AnyOfCustomGroup, +} from '../types/common-groups-options.js' +/** + * Parameters for computing the group of an element. + * + * @template CustomGroupMatchOptions - Type of custom group match options. + */ +interface ComputeGroupParameters { + /** + * Configuration options for grouping. + */ + options: Pick< + CommonGroupsOptions, + 'customGroups' | 'groups' + > + /** + * Function to test if an element matches a custom group. Takes a custom + * group configuration and returns true if the element matches. + */ + customGroupMatcher: CustomGroupMatcher + /** + * List of predefined groups that the element belongs to. These are checked + * after custom groups as a fallback. + */ + predefinedGroups: string[] +} +type CustomGroupMatcher = ( + customGroup: AnyOfCustomGroup | Partial, +) => boolean +/** + * Determines which group an element belongs to based on custom and predefined + * groups. + * + * The function checks groups in the following priority order: + * + * 1. Custom groups (if defined) - checked first, highest priority + * 2. Predefined groups - checked as fallback + * 3. Returns 'unknown' if no matching group is found. + * + * Only groups that exist in options.groups are considered valid. + * + * @example + * + * ```ts + * const group = computeGroup({ + * options: { + * groups: ['react', 'external', 'internal'], + * customGroups: [{ groupName: 'react', anyOf: ['react', 'react-*'] }], + * }, + * customGroupMatcher: customGroup => customGroup.anyOf.includes('react'), + * predefinedGroups: ['external'], + * name: 'react-dom', + * }) + * // Returns: 'react' + * ``` + * + * @template CustomGroupMatchOptions - Type of custom group match options. + * @param params - Parameters for group computation. + * @param params.options - Configuration with available groups and custom + * groups. + * @param params.customGroupMatcher - Matcher function for custom groups. + * @param params.predefinedGroups - Fallback predefined groups to check. + * @returns The matched group name or 'unknown' if no group matches. + */ +export declare function computeGroup({ + customGroupMatcher, + predefinedGroups, + options, +}: ComputeGroupParameters): 'unknown' | string +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-group.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-group.js new file mode 100644 index 0000000000000000000000000000000000000000..29e457921272cd269bdcf1e109415d47100d78f0 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-group.js @@ -0,0 +1,64 @@ +import { computeGroupsNames } from './compute-groups-names.js' +/** + * Determines which group an element belongs to based on custom and predefined + * groups. + * + * The function checks groups in the following priority order: + * + * 1. Custom groups (if defined) - checked first, highest priority + * 2. Predefined groups - checked as fallback + * 3. Returns 'unknown' if no matching group is found. + * + * Only groups that exist in options.groups are considered valid. + * + * @example + * + * ```ts + * const group = computeGroup({ + * options: { + * groups: ['react', 'external', 'internal'], + * customGroups: [{ groupName: 'react', anyOf: ['react', 'react-*'] }], + * }, + * customGroupMatcher: customGroup => customGroup.anyOf.includes('react'), + * predefinedGroups: ['external'], + * name: 'react-dom', + * }) + * // Returns: 'react' + * ``` + * + * @template CustomGroupMatchOptions - Type of custom group match options. + * @param params - Parameters for group computation. + * @param params.options - Configuration with available groups and custom + * groups. + * @param params.customGroupMatcher - Matcher function for custom groups. + * @param params.predefinedGroups - Fallback predefined groups to check. + * @returns The matched group name or 'unknown' if no group matches. + */ +function computeGroup({ customGroupMatcher, predefinedGroups, options }) { + let groupsSet = new Set(computeGroupsNames(options.groups)) + return ( + computeFirstMatchingCustomGroupName( + groupsSet, + options.customGroups, + customGroupMatcher, + ) ?? + predefinedGroups.find(group => groupsSet.has(group)) ?? + 'unknown' + ) +} +function computeFirstMatchingCustomGroupName( + groupsSet, + customGroups, + customGroupMatcher, +) { + for (let customGroup of customGroups) { + if ( + customGroupMatcher(customGroup) && + groupsSet.has(customGroup.groupName) + ) { + return customGroup.groupName + } + } + return null +} +export { computeGroup } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-groups-names.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-groups-names.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..01675a573a91e8ba4e0eabb8a88a95a507b25b8f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-groups-names.d.ts @@ -0,0 +1,8 @@ +import { GroupsOptions } from '../types/common-groups-options.js' +/** + * Computes the names of all groups based on the provided `GroupsOptions`. + * + * @param groups - An array of group options. + * @returns An array of computed group names as strings. + */ +export declare function computeGroupsNames(groups: GroupsOptions): string[] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-groups-names.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-groups-names.js new file mode 100644 index 0000000000000000000000000000000000000000..c6cc065d0556f119656356f3941a2e301f92a3cb --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-groups-names.js @@ -0,0 +1,33 @@ +import { isGroupWithOverridesOption } from './is-group-with-overrides-option.js' +import { isNewlinesBetweenOption } from './is-newlines-between-option.js' +import { UnreachableCaseError } from './unreachable-case-error.js' +/** + * Computes the names of all groups based on the provided `GroupsOptions`. + * + * @param groups - An array of group options. + * @returns An array of computed group names as strings. + */ +function computeGroupsNames(groups) { + return groups.flatMap(group => computeGroupNames(group)) +} +function computeGroupNames(group) { + if (typeof group === 'string' || Array.isArray(group)) { + return computeStringGroupNames(group) + } + if (isGroupWithOverridesOption(group)) { + return computeStringGroupNames(group.group) + } + /* v8 ignore else -- @preserve Exhaustive guard for unsupported group option. */ + if (isNewlinesBetweenOption(group)) { + return [] + } + /* v8 ignore next -- @preserve Exhaustive guard for unsupported group option. */ + throw new UnreachableCaseError(group) +} +function computeStringGroupNames(group) { + if (typeof group === 'string') { + return [group] + } + return group +} +export { computeGroupsNames } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-nodes-in-circular-dependencies.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-nodes-in-circular-dependencies.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b16cfcb85cccec030c1ed8ea06a4308a650d4502 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-nodes-in-circular-dependencies.d.ts @@ -0,0 +1,39 @@ +import { SortingNodeWithDependencies } from './sort-nodes-by-dependencies.js' +/** + * Detects nodes that are part of circular dependency chains. + * + * Uses a depth-first search (DFS) algorithm with three-color marking to + * identify cycles in the dependency graph. When a cycle is detected, all nodes + * in that cycle are added to the result set. + * + * The algorithm tracks three states for each node: + * + * - Not visited: Node hasn't been processed yet + * - Visiting: Currently in the DFS path (gray in three-color marking) + * - Visited: Completely processed (black in three-color marking). + * + * A cycle is detected when we encounter a node that is already in the + * "visiting" state, meaning we've found a back edge in the graph. + * + * @example + * + * ```ts + * const nodes = [ + * { name: 'A', dependencies: ['B'], dependencyNames: ['A'] }, + * { name: 'B', dependencies: ['C'], dependencyNames: ['B'] }, + * { name: 'C', dependencies: ['A'], dependencyNames: ['C'] }, + * ] + * const circularNodes = computeNodesInCircularDependencies(nodes) + * // Returns: Set containing all three nodes (A, B, C) + * ``` + * + * @template T - Type of sorting node with dependencies. + * @param elements - Array of nodes with dependency information. + * @returns Set of nodes that participate in circular dependencies. + */ +export declare function computeNodesInCircularDependencies< + T extends Pick< + SortingNodeWithDependencies, + 'dependencyNames' | 'dependencies' + >, +>(elements: T[]): Set diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-nodes-in-circular-dependencies.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-nodes-in-circular-dependencies.js new file mode 100644 index 0000000000000000000000000000000000000000..74d6d355fb82c7a0f709ebeae73389ad55e688c7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-nodes-in-circular-dependencies.js @@ -0,0 +1,85 @@ +/** + * Detects nodes that are part of circular dependency chains. + * + * Uses a depth-first search (DFS) algorithm with three-color marking to + * identify cycles in the dependency graph. When a cycle is detected, all nodes + * in that cycle are added to the result set. + * + * The algorithm tracks three states for each node: + * + * - Not visited: Node hasn't been processed yet + * - Visiting: Currently in the DFS path (gray in three-color marking) + * - Visited: Completely processed (black in three-color marking). + * + * A cycle is detected when we encounter a node that is already in the + * "visiting" state, meaning we've found a back edge in the graph. + * + * @example + * + * ```ts + * const nodes = [ + * { name: 'A', dependencies: ['B'], dependencyNames: ['A'] }, + * { name: 'B', dependencies: ['C'], dependencyNames: ['B'] }, + * { name: 'C', dependencies: ['A'], dependencyNames: ['C'] }, + * ] + * const circularNodes = computeNodesInCircularDependencies(nodes) + * // Returns: Set containing all three nodes (A, B, C) + * ``` + * + * @template T - Type of sorting node with dependencies. + * @param elements - Array of nodes with dependency information. + * @returns Set of nodes that participate in circular dependencies. + */ +function computeNodesInCircularDependencies(elements) { + let elementsInCycles = /* @__PURE__ */ new Set() + let visitingElements = /* @__PURE__ */ new Set() + let visitedElements = /* @__PURE__ */ new Set() + /** + * Performs depth-first search to detect cycles starting from the given + * element. + * + * Recursively traverses the dependency graph, maintaining a path of the + * current traversal. If a node in the current path is encountered again, a + * cycle is detected and all nodes in the cycle are marked. + * + * @param element - Current node being visited. + * @param path - Array of nodes in the current DFS path. + */ + function depthFirstSearch(element, path) { + if (visitedElements.has(element)) { + return + } + if (visitingElements.has(element)) { + let cycleStartIndex = path.indexOf(element) + /* v8 ignore else -- @preserve Visiting path already contains the element when this branch executes. */ + if (cycleStartIndex !== -1) { + for (let cycleElements of path.slice(cycleStartIndex)) { + elementsInCycles.add(cycleElements) + } + } + return + } + visitingElements.add(element) + path.push(element) + for (let dependency of element.dependencies) { + let dependencyElement = elements + .filter(currentElement => currentElement !== element) + .find(currentElement => + currentElement.dependencyNames.includes(dependency), + ) + /* v8 ignore next -- @preserve Dependencies are pre-filtered; missing entries are defensive fallback. */ + if (dependencyElement) { + depthFirstSearch(dependencyElement, [...path]) + } + } + visitingElements.delete(element) + visitedElements.add(element) + } + for (let element of elements) { + if (!visitedElements.has(element)) { + depthFirstSearch(element, []) + } + } + return elementsInCycles +} +export { computeNodesInCircularDependencies } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-overridden-options-by-group-index.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-overridden-options-by-group-index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cae29c3562442175375ea6a9433ebe6703fe2689 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-overridden-options-by-group-index.d.ts @@ -0,0 +1,51 @@ +import { CommonGroupsOptions } from '../types/common-groups-options.js' +import { CommonOptions } from '../types/common-options.js' +type Options = Pick< + CommonGroupsOptions, + 'customGroups' | 'groups' +> & + CommonOptions +/** + * Retrieves sorting options potentially overridden by a custom group or group + * with settings configuration. + * + * Checks if the group at the specified index is a custom group with its own + * sorting configuration. If so, returns the overridden options (type, order, + * fallbackSort). Otherwise, returns the original options. + * + * Custom groups can override: + * + * - Sort type (e.g., use 'natural' instead of global 'alphabetical') + * - Sort order (e.g., use 'desc' instead of global 'asc') + * - Fallback sort configuration. + * + * @example + * + * ```ts + * const options = { + * type: 'alphabetical', + * order: 'asc', + * fallbackSort: { type: 'natural' }, + * groups: ['custom-group', 'other'], + * customGroups: [ + * { + * groupName: 'custom-group', + * type: 'natural', + * order: 'desc', + * }, + * ], + * } + * const overridden = computeOverriddenOptionsByGroupIndex(options, 0) + * // Returns: { type: 'natural', order: 'desc', fallbackSort: { type: 'natural' } } + * ``` + * + * @param options - Combined group and sorting options. + * @param groupIndex - Index of the group to check for overrides. + * @returns Sorting options, potentially overridden by custom group + * configuration. + */ +export declare function computeOverriddenOptionsByGroupIndex( + options: T, + groupIndex: number, +): T +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-overridden-options-by-group-index.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-overridden-options-by-group-index.js new file mode 100644 index 0000000000000000000000000000000000000000..31beda0ce2695ff54d7100bd8672bce74fb9e29b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-overridden-options-by-group-index.js @@ -0,0 +1,86 @@ +import { isGroupWithOverridesOption } from './is-group-with-overrides-option.js' +import { computeGroupName } from './compute-group-name.js' +/** + * Retrieves sorting options potentially overridden by a custom group or group + * with settings configuration. + * + * Checks if the group at the specified index is a custom group with its own + * sorting configuration. If so, returns the overridden options (type, order, + * fallbackSort). Otherwise, returns the original options. + * + * Custom groups can override: + * + * - Sort type (e.g., use 'natural' instead of global 'alphabetical') + * - Sort order (e.g., use 'desc' instead of global 'asc') + * - Fallback sort configuration. + * + * @example + * + * ```ts + * const options = { + * type: 'alphabetical', + * order: 'asc', + * fallbackSort: { type: 'natural' }, + * groups: ['custom-group', 'other'], + * customGroups: [ + * { + * groupName: 'custom-group', + * type: 'natural', + * order: 'desc', + * }, + * ], + * } + * const overridden = computeOverriddenOptionsByGroupIndex(options, 0) + * // Returns: { type: 'natural', order: 'desc', fallbackSort: { type: 'natural' } } + * ``` + * + * @param options - Combined group and sorting options. + * @param groupIndex - Index of the group to check for overrides. + * @returns Sorting options, potentially overridden by custom group + * configuration. + */ +function computeOverriddenOptionsByGroupIndex(options, groupIndex) { + let { customGroups, groups } = options + let matchingGroup = groups[groupIndex] + let matchingGroupName = matchingGroup ? computeGroupName(matchingGroup) : null + let customGroup = customGroups.find( + currentGroup => matchingGroupName === currentGroup.groupName, + ) + let returnValue = { ...options } + if (matchingGroup && isGroupWithOverridesOption(matchingGroup)) { + let { + newlinesInside, + commentAbove, + fallbackSort, + group, + ...relevantGroupFields + } = matchingGroup + returnValue = { + ...returnValue, + ...relevantGroupFields, + fallbackSort: { + ...returnValue.fallbackSort, + ...fallbackSort, + }, + } + } + if (customGroup) { + let { + elementNamePattern, + newlinesInside, + fallbackSort, + groupName, + ...relevantCustomGroupFields + } = customGroup + returnValue = { + ...returnValue, + ...relevantCustomGroupFields, + fallbackSort: { + ...returnValue.fallbackSort, + ...fallbackSort, + }, + } + } + return returnValue +} +export { computeOverriddenOptionsByGroupIndex } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-parent-nodes-with-types.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-parent-nodes-with-types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..87e6d80ed62d375a31a578860b6fbc7097f388e3 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-parent-nodes-with-types.d.ts @@ -0,0 +1,28 @@ +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +import { TSESTree } from '@typescript-eslint/types' +import { NodeOfType } from '../types/node-of-type.js' +/** + * Finds all parent nodes matching one of the specified AST node types. + * + * @param options - Options for the search. + * @param options.allowedTypes - Array of AST node types to match. + * @param options.consecutiveOnly - If true, stops searching after the first + * non-matching parent node is found. + * @param options.node - Starting node to search from. + * @param options.maxParent - Optional maximum exclusive parent node to stop the + * search at. + * @returns List of matching parent nodes. + */ +export declare function computeParentNodesWithTypes< + NodeType extends AST_NODE_TYPES, +>({ + consecutiveOnly, + allowedTypes, + maxParent, + node, +}: { + maxParent: TSESTree.Node | null + consecutiveOnly: boolean + allowedTypes: NodeType[] + node: TSESTree.Node +}): NodeOfType[] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-parent-nodes-with-types.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-parent-nodes-with-types.js new file mode 100644 index 0000000000000000000000000000000000000000..554a2b4bbe5df23216b7a48f3ddf38a50760056c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/compute-parent-nodes-with-types.js @@ -0,0 +1,35 @@ +/** + * Finds all parent nodes matching one of the specified AST node types. + * + * @param options - Options for the search. + * @param options.allowedTypes - Array of AST node types to match. + * @param options.consecutiveOnly - If true, stops searching after the first + * non-matching parent node is found. + * @param options.node - Starting node to search from. + * @param options.maxParent - Optional maximum exclusive parent node to stop the + * search at. + * @returns List of matching parent nodes. + */ +function computeParentNodesWithTypes({ + consecutiveOnly, + allowedTypes, + maxParent, + node, +}) { + let allowedTypesSet = new Set(allowedTypes) + let returnValue = [] + let { parent } = node + while (parent) { + if (parent === maxParent) { + break + } + if (allowedTypesSet.has(parent.type)) { + returnValue.push(parent) + } else if (consecutiveOnly) { + break + } + ;({ parent } = parent) + } + return returnValue +} +export { computeParentNodesWithTypes } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/context-matching/passes-all-names-match-pattern-filter.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/context-matching/passes-all-names-match-pattern-filter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..02887eccf39b7ca6a57e4a41baa2709807380e68 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/context-matching/passes-all-names-match-pattern-filter.d.ts @@ -0,0 +1,18 @@ +import { RegexOption } from '../../types/common-options.js' +/** + * Checks if all node names match the specified pattern. + * + * @param params - The parameters object. + * @param params.allNamesMatchPattern - The pattern to match against all node + * names. + * @param params.nodeNames - Array of node names to test against patterns. + * @returns True if all node names match the specified pattern, or if no pattern + * is specified; otherwise, false. + */ +export declare function passesAllNamesMatchPatternFilter({ + allNamesMatchPattern, + nodeNames, +}: { + allNamesMatchPattern?: RegexOption + nodeNames: string[] +}): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/context-matching/passes-all-names-match-pattern-filter.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/context-matching/passes-all-names-match-pattern-filter.js new file mode 100644 index 0000000000000000000000000000000000000000..07b8043a989771fdb549953f7d95625a21b69fce --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/context-matching/passes-all-names-match-pattern-filter.js @@ -0,0 +1,18 @@ +import { matches } from '../matches.js' +/** + * Checks if all node names match the specified pattern. + * + * @param params - The parameters object. + * @param params.allNamesMatchPattern - The pattern to match against all node + * names. + * @param params.nodeNames - Array of node names to test against patterns. + * @returns True if all node names match the specified pattern, or if no pattern + * is specified; otherwise, false. + */ +function passesAllNamesMatchPatternFilter({ allNamesMatchPattern, nodeNames }) { + if (!allNamesMatchPattern) { + return true + } + return nodeNames.every(nodeName => matches(nodeName, allNamesMatchPattern)) +} +export { passesAllNamesMatchPatternFilter } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/context-matching/passes-ast-selector-filter.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/context-matching/passes-ast-selector-filter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..22fdff4f8c8bb4c69e29ac1e3f0e065aaefdb76a --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/context-matching/passes-ast-selector-filter.d.ts @@ -0,0 +1,17 @@ +/** + * Checks if the given AST selector matches the expected AST selector. + * + * @param params - The parameters object. + * @param params.matchesAstSelector - The AST selector to match against, or + * undefined if no selector is specified. + * @param params.matchedAstSelectors - The matched AST selectors for a node. + * @returns True if the given AST selector matches the expected AST selector, or + * if no selector is specified; otherwise, false. + */ +export declare function passesAstSelectorFilter({ + matchedAstSelectors, + matchesAstSelector, +}: { + matchedAstSelectors: ReadonlySet + matchesAstSelector: undefined | string +}): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/context-matching/passes-ast-selector-filter.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/context-matching/passes-ast-selector-filter.js new file mode 100644 index 0000000000000000000000000000000000000000..4051ada9a4a0fb22b774f6cbbb87905fc225f793 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/context-matching/passes-ast-selector-filter.js @@ -0,0 +1,17 @@ +/** + * Checks if the given AST selector matches the expected AST selector. + * + * @param params - The parameters object. + * @param params.matchesAstSelector - The AST selector to match against, or + * undefined if no selector is specified. + * @param params.matchedAstSelectors - The matched AST selectors for a node. + * @returns True if the given AST selector matches the expected AST selector, or + * if no selector is specified; otherwise, false. + */ +function passesAstSelectorFilter({ matchedAstSelectors, matchesAstSelector }) { + if (!matchesAstSelector) { + return true + } + return matchedAstSelectors.has(matchesAstSelector) +} +export { passesAstSelectorFilter } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/convert-boolean-to-sign.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/convert-boolean-to-sign.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f070c269ec7636d7b2d20edc9a512dc995f46f0 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/convert-boolean-to-sign.d.ts @@ -0,0 +1,27 @@ +/** + * Converts a boolean value to a sort direction multiplier. + * + * Used in sorting functions to convert boolean comparisons into numeric values + * suitable for array sort callbacks. This allows for concise expression of sort + * direction logic. + * + * @example + * + * ```ts + * // In ascending sort + * convertBooleanToSign(true) // Returns: 1 + * convertBooleanToSign(false) // Returns: -1 + * ``` + * + * @example + * + * ```ts + * // Usage in sorting + * const sortMultiplier = convertBooleanToSign(order === 'asc') + * return sortMultiplier * (a - b) + * ``` + * + * @param value - Boolean value to convert to a sign. + * @returns 1 if value is true, -1 if value is false. + */ +export declare function convertBooleanToSign(value: boolean): -1 | 1 diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/convert-boolean-to-sign.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/convert-boolean-to-sign.js new file mode 100644 index 0000000000000000000000000000000000000000..cc114f1df5d9e98bef4a2584d9a9c657b4160560 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/convert-boolean-to-sign.js @@ -0,0 +1,30 @@ +/** + * Converts a boolean value to a sort direction multiplier. + * + * Used in sorting functions to convert boolean comparisons into numeric values + * suitable for array sort callbacks. This allows for concise expression of sort + * direction logic. + * + * @example + * + * ```ts + * // In ascending sort + * convertBooleanToSign(true) // Returns: 1 + * convertBooleanToSign(false) // Returns: -1 + * ``` + * + * @example + * + * ```ts + * // Usage in sorting + * const sortMultiplier = convertBooleanToSign(order === 'asc') + * return sortMultiplier * (a - b) + * ``` + * + * @param value - Boolean value to convert to a sign. + * @returns 1 if value is true, -1 if value is false. + */ +function convertBooleanToSign(value) { + return value ? 1 : -1 +} +export { convertBooleanToSign } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/create-eslint-rule.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/create-eslint-rule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ebf8bb76a1068e98e74e39593873ccb819735f47 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/create-eslint-rule.d.ts @@ -0,0 +1,48 @@ +import { ESLintUtils } from '@typescript-eslint/utils' +/** + * Factory function for creating ESLint rules with consistent structure and + * documentation. + * + * Wraps the ESLintUtils.RuleCreator to automatically generate documentation + * URLs for each rule based on its name. All rules created with this function + * will have their documentation hosted at perfectionist.dev. + * + * @see {@link https://typescript-eslint.io/packages/utils/} - TypeScript ESLint + * Utils documentation + * @see {@link https://perfectionist.dev/} - Perfectionist plugin documentation + */ +export declare let createEslintRule: < + Options extends readonly unknown[], + MessageIds extends string, +>({ + meta, + name, + ...rule +}: Readonly< + ESLintUtils.RuleWithMetaAndName< + Options, + MessageIds, + { + /** + * Indicates whether the rule is part of the recommended configuration. + * + * @default false + */ + recommended?: boolean + } + > +>) => ESLintUtils.RuleModule< + MessageIds, + Options, + { + /** + * Indicates whether the rule is part of the recommended configuration. + * + * @default false + */ + recommended?: boolean + }, + ESLintUtils.RuleListener +> & { + name: string +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/create-eslint-rule.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/create-eslint-rule.js new file mode 100644 index 0000000000000000000000000000000000000000..7253d86e12dd275913fceab8b18e64b6c70195bb --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/create-eslint-rule.js @@ -0,0 +1,17 @@ +import { ESLintUtils } from '@typescript-eslint/utils' +/** + * Factory function for creating ESLint rules with consistent structure and + * documentation. + * + * Wraps the ESLintUtils.RuleCreator to automatically generate documentation + * URLs for each rule based on its name. All rules created with this function + * will have their documentation hosted at perfectionist.dev. + * + * @see {@link https://typescript-eslint.io/packages/utils/} - TypeScript ESLint + * Utils documentation + * @see {@link https://perfectionist.dev/} - Perfectionist plugin documentation + */ +var createEslintRule = ESLintUtils.RuleCreator( + ruleName => `https://perfectionist.dev/rules/${ruleName}`, +) +export { createEslintRule } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/create-node-index-map.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/create-node-index-map.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9a8a7c876acb8fc12ec700d32a3d3bad615fdb64 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/create-node-index-map.d.ts @@ -0,0 +1,30 @@ +import { TSESTree } from '@typescript-eslint/types' +import { SortingNode } from '../types/sorting-node.js' +/** + * Creates a Map for efficient lookup of node positions in the sorted array. + * + * Builds an index map that associates each sorting node with its position in + * the array. This is used to quickly determine the relative order of nodes + * without repeated array searches, improving performance when generating error + * messages for incorrectly sorted elements. + * + * @example + * + * ```ts + * const nodes = [ + * { name: 'foo', node: fooNode }, + * { name: 'bar', node: barNode }, + * { name: 'baz', node: bazNode }, + * ] + * const indexMap = createNodeIndexMap(nodes) + * indexMap.get(nodes[0]) // Returns: 0 + * indexMap.get(nodes[2]) // Returns: 2 + * ``` + * + * @template Node - Type of the AST node. + * @param nodes - Array of sorting nodes in their sorted order. + * @returns Map where keys are sorting nodes and values are their indices. + */ +export declare function createNodeIndexMap( + nodes: SortingNode[], +): Map diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/create-node-index-map.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/create-node-index-map.js new file mode 100644 index 0000000000000000000000000000000000000000..2a3bbf814c126b96f48d92e014c23b49e2af5bfd --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/create-node-index-map.js @@ -0,0 +1,33 @@ +/** + * Creates a Map for efficient lookup of node positions in the sorted array. + * + * Builds an index map that associates each sorting node with its position in + * the array. This is used to quickly determine the relative order of nodes + * without repeated array searches, improving performance when generating error + * messages for incorrectly sorted elements. + * + * @example + * + * ```ts + * const nodes = [ + * { name: 'foo', node: fooNode }, + * { name: 'bar', node: barNode }, + * { name: 'baz', node: bazNode }, + * ] + * const indexMap = createNodeIndexMap(nodes) + * indexMap.get(nodes[0]) // Returns: 0 + * indexMap.get(nodes[2]) // Returns: 2 + * ``` + * + * @template Node - Type of the AST node. + * @param nodes - Array of sorting nodes in their sorted order. + * @returns Map where keys are sorting nodes and values are their indices. + */ +function createNodeIndexMap(nodes) { + let nodeIndexMap = /* @__PURE__ */ new Map() + for (let [index, node] of nodes.entries()) { + nodeIndexMap.set(node, index) + } + return nodeIndexMap +} +export { createNodeIndexMap } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/does-custom-group-match.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/does-custom-group-match.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..078c354cdf40adcd47243a3ccaec3db5049ff820 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/does-custom-group-match.d.ts @@ -0,0 +1,128 @@ +import { AnyOfCustomGroup } from '../types/common-groups-options.js' +import { RegexOption } from '../types/common-options.js' +/** + * Parameters for testing if an element matches a custom group. + * + * Contains all the properties of an element that can be used for matching + * against custom group criteria. + */ +interface DoesCustomGroupMatchParameters { + /** + * Optional value of the element. Used for matching against + * elementValuePattern in custom groups. + */ + elementValue?: string | null + /** + * Optional list of decorator names applied to the element. Used for + * matching against decoratorNamePattern in custom groups. + */ + decoratorNames?: string[] + /** + * List of modifiers applied to the element (e.g., 'static', 'private', + * 'async'). Must include all modifiers specified in the custom group. + */ + modifiers: string[] + /** + * List of selectors that describe the element type. Used for matching + * against the selector field in custom groups. + */ + selectors: string[] + /** + * Name of the element. Used for matching against elementNamePattern in + * custom groups. + */ + elementName: string +} +/** + * Base structure for a single custom group configuration. + * + * Defines matching criteria that an element must satisfy to belong to this + * custom group. All specified criteria must match for the element to be + * considered part of the group. + */ +interface BaseCustomGroupMatchOptions { + /** + * Pattern to match against decorator names. Element must have at least one + * decorator matching this pattern. + */ + decoratorNamePattern?: RegexOption + /** + * Pattern to match against the element's value. Used for matching literal + * values, initializers, or expressions. + */ + elementValuePattern?: RegexOption + /** + * Regular expression pattern to match the element's name. Elements matching + * this pattern will be included in this custom group. + */ + elementNamePattern?: RegexOption + /** + * List of required modifiers. Element must have ALL specified modifiers to + * match. + */ + modifiers?: string[] + /** + * Required selector type. Element must have this exact selector to match. + */ + selector?: string +} +/** + * Checks whether an element matches the criteria of a custom group. + * + * Supports both single custom groups and "anyOf" groups (where matching any + * subgroup is sufficient). For single groups, all specified criteria must + * match. For "anyOf" groups, at least one subgroup must match. + * + * @example + * + * ```ts + * // Single custom group + * doesCustomGroupMatch({ + * customGroup: { + * selector: 'property', + * modifiers: ['static'], + * elementNamePattern: 'on*', + * }, + * elementName: 'onClick', + * selectors: ['property'], + * modifiers: ['static', 'readonly'], + * elementValue: null, + * decoratorNames: [], + * }) + * // Returns: true + * ``` + * + * @example + * + * ```ts + * // AnyOf custom group + * doesCustomGroupMatch({ + * customGroup: { + * anyOf: [ + * { selector: 'method' }, + * { selector: 'property', modifiers: ['static'] }, + * ], + * }, + * elementName: 'foo', + * selectors: ['method'], + * modifiers: [], + * elementValue: null, + * }) + * // Returns: true (matches first subgroup) + * ``` + * + * @template CustomGroupMatchOptions - Type of custom group match options. + * @param props - Combined parameters including the custom group and element + * properties. + * @returns True if the element matches the custom group criteria, false + * otherwise. + */ +export declare function doesCustomGroupMatch< + CustomGroupMatchOptions extends BaseCustomGroupMatchOptions, +>( + props: { + customGroup: + AnyOfCustomGroup | CustomGroupMatchOptions + } & DoesCustomGroupMatchParameters, +): boolean +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/does-custom-group-match.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/does-custom-group-match.js new file mode 100644 index 0000000000000000000000000000000000000000..e0d0a2bef47fb60235fecff863b17eea6b737881 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/does-custom-group-match.js @@ -0,0 +1,131 @@ +import { matches } from './matches.js' +/** + * Checks whether an element matches the criteria of a custom group. + * + * Supports both single custom groups and "anyOf" groups (where matching any + * subgroup is sufficient). For single groups, all specified criteria must + * match. For "anyOf" groups, at least one subgroup must match. + * + * @example + * + * ```ts + * // Single custom group + * doesCustomGroupMatch({ + * customGroup: { + * selector: 'property', + * modifiers: ['static'], + * elementNamePattern: 'on*', + * }, + * elementName: 'onClick', + * selectors: ['property'], + * modifiers: ['static', 'readonly'], + * elementValue: null, + * decoratorNames: [], + * }) + * // Returns: true + * ``` + * + * @example + * + * ```ts + * // AnyOf custom group + * doesCustomGroupMatch({ + * customGroup: { + * anyOf: [ + * { selector: 'method' }, + * { selector: 'property', modifiers: ['static'] }, + * ], + * }, + * elementName: 'foo', + * selectors: ['method'], + * modifiers: [], + * elementValue: null, + * }) + * // Returns: true (matches first subgroup) + * ``` + * + * @template CustomGroupMatchOptions - Type of custom group match options. + * @param props - Combined parameters including the custom group and element + * properties. + * @returns True if the element matches the custom group criteria, false + * otherwise. + */ +function doesCustomGroupMatch(props) { + if ('anyOf' in props.customGroup) { + return props.customGroup.anyOf.some(subgroup => + doesSingleCustomGroupMatch({ + ...props, + customGroup: subgroup, + }), + ) + } + return doesSingleCustomGroupMatch({ + ...props, + customGroup: props.customGroup, + }) +} +/** + * Checks whether an element matches a single custom group's criteria. + * + * Tests each criterion in sequence, returning false as soon as any criterion + * fails. All specified criteria must match for the function to return true. The + * checks are performed in the following order: + * + * 1. Selector match (exact) + * 2. Modifiers match (all required modifiers must be present) + * 3. Element name pattern match + * 4. Element value pattern match + * 5. Decorator name pattern match (at least one decorator must match). + * + * @param params - Parameters for matching. + * @param params.customGroup - Custom group configuration with matching + * criteria. + * @param params.elementName - Name of the element to test. + * @param params.elementValue - Optional value of the element. + * @param params.selectors - Element's selectors. + * @param params.modifiers - Element's modifiers. + * @param params.decoratorNames - Element's decorator names. + * @returns True if all specified criteria match, false otherwise. + */ +function doesSingleCustomGroupMatch({ + decoratorNames, + elementValue, + customGroup, + elementName, + selectors, + modifiers, +}) { + if (customGroup.selector && !selectors?.includes(customGroup.selector)) { + return false + } + if (customGroup.modifiers) { + for (let modifier of customGroup.modifiers) { + if (!modifiers?.includes(modifier)) { + return false + } + } + } + if ('elementNamePattern' in customGroup && customGroup.elementNamePattern) { + if (!matches(elementName, customGroup.elementNamePattern)) { + return false + } + } + if ('elementValuePattern' in customGroup && customGroup.elementValuePattern) { + if (!matches(elementValue ?? '', customGroup.elementValuePattern)) { + return false + } + } + if ( + 'decoratorNamePattern' in customGroup && + customGroup.decoratorNamePattern + ) { + let decoratorPattern = customGroup.decoratorNamePattern + if ( + !decoratorNames?.some(decorator => matches(decorator, decoratorPattern)) + ) { + return false + } + } + return true +} +export { doesCustomGroupMatch } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/does-sorting-node-have-one-of-dependency-names.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/does-sorting-node-have-one-of-dependency-names.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f892c5ad61d75e518c6e5e67f52f68872b8d7d68 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/does-sorting-node-have-one-of-dependency-names.d.ts @@ -0,0 +1,14 @@ +import { SortingNodeWithDependencies } from './sort-nodes-by-dependencies.js' +/** + * Checks whether the given sorting node has at least one of the given + * dependency names. + * + * @param sortingNode - The sorting node to check. + * @param dependencyNames - The dependency names to look for. + * @returns True if the sorting node has at least one of the dependency names, + * false otherwise. + */ +export declare function doesSortingNodeHaveOneOfDependencyNames( + sortingNode: Pick, + dependencyNames: string[], +): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/does-sorting-node-have-one-of-dependency-names.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/does-sorting-node-have-one-of-dependency-names.js new file mode 100644 index 0000000000000000000000000000000000000000..3078b5fb713c2cd9d68bb7beb60a17ef26ba23b4 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/does-sorting-node-have-one-of-dependency-names.js @@ -0,0 +1,16 @@ +/** + * Checks whether the given sorting node has at least one of the given + * dependency names. + * + * @param sortingNode - The sorting node to check. + * @param dependencyNames - The dependency names to look for. + * @returns True if the sorting node has at least one of the dependency names, + * false otherwise. + */ +function doesSortingNodeHaveOneOfDependencyNames(sortingNode, dependencyNames) { + let sortingNodeDependencyNames = new Set(sortingNode.dependencyNames) + return dependencyNames.some(dependencyName => + sortingNodeDependencyNames.has(dependencyName), + ) +} +export { doesSortingNodeHaveOneOfDependencyNames } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/generate-predefined-groups.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/generate-predefined-groups.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8cddb792fc32e690dbe12a87ef5c53c6d415a22f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/generate-predefined-groups.d.ts @@ -0,0 +1,25 @@ +interface GeneratePredefinedGroupsParameters { + cache: Map + modifiers: string[] + selectors: string[] +} +/** + * Generates an ordered list of group names associated with the provided + * modifiers and selectors. The groups are generated by combining all possible + * combinations of modifiers with each selector at the end. Selectors are + * prioritized over the quantity of modifiers. For example, `protected abstract + * override get fields();` should prioritize the `'get-method'` group over the + * `'protected-abstract-override-method'` group. + * + * @param props - The properties including selectors, modifiers, and cache. + * @param props.selectors - The list of selectors. + * @param props.modifiers - The list of modifiers. + * @param props.cache - Cache to store computed groups. + * @returns An array of generated group names. + */ +export declare function generatePredefinedGroups({ + selectors, + modifiers, + cache, +}: GeneratePredefinedGroupsParameters): string[] +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/generate-predefined-groups.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/generate-predefined-groups.js new file mode 100644 index 0000000000000000000000000000000000000000..226d6fcb824da21672acd92718eab7be999b716c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/generate-predefined-groups.js @@ -0,0 +1,75 @@ +import { getArrayCombinations } from './get-array-combinations.js' +/** + * Generates an ordered list of group names associated with the provided + * modifiers and selectors. The groups are generated by combining all possible + * combinations of modifiers with each selector at the end. Selectors are + * prioritized over the quantity of modifiers. For example, `protected abstract + * override get fields();` should prioritize the `'get-method'` group over the + * `'protected-abstract-override-method'` group. + * + * @param props - The properties including selectors, modifiers, and cache. + * @param props.selectors - The list of selectors. + * @param props.modifiers - The list of modifiers. + * @param props.cache - Cache to store computed groups. + * @returns An array of generated group names. + */ +function generatePredefinedGroups({ selectors, modifiers, cache }) { + let modifiersAndSelectorsKey = `${modifiers.join('&')}/${selectors.join('&')}` + let cachedValue = cache.get(modifiersAndSelectorsKey) + if (cachedValue) { + return cachedValue + } + let allModifiersCombinations = [] + for (let i = modifiers.length; i > 0; i--) { + allModifiersCombinations.push(...getArrayCombinations(modifiers, i)) + } + let allModifiersCombinationPermutations = allModifiersCombinations.flatMap( + result => getPermutations(result), + ) + let returnValue = [] + for (let selector of selectors) { + returnValue.push( + ...allModifiersCombinationPermutations.map( + modifiersCombinationPermutation => + [...modifiersCombinationPermutation, selector].join('-'), + ), + selector, + ) + } + cache.set(modifiersAndSelectorsKey, returnValue) + return returnValue +} +/** + * Generates all permutations of an array. This allows variations like + * `'abstract-override-protected-get-method'`, + * `'override-protected-abstract-get-method'`, + * `'protected-abstract-override-get-method'`, etc., to be entered by the user + * and always match the same group. Note that this can theoretically cause + * performance issues if too many modifiers are entered at once (e.g., 8 + * modifiers result in 40,320 permutations, 9 in 362,880). + * + * @param elements - The array of elements to permute. + * @returns An array containing all permutations of the input elements. + */ +function getPermutations(elements) { + let result = [] + function swapElements(indexA, indexB) { + let temporaryElement = elements[indexA] + elements[indexA] = elements[indexB] + elements[indexB] = temporaryElement + } + function backtrack(first) { + if (first === elements.length) { + result.push([...elements]) + return + } + for (let i = first; i < elements.length; i++) { + swapElements(first, i) + backtrack(first + 1) + swapElements(first, i) + } + } + backtrack(0) + return result +} +export { generatePredefinedGroups } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-array-combinations.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-array-combinations.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..57d8fa17270ebde56df9290cd68d788e41abdfb6 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-array-combinations.d.ts @@ -0,0 +1,11 @@ +/** + * Generates all possible combinations of a specific size from an array. + * + * @param array - The array of strings to generate combinations from. + * @param number - The number of elements in each combination. + * @returns An array containing all possible combinations. + */ +export declare function getArrayCombinations( + array: string[], + number: number, +): string[][] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-array-combinations.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-array-combinations.js new file mode 100644 index 0000000000000000000000000000000000000000..25fc691e92acf8aa738019e48ce9cc4c0c42f454 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-array-combinations.js @@ -0,0 +1,24 @@ +/** + * Generates all possible combinations of a specific size from an array. + * + * @param array - The array of strings to generate combinations from. + * @param number - The number of elements in each combination. + * @returns An array containing all possible combinations. + */ +function getArrayCombinations(array, number) { + let result = [] + function backtrack(start, comb) { + if (comb.length === number) { + result.push([...comb]) + return + } + for (let i = start; i < array.length; i++) { + comb.push(array[i]) + backtrack(i + 1, comb) + comb.pop() + } + } + backtrack(0, []) + return result +} +export { getArrayCombinations } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-comment-above-that-should-exist.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-comment-above-that-should-exist.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a827db7d781e1ccac4464ec0ff3792c37a134139 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-comment-above-that-should-exist.d.ts @@ -0,0 +1,88 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { CommonGroupsOptions } from '../types/common-groups-options.js' +import { SortingNode } from '../types/sorting-node.js' +/** + * Parameters for checking if a required comment above a node exists. + * + * @template T - Type of the sorting node. + */ +interface GetCommentAboveMissingParameters { + /** + * Configuration options for grouping. + */ + options: Pick< + CommonGroupsOptions, + 'customGroups' | 'groups' + > + /** + * ESLint source code object for accessing comments. + */ + sourceCode: TSESLint.SourceCode + /** + * Index of the group on the left side (previous element). Null if there is + * no previous element. + */ + leftGroupIndex: number | null + /** + * Index of the group on the right side (current element). + */ + rightGroupIndex: number + /** + * The sorting node to check for required comments above. + */ + sortingNode: T +} +/** + * Determines if a comment should exist above a node when transitioning between + * groups. + * + * Checks if the group configuration requires a comment above nodes when they + * are the first element of their group following a different group. This is + * used to enforce comment separators between different sections of sorted + * code. + * + * The function returns null if: + * + * - The left and right elements are in the same or reversed group order + * - The group configuration doesn't require a comment above. + * + * @example + * + * ```ts + * const result = getCommentAboveThatShouldExist({ + * options: { + * groups: [ + * 'external', + * { commentAbove: 'Internal imports' }, + * 'internal', + * ], + * }, + * leftGroupIndex: 0, // 'external' group + * rightGroupIndex: 2, // 'internal' group + * sortingNode: internalImportNode, + * sourceCode, + * }) + * // Returns: { comment: 'Internal imports', exists: false } + * ``` + * + * @template T - Type of the sorting node. + * @param params - Parameters for checking comment requirements. + * @param params.options - Configuration with groups that may require comments. + * @param params.leftGroupIndex - Index of the previous element's group. + * @param params.rightGroupIndex - Index of the current element's group. + * @param params.sortingNode - Node to check for required comments. + * @param params.sourceCode - ESLint source code for accessing comments. + * @returns Object with required comment text and existence status, or null if + * no comment required. + */ +export declare function getCommentAboveThatShouldExist({ + rightGroupIndex, + leftGroupIndex, + sortingNode, + sourceCode, + options, +}: GetCommentAboveMissingParameters): { + comment: string + exists: boolean +} | null +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-comment-above-that-should-exist.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-comment-above-that-should-exist.js new file mode 100644 index 0000000000000000000000000000000000000000..7e49150d277a2e09b7b8b63ce504ef971427c3fc --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-comment-above-that-should-exist.js @@ -0,0 +1,75 @@ +import { isGroupWithOverridesOption } from './is-group-with-overrides-option.js' +import { getCommentsBefore } from './get-comments-before.js' +/** + * Determines if a comment should exist above a node when transitioning between + * groups. + * + * Checks if the group configuration requires a comment above nodes when they + * are the first element of their group following a different group. This is + * used to enforce comment separators between different sections of sorted + * code. + * + * The function returns null if: + * + * - The left and right elements are in the same or reversed group order + * - The group configuration doesn't require a comment above. + * + * @example + * + * ```ts + * const result = getCommentAboveThatShouldExist({ + * options: { + * groups: [ + * 'external', + * { commentAbove: 'Internal imports' }, + * 'internal', + * ], + * }, + * leftGroupIndex: 0, // 'external' group + * rightGroupIndex: 2, // 'internal' group + * sortingNode: internalImportNode, + * sourceCode, + * }) + * // Returns: { comment: 'Internal imports', exists: false } + * ``` + * + * @template T - Type of the sorting node. + * @param params - Parameters for checking comment requirements. + * @param params.options - Configuration with groups that may require comments. + * @param params.leftGroupIndex - Index of the previous element's group. + * @param params.rightGroupIndex - Index of the current element's group. + * @param params.sortingNode - Node to check for required comments. + * @param params.sourceCode - ESLint source code for accessing comments. + * @returns Object with required comment text and existence status, or null if + * no comment required. + */ +function getCommentAboveThatShouldExist({ + rightGroupIndex, + leftGroupIndex, + sortingNode, + sourceCode, + options, +}) { + if (leftGroupIndex !== null && leftGroupIndex >= rightGroupIndex) { + return null + } + let rightGroup = options.groups[rightGroupIndex] + if (!rightGroup || !isGroupWithOverridesOption(rightGroup)) { + return null + } + let rightGroupCommentAbove = rightGroup.commentAbove + if (!rightGroupCommentAbove) { + return null + } + return { + comment: rightGroupCommentAbove, + exists: !!getCommentsBefore({ + node: sortingNode.node, + sourceCode, + }).find(comment => commentMatches(comment.value, rightGroupCommentAbove)), + } +} +function commentMatches(comment, expected) { + return comment.toLowerCase().includes(expected.toLowerCase().trim()) +} +export { getCommentAboveThatShouldExist } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-comments-before.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-comments-before.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6e4b999feda76a28f69898936af1e1e6fb4dfd11 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-comments-before.d.ts @@ -0,0 +1,24 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { TSESTree } from '@typescript-eslint/types' +interface GetCommentsBeforeParameters { + tokenValueToIgnoreBefore?: string + sourceCode: TSESLint.SourceCode + node: TSESTree.Node +} +/** + * Returns a list of comments before a given node, excluding ones that are right + * after code. Includes comment blocks, ignore shebang comments. + * + * @param params - Parameters object. + * @param params.node - The node to get comments before. + * @param params.sourceCode - The source code object. + * @param [params.tokenValueToIgnoreBefore] - Allows the following token to + * directly precede the node. + * @returns An array of comments before the given node. + */ +export declare function getCommentsBefore({ + tokenValueToIgnoreBefore, + sourceCode, + node, +}: GetCommentsBeforeParameters): TSESTree.Comment[] +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-comments-before.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-comments-before.js new file mode 100644 index 0000000000000000000000000000000000000000..95ce1dccadbc2898e3de684b6a26a42a40e0c7e6 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-comments-before.js @@ -0,0 +1,37 @@ +/** + * Returns a list of comments before a given node, excluding ones that are right + * after code. Includes comment blocks, ignore shebang comments. + * + * @param params - Parameters object. + * @param params.node - The node to get comments before. + * @param params.sourceCode - The source code object. + * @param [params.tokenValueToIgnoreBefore] - Allows the following token to + * directly precede the node. + * @returns An array of comments before the given node. + */ +function getCommentsBefore({ tokenValueToIgnoreBefore, sourceCode, node }) { + let commentsBefore = getRelevantCommentsBeforeNodeOrToken(sourceCode, node) + let tokenBeforeNode = sourceCode.getTokenBefore(node) + if ( + !tokenValueToIgnoreBefore || + commentsBefore.length > 0 || + tokenBeforeNode?.value !== tokenValueToIgnoreBefore + ) { + return commentsBefore + } + return getRelevantCommentsBeforeNodeOrToken(sourceCode, tokenBeforeNode) +} +function getRelevantCommentsBeforeNodeOrToken(source, node) { + return source + .getCommentsBefore(node) + .filter(comment => !isShebangComment(comment)) + .filter(comment => { + return ( + source.getTokenBefore(comment)?.loc.end.line !== comment.loc.start.line + ) + }) +} +function isShebangComment(comment) { + return comment.type === 'Shebang' || comment.type === 'Hashbang' +} +export { getCommentsBefore } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-decorator-name.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-decorator-name.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a37d1d2c222f6f92b6e5f851125487fcc9168c13 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-decorator-name.d.ts @@ -0,0 +1,45 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +/** + * Extracts the name of a decorator from its AST node. + * + * Processes the decorator text to extract just the name portion, removing the + * '@' prefix if present and any parameters or arguments that follow the name. + * This is useful for sorting and matching decorators by their base name. + * + * @example + * + * ```ts + * // Simple decorator + * getDecoratorName({ sourceCode, decorator: @Component }); + * // Returns: 'Component' + * ``` + * + * @example + * + * ```ts + * // Decorator with parameters + * getDecoratorName({ sourceCode, decorator: @Injectable({ providedIn: 'root' }) }); + * // Returns: 'Injectable' + * ``` + * + * @example + * + * ```ts + * // Namespaced decorator + * getDecoratorName({ sourceCode, decorator: @angular.Component() }); + * // Returns: 'angular.Component' + * ``` + * + * @param params - Parameters object. + * @param params.sourceCode - ESLint source code object for text extraction. + * @param params.decorator - Decorator AST node to extract name from. + * @returns The decorator name without '@' prefix and parameters. + */ +export declare function getDecoratorName({ + sourceCode, + decorator, +}: { + sourceCode: TSESLint.SourceCode + decorator: TSESTree.Decorator +}): string diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-decorator-name.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-decorator-name.js new file mode 100644 index 0000000000000000000000000000000000000000..5c81500df23b13267bb4024c2d148dbdc4773919 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-decorator-name.js @@ -0,0 +1,44 @@ +/** + * Extracts the name of a decorator from its AST node. + * + * Processes the decorator text to extract just the name portion, removing the + * '@' prefix if present and any parameters or arguments that follow the name. + * This is useful for sorting and matching decorators by their base name. + * + * @example + * + * ```ts + * // Simple decorator + * getDecoratorName({ sourceCode, decorator: @Component }); + * // Returns: 'Component' + * ``` + * + * @example + * + * ```ts + * // Decorator with parameters + * getDecoratorName({ sourceCode, decorator: @Injectable({ providedIn: 'root' }) }); + * // Returns: 'Injectable' + * ``` + * + * @example + * + * ```ts + * // Namespaced decorator + * getDecoratorName({ sourceCode, decorator: @angular.Component() }); + * // Returns: 'angular.Component' + * ``` + * + * @param params - Parameters object. + * @param params.sourceCode - ESLint source code object for text extraction. + * @param params.decorator - Decorator AST node to extract name from. + * @returns The decorator name without '@' prefix and parameters. + */ +function getDecoratorName({ sourceCode, decorator }) { + let fullName = sourceCode.getText(decorator) + if (fullName.startsWith('@')) { + fullName = fullName.slice(1) + } + return fullName.split('(', 1)[0] +} +export { getDecoratorName } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-enum-members.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-enum-members.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..04fbb96b853d9f9b54e856260246ebd06e72e1bb --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-enum-members.d.ts @@ -0,0 +1,28 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Retrieves enum members from a TypeScript enum declaration node. + * + * Handles AST shape changes in TS-ESTree `@typescript-eslint/types`: + * + * - Newer parser versions wrap enum members in `body.members` and deprecate + * `members` on the enum node. + * - Older parser versions expose members directly on the enum node as `members`. + * The fallback keeps backward compatibility with older parser releases. + * + * @example + * + * ```ts + * enum Color { + * Red = 'RED', + * Green = 'GREEN', + * Blue = 'BLUE', + * } + * // Returns array of three TSEnumMember nodes + * ``` + * + * @param value - TypeScript enum declaration AST node. + * @returns Array of enum member nodes. + */ +export declare function getEnumMembers( + value: TSESTree.TSEnumDeclaration, +): TSESTree.TSEnumMember[] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-enum-members.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-enum-members.js new file mode 100644 index 0000000000000000000000000000000000000000..242bea427cc82b52a6b7fe9fa6aac825b61430bf --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-enum-members.js @@ -0,0 +1,28 @@ +/** + * Retrieves enum members from a TypeScript enum declaration node. + * + * Handles AST shape changes in TS-ESTree `@typescript-eslint/types`: + * + * - Newer parser versions wrap enum members in `body.members` and deprecate + * `members` on the enum node. + * - Older parser versions expose members directly on the enum node as `members`. + * The fallback keeps backward compatibility with older parser releases. + * + * @example + * + * ```ts + * enum Color { + * Red = 'RED', + * Green = 'GREEN', + * Blue = 'BLUE', + * } + * // Returns array of three TSEnumMember nodes + * ``` + * + * @param value - TypeScript enum declaration AST node. + * @returns Array of enum member nodes. + */ +function getEnumMembers(value) { + return value.body?.members ?? value.members +} +export { getEnumMembers } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-eslint-disabled-lines.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-eslint-disabled-lines.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eeb48eb694f9d9fb15a87e00614a18b05d35897d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-eslint-disabled-lines.d.ts @@ -0,0 +1,47 @@ +import { TSESLint } from '@typescript-eslint/utils' +/** + * Determines which lines have the specified ESLint rule disabled via comments. + * + * Parses ESLint disable comments in the source code to identify lines where a + * specific rule should not be enforced. Handles all ESLint disable directives: + * + * - `eslint-disable-next-line` - Disables the rule for the next line + * - `eslint-disable-line` - Disables the rule for the current line + * - `eslint-disable` - Disables the rule from this point forward + * - `eslint-enable` - Re-enables the rule after a previous disable. + * + * The function correctly handles: + * + * - Rule-specific disables (e.g., `eslint-disable-next-line rule-name`) + * - Global disables (e.g., `eslint-disable-next-line` without specific rules) + * - Nested disable/enable pairs. + * + * @example + * + * ```ts + * // Source code with disable comments: + * // eslint-disable-next-line perfectionist/sort-imports + * import { z } from 'zod' + * import { a } from 'a' + * + * // eslint-disable perfectionist/sort-imports + * import { y } from 'y' + * import { b } from 'b' + * // eslint-enable perfectionist/sort-imports + * + * getEslintDisabledLines({ + * sourceCode, + * ruleName: 'perfectionist/sort-imports', + * }) + * // Returns: [2, 5, 6] (lines where the rule is disabled) + * ``` + * + * @param props - Configuration object. + * @param props.sourceCode - ESLint source code object containing comments. + * @param props.ruleName - Name of the rule to check for disable directives. + * @returns Array of line numbers (1-indexed) where the rule is disabled. + */ +export declare function getEslintDisabledLines(props: { + sourceCode: TSESLint.SourceCode + ruleName: string +}): number[] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-eslint-disabled-lines.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-eslint-disabled-lines.js new file mode 100644 index 0000000000000000000000000000000000000000..b0070d4166d456fd7c252444106766aa4a5f1729 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-eslint-disabled-lines.js @@ -0,0 +1,113 @@ +import { UnreachableCaseError } from './unreachable-case-error.js' +import { getEslintDisabledRules } from './get-eslint-disabled-rules.js' +/** + * Determines which lines have the specified ESLint rule disabled via comments. + * + * Parses ESLint disable comments in the source code to identify lines where a + * specific rule should not be enforced. Handles all ESLint disable directives: + * + * - `eslint-disable-next-line` - Disables the rule for the next line + * - `eslint-disable-line` - Disables the rule for the current line + * - `eslint-disable` - Disables the rule from this point forward + * - `eslint-enable` - Re-enables the rule after a previous disable. + * + * The function correctly handles: + * + * - Rule-specific disables (e.g., `eslint-disable-next-line rule-name`) + * - Global disables (e.g., `eslint-disable-next-line` without specific rules) + * - Nested disable/enable pairs. + * + * @example + * + * ```ts + * // Source code with disable comments: + * // eslint-disable-next-line perfectionist/sort-imports + * import { z } from 'zod' + * import { a } from 'a' + * + * // eslint-disable perfectionist/sort-imports + * import { y } from 'y' + * import { b } from 'b' + * // eslint-enable perfectionist/sort-imports + * + * getEslintDisabledLines({ + * sourceCode, + * ruleName: 'perfectionist/sort-imports', + * }) + * // Returns: [2, 5, 6] (lines where the rule is disabled) + * ``` + * + * @param props - Configuration object. + * @param props.sourceCode - ESLint source code object containing comments. + * @param props.ruleName - Name of the rule to check for disable directives. + * @returns Array of line numbers (1-indexed) where the rule is disabled. + */ +function getEslintDisabledLines(props) { + let { sourceCode, ruleName } = props + let returnValue = [] + let lineRulePermanentlyDisabled = null + for (let comment of sourceCode.getAllComments()) { + let eslintDisabledRules = getEslintDisabledRules(comment.value) + if (!eslintDisabledRules) { + continue + } + /* v8 ignore next 3 -- @preserve Hard to test this false branch. */ + if (!( + eslintDisabledRules.rules === 'all' || + eslintDisabledRules.rules.includes(ruleName) + )) { + continue + } + switch (eslintDisabledRules.eslintDisableDirective) { + case 'eslint-disable-next-line': + returnValue.push(comment.loc.end.line + 1) + continue + case 'eslint-disable-line': + returnValue.push(comment.loc.start.line) + continue + case 'eslint-disable': + lineRulePermanentlyDisabled ??= comment.loc.start.line + break + case 'eslint-enable': + /* v8 ignore next -- @preserve Hard to cover in test without raising another ESLint error. */ + if (!lineRulePermanentlyDisabled) { + continue + } + returnValue.push( + ...createArrayFromTo( + lineRulePermanentlyDisabled + 1, + comment.loc.start.line, + ), + ) + lineRulePermanentlyDisabled = null + break + /* v8 ignore next 2 -- @preserve Exhaustive guard. */ + default: + throw new UnreachableCaseError( + eslintDisabledRules.eslintDisableDirective, + ) + } + } + return returnValue +} +/** + * Creates an array of consecutive integers from start to end (inclusive). + * + * Helper function to generate an array of line numbers for ranges disabled by + * eslint-disable/eslint-enable comment pairs. + * + * @example + * + * ```ts + * createArrayFromTo(5, 8) + * // Returns: [5, 6, 7, 8] + * ``` + * + * @param i - Starting number (inclusive). + * @param index - Ending number (inclusive). + * @returns Array of consecutive integers from i to index. + */ +function createArrayFromTo(i, index) { + return Array.from({ length: index - i + 1 }, (_, item) => i + item) +} +export { getEslintDisabledLines } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-eslint-disabled-rules.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-eslint-disabled-rules.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6655944de4136dcef8b9bb50b58cfaee28690a33 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-eslint-disabled-rules.d.ts @@ -0,0 +1,57 @@ +/** + * Array of all ESLint disable directive types. Used to identify and parse + * ESLint disable comments in source code. + */ +declare let eslintDisableDirectives: readonly [ + 'eslint-disable', + 'eslint-enable', + 'eslint-disable-line', + 'eslint-disable-next-line', +] +/** + * Type representing one of the ESLint disable directive types. Can be + * 'eslint-disable', 'eslint-enable', 'eslint-disable-line', or + * 'eslint-disable-next-line'. + */ +type EslintDisableDirective = (typeof eslintDisableDirectives)[number] +/** + * Parses an ESLint disable comment to extract the directive type and affected + * rules. + * + * Analyzes comment text to determine if it contains an ESLint disable directive + * and which rules are affected. Returns null if the comment is not a valid + * ESLint disable directive. + * + * @example + * + * ```ts + * getEslintDisabledRules('eslint-disable') + * // Returns: { eslintDisableDirective: 'eslint-disable', rules: 'all' } + * ``` + * + * @example + * + * ```ts + * getEslintDisabledRules('eslint-disable-next-line no-console, no-alert') + * // Returns: { + * // eslintDisableDirective: 'eslint-disable-next-line', + * // rules: ['no-console', 'no-alert'] + * // } + * ``` + * + * @example + * + * ```ts + * getEslintDisabledRules('regular comment') + * // Returns: null + * ``` + * + * @param comment - Comment text to parse (without comment delimiters). + * @returns Object containing directive type and affected rules, or null if not + * a disable comment. + */ +export declare function getEslintDisabledRules(comment: string): { + eslintDisableDirective: EslintDisableDirective + rules: string[] | 'all' +} | null +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-eslint-disabled-rules.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-eslint-disabled-rules.js new file mode 100644 index 0000000000000000000000000000000000000000..c10d8e6653011a82cefb75fd3d71586a2d0b6c36 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-eslint-disabled-rules.js @@ -0,0 +1,116 @@ +/** + * Array of all ESLint disable directive types. Used to identify and parse + * ESLint disable comments in source code. + */ +var eslintDisableDirectives = [ + 'eslint-disable', + 'eslint-enable', + 'eslint-disable-line', + 'eslint-disable-next-line', +] +/** + * Parses an ESLint disable comment to extract the directive type and affected + * rules. + * + * Analyzes comment text to determine if it contains an ESLint disable directive + * and which rules are affected. Returns null if the comment is not a valid + * ESLint disable directive. + * + * @example + * + * ```ts + * getEslintDisabledRules('eslint-disable') + * // Returns: { eslintDisableDirective: 'eslint-disable', rules: 'all' } + * ``` + * + * @example + * + * ```ts + * getEslintDisabledRules('eslint-disable-next-line no-console, no-alert') + * // Returns: { + * // eslintDisableDirective: 'eslint-disable-next-line', + * // rules: ['no-console', 'no-alert'] + * // } + * ``` + * + * @example + * + * ```ts + * getEslintDisabledRules('regular comment') + * // Returns: null + * ``` + * + * @param comment - Comment text to parse (without comment delimiters). + * @returns Object containing directive type and affected rules, or null if not + * a disable comment. + */ +function getEslintDisabledRules(comment) { + for (let eslintDisableDirective of eslintDisableDirectives) { + let disabledRules = getEslintDisabledRulesByType( + comment, + eslintDisableDirective, + ) + if (disabledRules) { + return { + eslintDisableDirective, + rules: disabledRules, + } + } + } + return null +} +/** + * Extracts disabled rules from a comment for a specific ESLint directive type. + * + * Attempts to parse the comment as the specified ESLint disable directive. + * Returns the list of disabled rules if the comment matches the directive, + * 'all' if no specific rules are mentioned (global disable), or null if the + * comment doesn't match the directive pattern. + * + * @example + * + * ```ts + * getEslintDisabledRulesByType('eslint-disable', 'eslint-disable') + * // Returns: 'all' + * ``` + * + * @example + * + * ```ts + * getEslintDisabledRulesByType( + * 'eslint-disable-line rule1, rule2', + * 'eslint-disable-line', + * ) + * // Returns: ['rule1', 'rule2'] + * ``` + * + * @example + * + * ```ts + * getEslintDisabledRulesByType( + * 'eslint-disable-line rule1', + * 'eslint-disable-next-line', + * ) + * // Returns: null (wrong directive type) + * ``` + * + * @param comment - Comment text to parse. + * @param eslintDisableDirective - Specific directive type to match against. + * @returns Array of rule names, 'all' for global disable, or null if no match. + */ +function getEslintDisabledRulesByType(comment, eslintDisableDirective) { + let trimmedCommentValue = comment.trim() + if (eslintDisableDirective === trimmedCommentValue) { + return 'all' + } + let regexp = new RegExp(String.raw`^${eslintDisableDirective} ((?:.|\s)*)$`) + let disableRulesMatchValue = trimmedCommentValue.match(regexp)?.[1] + if (!disableRulesMatchValue) { + return null + } + return disableRulesMatchValue + .split(',') + .map(rule => rule.trim()) + .filter(rule => !!rule) +} +export { getEslintDisabledRules } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-group-index.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-group-index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..48b523fdc7cff8bed1f75780a4fcfa8630d6b043 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-group-index.d.ts @@ -0,0 +1,41 @@ +import { GroupsOptions } from '../types/common-groups-options.js' +import { SortingNode } from '../types/sorting-node.js' +/** + * Type representing a single group or an array of group names. Used in group + * configuration where elements can belong to multiple subgroups. + */ +type Group = GroupsOptions[number] +/** + * Determines the index of the group that a node belongs to. + * + * Searches through the groups array to find which group contains the node. + * Supports simple groups (string), subgroups (array of strings) and objects + * containing a `group` property. For subgroups, the node matches if its group + * is any element in the array. + * + * The function returns the index of the matching group. If no group matches, it + * returns the length of the groups array, which conventionally represents the + * "unknown" group and ensures such nodes are sorted last. + * + * @example + * + * ```ts + * const groups = ['imports', ['types', 'interfaces'], 'functions'] + * const node1 = { group: 'imports', name: 'lodash' } + * const node2 = { group: 'types', name: 'User' } + * const node3 = { group: 'unknown-group', name: 'misc' } + * + * getGroupIndex(groups, node1) // Returns: 0 + * getGroupIndex(groups, node2) // Returns: 1 (matches subgroup) + * getGroupIndex(groups, node3) // Returns: 3 (groups.length, unknown group) + * ``` + * + * @param groups - Array of group configurations (strings or arrays of strings). + * @param node - Sorting node with a group property to match. + * @returns Index of the matching group, or groups.length if no match found. + */ +export declare function getGroupIndex( + groups: Group[], + node: SortingNode, +): number +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-group-index.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-group-index.js new file mode 100644 index 0000000000000000000000000000000000000000..a5d3659202f603abf8a8bd7b5952ed846385d8de --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-group-index.js @@ -0,0 +1,62 @@ +import { isGroupWithOverridesOption } from './is-group-with-overrides-option.js' +import { isNewlinesBetweenOption } from './is-newlines-between-option.js' +import { UnreachableCaseError } from './unreachable-case-error.js' +/** + * Determines the index of the group that a node belongs to. + * + * Searches through the groups array to find which group contains the node. + * Supports simple groups (string), subgroups (array of strings) and objects + * containing a `group` property. For subgroups, the node matches if its group + * is any element in the array. + * + * The function returns the index of the matching group. If no group matches, it + * returns the length of the groups array, which conventionally represents the + * "unknown" group and ensures such nodes are sorted last. + * + * @example + * + * ```ts + * const groups = ['imports', ['types', 'interfaces'], 'functions'] + * const node1 = { group: 'imports', name: 'lodash' } + * const node2 = { group: 'types', name: 'User' } + * const node3 = { group: 'unknown-group', name: 'misc' } + * + * getGroupIndex(groups, node1) // Returns: 0 + * getGroupIndex(groups, node2) // Returns: 1 (matches subgroup) + * getGroupIndex(groups, node3) // Returns: 3 (groups.length, unknown group) + * ``` + * + * @param groups - Array of group configurations (strings or arrays of strings). + * @param node - Sorting node with a group property to match. + * @returns Index of the matching group, or groups.length if no match found. + */ +function getGroupIndex(groups, node) { + for (let max = groups.length, i = 0; i < max; i++) { + let currentGroup = groups[i] + if (doesGroupMatch(currentGroup, node.group)) { + return i + } + } + return groups.length +} +function doesGroupMatch(group, groupName) { + if (typeof group === 'string' || Array.isArray(group)) { + return doesStringGroupMatch(group, groupName) + } + if (isGroupWithOverridesOption(group)) { + return doesStringGroupMatch(group.group, groupName) + } + /* v8 ignore else -- @preserve Exhaustive guard: other directives are filtered out earlier. */ + if (isNewlinesBetweenOption(group)) { + return false + } + /* v8 ignore next -- @preserve Exhaustive guard: other directives are filtered out earlier. */ + throw new UnreachableCaseError(group) +} +function doesStringGroupMatch(group, groupName) { + if (typeof group === 'string') { + return group === groupName + } + return group.includes(groupName) +} +export { getGroupIndex } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-lines-between.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-lines-between.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a4a4fab6117eae253f1e17714ec092092cb56dea --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-lines-between.d.ts @@ -0,0 +1,44 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { SortingNode } from '../types/sorting-node.js' +/** + * Counts the number of empty lines between two AST nodes. + * + * Extracts the lines between the end of the left node and the start of the + * right node, then counts only the completely empty lines (containing only + * whitespace). This is used to determine if nodes are separated by newlines and + * to enforce newline formatting rules. + * + * @example + * + * ```ts + * // Source code: + * // const a = 1; + * // + * // const b = 2; + * + * getLinesBetween(sourceCode, nodeA, nodeB) + * // Returns: 1 (one empty line between nodes) + * ``` + * + * @example + * + * ```ts + * // Source code: + * // const a = 1; + * // // comment + * // const b = 2; + * + * getLinesBetween(sourceCode, nodeA, nodeB) + * // Returns: 0 (no empty lines, comment line is not empty) + * ``` + * + * @param source - ESLint source code object containing the lines array. + * @param left - Node or object containing the left/first node. + * @param right - Node or object containing the right/second node. + * @returns Number of empty lines between the two nodes. + */ +export declare function getLinesBetween( + source: TSESLint.SourceCode, + left: Pick, + right: Pick, +): number diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-lines-between.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-lines-between.js new file mode 100644 index 0000000000000000000000000000000000000000..8949b853aa9244c0d5a11d52583ee9ba836a718f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-lines-between.js @@ -0,0 +1,43 @@ +/** + * Counts the number of empty lines between two AST nodes. + * + * Extracts the lines between the end of the left node and the start of the + * right node, then counts only the completely empty lines (containing only + * whitespace). This is used to determine if nodes are separated by newlines and + * to enforce newline formatting rules. + * + * @example + * + * ```ts + * // Source code: + * // const a = 1; + * // + * // const b = 2; + * + * getLinesBetween(sourceCode, nodeA, nodeB) + * // Returns: 1 (one empty line between nodes) + * ``` + * + * @example + * + * ```ts + * // Source code: + * // const a = 1; + * // // comment + * // const b = 2; + * + * getLinesBetween(sourceCode, nodeA, nodeB) + * // Returns: 0 (no empty lines, comment line is not empty) + * ``` + * + * @param source - ESLint source code object containing the lines array. + * @param left - Node or object containing the left/first node. + * @param right - Node or object containing the right/second node. + * @returns Number of empty lines between the two nodes. + */ +function getLinesBetween(source, left, right) { + return source.lines + .slice(left.node.loc.end.line, right.node.loc.start.line - 1) + .filter(line => line.trim().length === 0).length +} +export { getLinesBetween } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-newlines-between-errors.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-newlines-between-errors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..320be66b350621772e0b998b118b2508941970d6 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-newlines-between-errors.d.ts @@ -0,0 +1,126 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { + NewlinesBetweenOption, + CommonGroupsOptions, +} from '../types/common-groups-options.js' +import { SortingNode } from '../types/sorting-node.js' +/** + * Function type for customizing newlines between specific nodes. + * + * Allows overriding the computed newlines requirement based on the specific + * nodes being compared. Can return 'ignore' to skip newline checking or a + * number to specify exact newlines required. + * + * @template T - Type of the sorting node. + * @param props - Properties for computing newlines. + * @param props.computedNewlinesBetween - Default computed newlines requirement. + * @param props.left - Left/first node. + * @param props.right - Right/second node. + * @returns Number of required newlines or 'ignore' to skip checking. + */ +export type NewlinesBetweenValueGetter = (props: { + computedNewlinesBetween: NewlinesBetweenOption + right: T + left: T +}) => NewlinesBetweenOption +/** + * Parameters for checking newlines between nodes and generating errors. + * + * @template MessageIds - Type of error message identifiers. + * @template T - Type of the sorting node. + */ +interface GetNewlinesBetweenErrorsParameters< + MessageIds extends string, + T extends SortingNode, +> { + /** + * Optional function to customize newlines between specific nodes. + */ + newlinesBetweenValueGetter?: NewlinesBetweenValueGetter + /** + * Configuration options for newlines and groups. + */ + options: CommonGroupsOptions + /** + * ESLint source code object for accessing lines. + */ + sourceCode: TSESLint.SourceCode + /** + * Error message ID for missing required newlines. + */ + missedSpacingError: MessageIds + /** + * Error message ID for extra unwanted newlines. + */ + extraSpacingError: MessageIds + /** + * Group index of the right/second node. + */ + rightGroupIndex: number + /** + * Group index of the left/first node. + */ + leftGroupIndex: number + /** + * Right/second node in the comparison. + */ + right: T + /** + * Left/first node in the comparison. + */ + left: T +} +/** + * Checks if the newlines between two nodes match the required configuration. + * + * Validates the number of empty lines between two nodes against the expected + * newlines based on their group indices and configuration. Generates + * appropriate error messages when the actual newlines don't match the + * requirement. + * + * The function returns no errors if: + * + * - The left node's group index is greater than the right's (wrong order) + * - The nodes are in different partitions + * - The newlines configuration is set to 'ignore' + * - The actual newlines match the expected newlines. + * + * @example + * + * ```ts + * // Configuration requires 1 newline between different groups + * const errors = getNewlinesBetweenErrors({ + * options: { newlinesBetween: 1, groups: ['imports', 'types'] }, + * leftGroupIndex: 0, // imports group + * rightGroupIndex: 1, // types group + * left: importNode, + * right: typeNode, + * sourceCode, + * missedSpacingError: 'missedNewline', + * extraSpacingError: 'extraNewline', + * }) + * // If no newline between nodes: Returns ['missedNewline'] + * // If 2+ newlines between nodes: Returns ['extraNewline'] + * // If exactly 1 newline: Returns [] + * ``` + * + * @template MessageIds - Type of error message identifiers. + * @template T - Type of the sorting node. + * @param params - Parameters for newline checking. + * @returns Array of error message IDs (empty if no errors). + */ +export declare function getNewlinesBetweenErrors< + MessageIds extends string, + T extends SortingNode, +>({ + newlinesBetweenValueGetter, + missedSpacingError, + extraSpacingError, + rightGroupIndex, + leftGroupIndex, + sourceCode, + options, + right, + left, +}: GetNewlinesBetweenErrorsParameters): MessageIds[] +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-newlines-between-errors.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-newlines-between-errors.js new file mode 100644 index 0000000000000000000000000000000000000000..5ec2b297815ce4b58d8a1aa084aeb1bc61061d1d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-newlines-between-errors.js @@ -0,0 +1,82 @@ +import { getNewlinesBetweenOption } from './get-newlines-between-option.js' +import { getLinesBetween } from './get-lines-between.js' +/** + * Checks if the newlines between two nodes match the required configuration. + * + * Validates the number of empty lines between two nodes against the expected + * newlines based on their group indices and configuration. Generates + * appropriate error messages when the actual newlines don't match the + * requirement. + * + * The function returns no errors if: + * + * - The left node's group index is greater than the right's (wrong order) + * - The nodes are in different partitions + * - The newlines configuration is set to 'ignore' + * - The actual newlines match the expected newlines. + * + * @example + * + * ```ts + * // Configuration requires 1 newline between different groups + * const errors = getNewlinesBetweenErrors({ + * options: { newlinesBetween: 1, groups: ['imports', 'types'] }, + * leftGroupIndex: 0, // imports group + * rightGroupIndex: 1, // types group + * left: importNode, + * right: typeNode, + * sourceCode, + * missedSpacingError: 'missedNewline', + * extraSpacingError: 'extraNewline', + * }) + * // If no newline between nodes: Returns ['missedNewline'] + * // If 2+ newlines between nodes: Returns ['extraNewline'] + * // If exactly 1 newline: Returns [] + * ``` + * + * @template MessageIds - Type of error message identifiers. + * @template T - Type of the sorting node. + * @param params - Parameters for newline checking. + * @returns Array of error message IDs (empty if no errors). + */ +function getNewlinesBetweenErrors({ + newlinesBetweenValueGetter, + missedSpacingError, + extraSpacingError, + rightGroupIndex, + leftGroupIndex, + sourceCode, + options, + right, + left, +}) { + if ( + leftGroupIndex > rightGroupIndex || + left.partitionId !== right.partitionId + ) { + return [] + } + let newlinesBetween = getNewlinesBetweenOption({ + nextNodeGroupIndex: rightGroupIndex, + nodeGroupIndex: leftGroupIndex, + options, + }) + newlinesBetween = + newlinesBetweenValueGetter?.({ + computedNewlinesBetween: newlinesBetween, + right, + left, + }) ?? newlinesBetween + if (newlinesBetween === 'ignore') { + return [] + } + let numberOfEmptyLinesBetween = getLinesBetween(sourceCode, left, right) + if (numberOfEmptyLinesBetween < newlinesBetween) { + return [missedSpacingError] + } + if (numberOfEmptyLinesBetween > newlinesBetween) { + return [extraSpacingError] + } + return [] +} +export { getNewlinesBetweenErrors } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-newlines-between-option.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-newlines-between-option.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..494c1d2ca0f67fb9543117614e1c4fa508a5a2bc --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-newlines-between-option.d.ts @@ -0,0 +1,43 @@ +import { + NewlinesBetweenOption, + CommonGroupsOptions, +} from '../types/common-groups-options.js' +/** + * Parameters for determining newlines requirement between nodes. + * + * Contains group indices and configuration options needed to calculate the + * required number of newlines between two nodes. + */ +export interface GetNewlinesBetweenOptionParameters { + /** + * Configuration options for newlines and groups. + */ + options: CommonGroupsOptions + /** + * Group index of the next/second node. + */ + nextNodeGroupIndex: number + /** + * Group index of the current/first node. + */ + nodeGroupIndex: number +} +/** + * Get the `newlinesBetween` option to use between two consecutive nodes. The + * result is based on the global `newlinesBetween` option and the custom groups, + * which can override the global option. + * + * - If the two nodes are in the same custom group, the `newlinesInside` option of + * the group is used. + * + * @param props - The function arguments. + * @param props.nextNodeGroupIndex - The next node index to sort. + * @param props.nodeGroupIndex - The current node index to sort. + * @param props.options - Newlines between related options. + * @returns - The `newlinesBetween` option to use. + */ +export declare function getNewlinesBetweenOption({ + nextNodeGroupIndex, + nodeGroupIndex, + options, +}: GetNewlinesBetweenOptionParameters): NewlinesBetweenOption diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-newlines-between-option.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-newlines-between-option.js new file mode 100644 index 0000000000000000000000000000000000000000..82f5214c549011669072f5d6cfa042ec67b8912c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-newlines-between-option.js @@ -0,0 +1,145 @@ +import { isGroupWithOverridesOption } from './is-group-with-overrides-option.js' +import { isNewlinesBetweenOption } from './is-newlines-between-option.js' +import { computeGroupName } from './compute-group-name.js' +/** + * Get the `newlinesBetween` option to use between two consecutive nodes. The + * result is based on the global `newlinesBetween` option and the custom groups, + * which can override the global option. + * + * - If the two nodes are in the same custom group, the `newlinesInside` option of + * the group is used. + * + * @param props - The function arguments. + * @param props.nextNodeGroupIndex - The next node index to sort. + * @param props.nodeGroupIndex - The current node index to sort. + * @param props.options - Newlines between related options. + * @returns - The `newlinesBetween` option to use. + */ +function getNewlinesBetweenOption({ + nextNodeGroupIndex, + nodeGroupIndex, + options, +}) { + if (nodeGroupIndex === nextNodeGroupIndex) { + return computeNewlinesInsideOption({ + groupIndex: nodeGroupIndex, + options, + }) + } + if (nextNodeGroupIndex >= nodeGroupIndex + 2) { + return computeNewlinesBetweenOptionForDifferentGroups({ + nextNodeGroupIndex, + nodeGroupIndex, + options, + }) + } + return options.newlinesBetween +} +function computeNewlinesBetweenOptionForDifferentGroups({ + nextNodeGroupIndex, + nodeGroupIndex, + options, +}) { + if (nextNodeGroupIndex === nodeGroupIndex + 2) { + let groupBetween = options.groups[nodeGroupIndex + 1] + if (isNewlinesBetweenOption(groupBetween)) { + return groupBetween.newlinesBetween + } + return options.newlinesBetween + } + let groupsWithAllNewlinesBetween = buildGroupsWithAllNewlinesBetween( + options.groups.slice(nodeGroupIndex, nextNodeGroupIndex + 1), + options.newlinesBetween, + ) + let newlinesBetweenOptions = new Set( + groupsWithAllNewlinesBetween + .filter(isNewlinesBetweenOption) + .map(group => group.newlinesBetween), + ) + let numberNewlinesBetween = [...newlinesBetweenOptions].filter( + option => typeof option === 'number', + ) + let maxNewlinesBetween = + numberNewlinesBetween.length > 0 ? Math.max(...numberNewlinesBetween) : null + if (maxNewlinesBetween !== null && maxNewlinesBetween >= 1) { + return maxNewlinesBetween + } + if (newlinesBetweenOptions.has('ignore')) { + return 'ignore' + } + return 0 +} +function computeNewlinesInsideOption({ groupIndex, options }) { + let globalNewlinesInsideOption = computeGlobalNewlinesInsideOption() + let group = options.groups[groupIndex] + if (!group) { + return globalNewlinesInsideOption + } + let groupName = computeGroupName(group) + let nodeCustomGroup = options.customGroups.find( + customGroup => customGroup.groupName === groupName, + ) + let groupOverrideNewlinesInside = + isGroupWithOverridesOption(group) ? group.newlinesInside : null + return ( + nodeCustomGroup?.newlinesInside ?? + groupOverrideNewlinesInside ?? + globalNewlinesInsideOption + ) + function computeGlobalNewlinesInsideOption() { + switch (options.newlinesInside) { + case 'newlinesBetween': + return options.newlinesBetween === 'ignore' ? 'ignore' : 0 + case 'ignore': + return 'ignore' + default: + return options.newlinesInside + } + } +} +/** + * Inserts newlines settings between groups that don't already have them. + * + * Fills in missing newlines settings between adjacent groups using the global + * newlines option. This ensures every transition between groups has an explicit + * newlines setting for consistent calculation. + * + * @example + * + * ```ts + * buildGroupsWithAllNewlinesBetween( + * ['imports', 'types', { newlinesBetween: 2 }, 'functions'], + * 1, + * ) + * // Returns: [ + * // 'imports', + * // { newlinesBetween: 1 }, // Added + * // 'types', + * // { newlinesBetween: 2 }, // Already existed + * // 'functions' + * // ] + * ``` + * + * @param groups - Array of groups with optional inline newlines settings. + * @param globalNewlinesBetweenOption - Default newlines to use for missing + * settings. + * @returns Groups array with newlines settings filled in between all groups. + */ +function buildGroupsWithAllNewlinesBetween( + groups, + globalNewlinesBetweenOption, +) { + let returnValue = [] + for (let i = 0; i < groups.length; i++) { + let group = groups[i] + if (!isNewlinesBetweenOption(group)) { + let previousGroup = groups[i - 1] + if (previousGroup && !isNewlinesBetweenOption(previousGroup)) { + returnValue.push({ newlinesBetween: globalNewlinesBetweenOption }) + } + } + returnValue.push(group) + } + return returnValue +} +export { getNewlinesBetweenOption } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-node-decorators.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-node-decorators.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..57c420e1d351f2a0d8f402961654e61dded9aeee --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-node-decorators.d.ts @@ -0,0 +1,33 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Type representing an AST node that may have decorators. + * + * Extends the base Node type with an optional decorators array. Used for + * TypeScript/JavaScript decorators on classes, methods, and properties. + */ +type NodeWithDecorator = { + decorators: TSESTree.Decorator[] +} & TSESTree.Node +/** + * Safely retrieves decorators from an AST node. + * + * Provides a safe way to access the decorators property which may not exist on + * all nodes or in all parser versions. Returns an empty array when decorators + * are undefined, ensuring consistent behavior across different AST structures. + * + * @example + * + * ```ts + * // Node without decorators + * const plainMethod = { type: 'MethodDefinition', ... }; + * getNodeDecorators(plainMethod); + * // Returns: [] + * ``` + * + * @param node - AST node that may contain decorators. + * @returns Array of decorator nodes, empty array if none exist. + */ +export declare function getNodeDecorators( + node: NodeWithDecorator, +): TSESTree.Decorator[] +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-node-decorators.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-node-decorators.js new file mode 100644 index 0000000000000000000000000000000000000000..989156be6543203ab91d7240454b1fa527ed9619 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-node-decorators.js @@ -0,0 +1,23 @@ +/** + * Safely retrieves decorators from an AST node. + * + * Provides a safe way to access the decorators property which may not exist on + * all nodes or in all parser versions. Returns an empty array when decorators + * are undefined, ensuring consistent behavior across different AST structures. + * + * @example + * + * ```ts + * // Node without decorators + * const plainMethod = { type: 'MethodDefinition', ... }; + * getNodeDecorators(plainMethod); + * // Returns: [] + * ``` + * + * @param node - AST node that may contain decorators. + * @returns Array of decorator nodes, empty array if none exist. + */ +function getNodeDecorators(node) { + return node.decorators ?? [] +} +export { getNodeDecorators } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-node-range.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-node-range.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf9c21ebf1c3639f7b3c2a77e563618c3e217980 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-node-range.d.ts @@ -0,0 +1,95 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +import { CommonPartitionOptions } from '../types/common-partition-options.js' +/** + * Parameters for determining the complete range of a node. + * + * Configures how to calculate the node's range including associated comments + * and parentheses. + */ +interface GetNodeRangeParameters { + /** + * Optional configuration for comment handling. + */ + options?: Pick + /** + * Decorators associated with this node that are not directly accessible via + * the AST node's own `decorators` property. + * + * Used in contexts where decorators are tracked separately from their + * decorated node. When provided, these decorators override the node's own + * `decorators` in range calculations, ensuring they are included when the + * node is moved during sorting fixes. + */ + implicitDecorators?: TSESTree.Decorator[] + /** + * Whether to exclude the highest-level block comment from the range. Useful + * for preserving file-level documentation comments in their original + * position. + */ + ignoreHighestBlockComment?: boolean + /** + * ESLint source code object for accessing comments and tokens. + */ + sourceCode: TSESLint.SourceCode + /** + * AST node to get the range for. + */ + node: TSESTree.Node +} +/** + * Determines the complete range of a node including its associated comments. + * + * Calculates the full range that should be considered when moving or analyzing + * a node. This includes: + * + * - The node itself + * - Parentheses surrounding the node (if any) + * - Preceding comments that "belong" to the node. + * + * The function intelligently determines which comments should be included by: + * + * - Including comments directly above the node (no empty lines between) + * - Stopping at partition comments (used to separate sections) + * - Stopping at ESLint disable/enable comments + * - Optionally excluding the highest block comment (e.g., file headers). + * + * @example + * + * ```ts + * // Source code: + * // This comment belongs to the function + * // So does this one + * function foo() {} + * + * const range = getNodeRange({ node: functionNode, sourceCode }) + * // Returns range including both comments + * ``` + * + * @example + * + * ```ts + * // Source code: + * /* File header comment *\/ + * // Function comment + * function bar() { } + * + * const range = getNodeRange({ + * node: functionNode, + * sourceCode, + * ignoreHighestBlockComment: true + * }); + * // Returns range including line comment but not block comment + * ``` + * + * @param params - Parameters for range calculation. + * @returns Tuple of [start, end] positions including relevant comments. + */ +export declare function getNodeRange({ + ignoreHighestBlockComment, + implicitDecorators, + sourceCode, + options, + node, +}: GetNodeRangeParameters): TSESTree.Range +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-node-range.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-node-range.js new file mode 100644 index 0000000000000000000000000000000000000000..1ac032221d2fff09c692c207f683d7736679e523 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-node-range.js @@ -0,0 +1,142 @@ +import { getEslintDisabledRules } from './get-eslint-disabled-rules.js' +import { isPartitionComment } from './is-partition-comment.js' +import { getCommentsBefore } from './get-comments-before.js' +import { ASTUtils } from '@typescript-eslint/utils' +/** + * Determines the complete range of a node including its associated comments. + * + * Calculates the full range that should be considered when moving or analyzing + * a node. This includes: + * + * - The node itself + * - Parentheses surrounding the node (if any) + * - Preceding comments that "belong" to the node. + * + * The function intelligently determines which comments should be included by: + * + * - Including comments directly above the node (no empty lines between) + * - Stopping at partition comments (used to separate sections) + * - Stopping at ESLint disable/enable comments + * - Optionally excluding the highest block comment (e.g., file headers). + * + * @example + * + * ```ts + * // Source code: + * // This comment belongs to the function + * // So does this one + * function foo() {} + * + * const range = getNodeRange({ node: functionNode, sourceCode }) + * // Returns range including both comments + * ``` + * + * @example + * + * ```ts + * // Source code: + * /* File header comment *\/ + * // Function comment + * function bar() { } + * + * const range = getNodeRange({ + * node: functionNode, + * sourceCode, + * ignoreHighestBlockComment: true + * }); + * // Returns range including line comment but not block comment + * ``` + * + * @param params - Parameters for range calculation. + * @returns Tuple of [start, end] positions including relevant comments. + */ +function getNodeRange({ + ignoreHighestBlockComment, + implicitDecorators, + sourceCode, + options, + node, +}) { + let start = node.range.at(0) + let end = node.range.at(1) + let decorators = + implicitDecorators ?? ('decorators' in node ? node.decorators : []) + if (decorators[0]) { + start = Math.min(start, decorators[0].range[0]) + let decoratorTopCommentStart = computeHighestCommentStart({ + comments: getCommentsBefore({ + node: decorators[0], + sourceCode, + }), + anchorLine: decorators[0].loc.start.line, + ignoreHighestBlockComment, + options, + }) + if (decoratorTopCommentStart !== void 0) { + start = Math.min(start, decoratorTopCommentStart) + } + } + if (ASTUtils.isParenthesized(node, sourceCode)) { + let bodyOpeningParen = sourceCode.getTokenBefore( + node, + ASTUtils.isOpeningParenToken, + ) + let bodyClosingParen = sourceCode.getTokenAfter( + node, + ASTUtils.isClosingParenToken, + ) + start = Math.min(start, bodyOpeningParen.range.at(0)) + end = bodyClosingParen.range.at(1) + } + let topCommentStart = computeHighestCommentStart({ + comments: getCommentsBefore({ + sourceCode, + node, + }), + anchorLine: node.loc.start.line, + ignoreHighestBlockComment, + options, + }) + if (topCommentStart !== void 0) { + start = Math.min(start, topCommentStart) + } + return [start, end] +} +function computeHighestCommentStart({ + ignoreHighestBlockComment, + anchorLine, + comments, + options, +}) { + let highestBlockComment = comments.find(comment => comment.type === 'Block') + let highestCommentStart + for (let i = comments.length - 1; i >= 0; i--) { + let comment = comments[i] + if (ignoreHighestBlockComment && comment === highestBlockComment) { + break + } + let eslintDisabledRules = getEslintDisabledRules(comment.value) + if ( + isPartitionComment({ + partitionByComment: options?.partitionByComment ?? false, + comment, + }) || + eslintDisabledRules?.eslintDisableDirective === 'eslint-disable' || + eslintDisabledRules?.eslintDisableDirective === 'eslint-enable' + ) { + break + } + /** + * Check for newlines between comments or between the first comment and the + * node. + */ + let previousCommentOrAnchorLine = + i === comments.length - 1 ? anchorLine : comments[i + 1].loc.start.line + if (comment.loc.end.line !== previousCommentOrAnchorLine - 1) { + break + } + highestCommentStart = comment.range.at(0) + } + return highestCommentStart +} +export { getNodeRange } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-options-with-clean-groups.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-options-with-clean-groups.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5fb85bf36f4e28347d6231d75c24ff423c56d428 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-options-with-clean-groups.d.ts @@ -0,0 +1,58 @@ +import { GroupsOptions } from '../types/common-groups-options.js' +/** + * Parameters for cleaning and normalizing groups configuration. + * + * Contains the groups array that needs to be cleaned up. + */ +interface GetOptionsWithCleanGroupsParameters { + /** + * Groups configuration that may contain empty arrays or single-element + * arrays. + */ + groups: GroupsOptions +} +/** + * Cleans and normalizes the groups configuration in options. + * + * Performs the following optimizations on the groups array: + * + * - Removes empty arrays (they serve no purpose in grouping) + * - Converts single-element arrays to plain strings (simplifies structure) + * - Preserves multi-element arrays as-is (maintains subgroups). + * + * This normalization ensures consistent group handling and eliminates + * unnecessary complexity in the configuration. + * + * @example + * + * ```ts + * getOptionsWithCleanGroups({ + * groups: [ + * 'imports', + * ['types'], // Single element - will become 'types' + * ['hooks', 'utils'], // Multiple elements - preserved as array + * [], // Empty - will be removed + * 'components', + * ], + * }) + * // Returns: { + * // groups: [ + * // 'imports', + * // 'types', + * // ['hooks', 'utils'], + * // 'components' + * // ] + * // } + * ``` + * + * @template CustomTypeOption - Custom type option string for GroupsOptions. + * @template Options - Type of options extending + * GetOptionsWithCleanGroupsParameters. + * @param options - Options object containing groups to clean. + * @returns Options with cleaned and normalized groups array. + */ +export declare function getOptionsWithCleanGroups< + CustomTypeOption extends string, + Options extends GetOptionsWithCleanGroupsParameters, +>(options: Options): Options +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-options-with-clean-groups.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-options-with-clean-groups.js new file mode 100644 index 0000000000000000000000000000000000000000..6f0261a76e24ec7f1b5b0aef513acbb823a4aec8 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-options-with-clean-groups.js @@ -0,0 +1,78 @@ +/** + * Cleans and normalizes the groups configuration in options. + * + * Performs the following optimizations on the groups array: + * + * - Removes empty arrays (they serve no purpose in grouping) + * - Converts single-element arrays to plain strings (simplifies structure) + * - Preserves multi-element arrays as-is (maintains subgroups). + * + * This normalization ensures consistent group handling and eliminates + * unnecessary complexity in the configuration. + * + * @example + * + * ```ts + * getOptionsWithCleanGroups({ + * groups: [ + * 'imports', + * ['types'], // Single element - will become 'types' + * ['hooks', 'utils'], // Multiple elements - preserved as array + * [], // Empty - will be removed + * 'components', + * ], + * }) + * // Returns: { + * // groups: [ + * // 'imports', + * // 'types', + * // ['hooks', 'utils'], + * // 'components' + * // ] + * // } + * ``` + * + * @template CustomTypeOption - Custom type option string for GroupsOptions. + * @template Options - Type of options extending + * GetOptionsWithCleanGroupsParameters. + * @param options - Options object containing groups to clean. + * @returns Options with cleaned and normalized groups array. + */ +function getOptionsWithCleanGroups(options) { + return { + ...options, + groups: options.groups + .filter(group => !Array.isArray(group) || group.length > 0) + .map(group => + Array.isArray(group) ? getCleanedNestedGroups(group) : group, + ), + } +} +/** + * Simplifies a nested group array by converting single-element arrays to + * strings. + * + * Helper function that normalizes array groups: + * + * - Single-element arrays are unwrapped to plain strings + * - Multi-element arrays are preserved as-is + * - Empty single-element arrays remain as arrays. + * + * @example + * + * ```ts + * getCleanedNestedGroups(['types']) // Returns: 'types' + * getCleanedNestedGroups(['a', 'b']) // Returns: ['a', 'b'] + * getCleanedNestedGroups(['']) // Returns: [''] + * ``` + * + * @param nestedGroup - Array of group names to potentially simplify. + * @returns Simplified string if single non-empty element, otherwise the + * original array. + */ +function getCleanedNestedGroups(nestedGroup) { + return nestedGroup.length === 1 && nestedGroup[0] ? + nestedGroup[0] + : nestedGroup +} +export { getOptionsWithCleanGroups } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-settings.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-settings.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d156dc4c960a8b03dd05564ba1c185ab7960da29 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-settings.d.ts @@ -0,0 +1,58 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { CommonPartitionOptions } from '../types/common-partition-options.js' +import { CommonGroupsOptions } from '../types/common-groups-options.js' +import { CommonOptions } from '../types/common-options.js' +/** + * Global settings for the Perfectionist plugin. + * + * These settings can be configured in ESLint configuration under the + * 'perfectionist' key and apply to all Perfectionist rules unless overridden by + * rule-specific options. + */ +export type Settings = Partial< + Pick< + CommonGroupsOptions, + 'newlinesBetween' | 'newlinesInside' + > & + CommonPartitionOptions & + CommonOptions +> +/** + * Extracts and validates Perfectionist settings from ESLint configuration. + * + * Retrieves global Perfectionist settings that apply to all rules. Validates + * that only allowed settings are provided and throws an error if invalid + * options are detected. This ensures configuration errors are caught early with + * clear error messages. + * + * The settings are accessed from the 'perfectionist' key in ESLint's shared + * configuration settings. + * + * @example + * + * ```ts + * // Valid usage: + * const settings = getSettings(context.settings) + * // Returns: { type: 'natural', order: 'asc', ignoreCase: true } + * ``` + * + * @example + * + * ```ts + * // Invalid setting throws error: + * getSettings({ + * perfectionist: { + * type: 'natural', + * invalidOption: true, // This will throw + * }, + * }) + * // Throws: Error: Invalid Perfectionist setting(s): invalidOption + * ``` + * + * @param settings - ESLint shared configuration settings object. + * @returns Validated Perfectionist settings or empty object if none configured. + * @throws {Error} If invalid settings are provided. + */ +export declare function getSettings( + settings: TSESLint.SharedConfigurationSettings, +): Settings diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-settings.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-settings.js new file mode 100644 index 0000000000000000000000000000000000000000..9c82e84912a64bba92105e6a90a185ef35761620 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/get-settings.js @@ -0,0 +1,72 @@ +/** + * Extracts and validates Perfectionist settings from ESLint configuration. + * + * Retrieves global Perfectionist settings that apply to all rules. Validates + * that only allowed settings are provided and throws an error if invalid + * options are detected. This ensures configuration errors are caught early with + * clear error messages. + * + * The settings are accessed from the 'perfectionist' key in ESLint's shared + * configuration settings. + * + * @example + * + * ```ts + * // Valid usage: + * const settings = getSettings(context.settings) + * // Returns: { type: 'natural', order: 'asc', ignoreCase: true } + * ``` + * + * @example + * + * ```ts + * // Invalid setting throws error: + * getSettings({ + * perfectionist: { + * type: 'natural', + * invalidOption: true, // This will throw + * }, + * }) + * // Throws: Error: Invalid Perfectionist setting(s): invalidOption + * ``` + * + * @param settings - ESLint shared configuration settings object. + * @returns Validated Perfectionist settings or empty object if none configured. + * @throws {Error} If invalid settings are provided. + */ +function getSettings(settings) { + if (!settings['perfectionist']) { + return {} + } + /** + * Identifies settings keys that are not in the allowed list. + * + * @param object - Settings object to validate. + * @returns Array of invalid setting names. + */ + function getInvalidOptions(object) { + let allowedOptions = /* @__PURE__ */ new Set([ + 'partitionByComment', + 'partitionByNewLine', + 'specialCharacters', + 'newlinesBetween', + 'newlinesInside', + 'fallbackSort', + 'ignoreCase', + 'alphabet', + 'locales', + 'order', + 'type', + ]) + return Object.keys(object).filter(key => !allowedOptions.has(key)) + } + let perfectionistSettings = settings['perfectionist'] + let invalidOptions = getInvalidOptions(perfectionistSettings) + if (invalidOptions.length > 0) { + throw new Error( + `Invalid Perfectionist setting(s): ${invalidOptions.join(', ')}`, + ) + } + return settings['perfectionist'] +} +export { getSettings } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-group-with-overrides-option.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-group-with-overrides-option.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a19dae6f206a727c4dee155c9d5f6b460b81500 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-group-with-overrides-option.d.ts @@ -0,0 +1,40 @@ +import { + GroupWithOverridesOption, + GroupsOptions, +} from '../types/common-groups-options.js' +/** + * Type guard to check if a group option is a group with overrides + * configuration. + * + * Determines whether a group element is a special configuration object that + * contains group settings rather than being a regular group name or newlines + * option. + * + * @example + * + * ```ts + * const groups = [ + * 'imports', + * { group: 'foo', commentAbove: '// Components' }, + * 'components', + * { newlinesBetween: 1 }, + * 'utils', + * ] + * + * isGroupWithOverridesOption(groups[0]) // false (string) + * isGroupWithOverridesOption(groups[1]) // true + * isGroupWithOverridesOption(groups[3]) // false (newlines option) + * ``` + * + * @param groupOption - A single element from the groups configuration array. + * @returns True if the element is a group with overrides configuration object. + */ +export declare function isGroupWithOverridesOption< + CustomTypeOption extends string, + AdditionalSortOptions, +>( + groupOption: GroupsOptions[number], +): groupOption is GroupWithOverridesOption< + CustomTypeOption, + AdditionalSortOptions +> diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-group-with-overrides-option.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-group-with-overrides-option.js new file mode 100644 index 0000000000000000000000000000000000000000..688d6cf17ab66ff6e04a7c05fb8a352d972c195c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-group-with-overrides-option.js @@ -0,0 +1,31 @@ +/** + * Type guard to check if a group option is a group with overrides + * configuration. + * + * Determines whether a group element is a special configuration object that + * contains group settings rather than being a regular group name or newlines + * option. + * + * @example + * + * ```ts + * const groups = [ + * 'imports', + * { group: 'foo', commentAbove: '// Components' }, + * 'components', + * { newlinesBetween: 1 }, + * 'utils', + * ] + * + * isGroupWithOverridesOption(groups[0]) // false (string) + * isGroupWithOverridesOption(groups[1]) // true + * isGroupWithOverridesOption(groups[3]) // false (newlines option) + * ``` + * + * @param groupOption - A single element from the groups configuration array. + * @returns True if the element is a group with overrides configuration object. + */ +function isGroupWithOverridesOption(groupOption) { + return typeof groupOption === 'object' && 'group' in groupOption +} +export { isGroupWithOverridesOption } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-newlines-between-option.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-newlines-between-option.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c76fe703cb4ab8b6152de10d5e799aaad253b0aa --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-newlines-between-option.d.ts @@ -0,0 +1,40 @@ +import { + GroupNewlinesBetweenOption, + GroupsOptions, +} from '../types/common-groups-options.js' +/** + * Type guard to check if a group option is a newlines-between configuration. + * + * Determines whether a group element contains a `newlinesBetween` property, + * which indicates it's a special configuration object that controls spacing + * between groups rather than being a regular group name or comment option. + * + * Newlines-between options are placed between group names in the configuration + * to specify how many newlines should separate those groups in the sorted + * output. + * + * @example + * + * ```ts + * const groups = [ + * 'imports', + * { newlinesBetween: 1 }, // Add 1 newline between imports and types + * 'types', + * { newlinesBetween: 2 }, // Add 2 newlines between types and components + * 'components', + * { commentAbove: '// Utils' }, // Not a newlines option + * 'utils', + * ] + * + * isNewlinesBetweenOption(groups[0]) // false (string) + * isNewlinesBetweenOption(groups[1]) // true (has newlinesBetween) + * isNewlinesBetweenOption(groups[3]) // true (has newlinesBetween) + * isNewlinesBetweenOption(groups[5]) // false (comment option) + * ``` + * + * @param groupOption - A single element from the groups configuration array. + * @returns True if the element is a newlines-between configuration object. + */ +export declare function isNewlinesBetweenOption( + groupOption: GroupsOptions[number], +): groupOption is GroupNewlinesBetweenOption diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-newlines-between-option.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-newlines-between-option.js new file mode 100644 index 0000000000000000000000000000000000000000..36b8fabc7edc670c0e709436ebcdca8630e0dfd5 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-newlines-between-option.js @@ -0,0 +1,37 @@ +/** + * Type guard to check if a group option is a newlines-between configuration. + * + * Determines whether a group element contains a `newlinesBetween` property, + * which indicates it's a special configuration object that controls spacing + * between groups rather than being a regular group name or comment option. + * + * Newlines-between options are placed between group names in the configuration + * to specify how many newlines should separate those groups in the sorted + * output. + * + * @example + * + * ```ts + * const groups = [ + * 'imports', + * { newlinesBetween: 1 }, // Add 1 newline between imports and types + * 'types', + * { newlinesBetween: 2 }, // Add 2 newlines between types and components + * 'components', + * { commentAbove: '// Utils' }, // Not a newlines option + * 'utils', + * ] + * + * isNewlinesBetweenOption(groups[0]) // false (string) + * isNewlinesBetweenOption(groups[1]) // true (has newlinesBetween) + * isNewlinesBetweenOption(groups[3]) // true (has newlinesBetween) + * isNewlinesBetweenOption(groups[5]) // false (comment option) + * ``` + * + * @param groupOption - A single element from the groups configuration array. + * @returns True if the element is a newlines-between configuration object. + */ +function isNewlinesBetweenOption(groupOption) { + return typeof groupOption === 'object' && 'newlinesBetween' in groupOption +} +export { isNewlinesBetweenOption } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-dependent-on-other-node.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-dependent-on-other-node.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5e1179965988edbce30cf89a39326b2be5fb8410 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-dependent-on-other-node.d.ts @@ -0,0 +1,51 @@ +import { SortingNodeWithDependencies } from './sort-nodes-by-dependencies.js' +/** + * Checks if one node has a dependency on another node. + * + * Determines whether sortingNode1 depends on sortingNode2 by checking if any of + * sortingNode1's dependency names match any of sortingNode2's dependencies. + * This is used in dependency-aware sorting to ensure that dependent nodes are + * placed after their dependencies. + * + * Returns false for self-dependency (when both nodes are the same) to prevent + * circular dependency issues. + * + * @example + * + * ```ts + * const nodeA = { + * name: 'userService', + * dependencies: ['userService'], + * dependencyNames: ['logger', 'database'], + * } + * + * const nodeB = { + * name: 'logger', + * dependencies: ['logger'], + * dependencyNames: [], + * } + * + * isNodeDependentOnOtherNode(nodeA, nodeB) + * // Returns: true (userService depends on logger) + * + * isNodeDependentOnOtherNode(nodeB, nodeA) + * // Returns: false (logger doesn't depend on userService) + * + * isNodeDependentOnOtherNode(nodeA, nodeA) + * // Returns: false (self-dependency check) + * ``` + * + * @param sortingNode1 - The node to check for dependencies. + * @param sortingNode2 - The potential dependency node. + * @returns True if sortingNode1 depends on sortingNode2, false otherwise. + */ +export declare function isNodeDependentOnOtherNode( + sortingNode1: Pick< + SortingNodeWithDependencies, + 'dependencyNames' | 'dependencies' + >, + sortingNode2: Pick< + SortingNodeWithDependencies, + 'dependencyNames' | 'dependencies' + >, +): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-dependent-on-other-node.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-dependent-on-other-node.js new file mode 100644 index 0000000000000000000000000000000000000000..159eef41b5f1445b45d17297a9790d1a45d58763 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-dependent-on-other-node.js @@ -0,0 +1,49 @@ +/** + * Checks if one node has a dependency on another node. + * + * Determines whether sortingNode1 depends on sortingNode2 by checking if any of + * sortingNode1's dependency names match any of sortingNode2's dependencies. + * This is used in dependency-aware sorting to ensure that dependent nodes are + * placed after their dependencies. + * + * Returns false for self-dependency (when both nodes are the same) to prevent + * circular dependency issues. + * + * @example + * + * ```ts + * const nodeA = { + * name: 'userService', + * dependencies: ['userService'], + * dependencyNames: ['logger', 'database'], + * } + * + * const nodeB = { + * name: 'logger', + * dependencies: ['logger'], + * dependencyNames: [], + * } + * + * isNodeDependentOnOtherNode(nodeA, nodeB) + * // Returns: true (userService depends on logger) + * + * isNodeDependentOnOtherNode(nodeB, nodeA) + * // Returns: false (logger doesn't depend on userService) + * + * isNodeDependentOnOtherNode(nodeA, nodeA) + * // Returns: false (self-dependency check) + * ``` + * + * @param sortingNode1 - The node to check for dependencies. + * @param sortingNode2 - The potential dependency node. + * @returns True if sortingNode1 depends on sortingNode2, false otherwise. + */ +function isNodeDependentOnOtherNode(sortingNode1, sortingNode2) { + if (sortingNode1 === sortingNode2) { + return false + } + return sortingNode1.dependencyNames.some(dependency => + sortingNode2.dependencies.includes(dependency), + ) +} +export { isNodeDependentOnOtherNode } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-eslint-disabled.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-eslint-disabled.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..28e42974de3836ff5aa879a3b62e01430ab676e5 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-eslint-disabled.d.ts @@ -0,0 +1,32 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Checks if ESLint rules are disabled for a specific AST node. + * + * Determines whether a node is located on a line where ESLint rules have been + * disabled via comments (eslint-disable, eslint-disable-line, + * eslint-disable-next-line). This is used to exclude disabled nodes from + * sorting operations to respect user's explicit disable directives. + * + * @example + * + * ```ts + * const eslintDisabledLines = [5, 10, 11, 12] // Lines where ESLint is disabled + * + * const nodeOnLine5 = { loc: { start: { line: 5 } } } + * const nodeOnLine6 = { loc: { start: { line: 6 } } } + * + * isNodeEslintDisabled(nodeOnLine5, eslintDisabledLines) + * // Returns: true (line 5 is in disabled lines) + * + * isNodeEslintDisabled(nodeOnLine6, eslintDisabledLines) + * // Returns: false (line 6 is not in disabled lines) + * ``` + * + * @param node - AST node to check for ESLint disable status. + * @param eslintDisabledLines - Array of line numbers where ESLint is disabled. + * @returns True if the node is on a disabled line, false otherwise. + */ +export declare function isNodeEslintDisabled( + node: TSESTree.Node, + eslintDisabledLines: number[], +): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-eslint-disabled.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-eslint-disabled.js new file mode 100644 index 0000000000000000000000000000000000000000..2afc32ed8fd1c74a5bc0dbf981e9c393f6794563 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-eslint-disabled.js @@ -0,0 +1,31 @@ +/** + * Checks if ESLint rules are disabled for a specific AST node. + * + * Determines whether a node is located on a line where ESLint rules have been + * disabled via comments (eslint-disable, eslint-disable-line, + * eslint-disable-next-line). This is used to exclude disabled nodes from + * sorting operations to respect user's explicit disable directives. + * + * @example + * + * ```ts + * const eslintDisabledLines = [5, 10, 11, 12] // Lines where ESLint is disabled + * + * const nodeOnLine5 = { loc: { start: { line: 5 } } } + * const nodeOnLine6 = { loc: { start: { line: 6 } } } + * + * isNodeEslintDisabled(nodeOnLine5, eslintDisabledLines) + * // Returns: true (line 5 is in disabled lines) + * + * isNodeEslintDisabled(nodeOnLine6, eslintDisabledLines) + * // Returns: false (line 6 is not in disabled lines) + * ``` + * + * @param node - AST node to check for ESLint disable status. + * @param eslintDisabledLines - Array of line numbers where ESLint is disabled. + * @returns True if the node is on a disabled line, false otherwise. + */ +function isNodeEslintDisabled(node, eslintDisabledLines) { + return eslintDisabledLines.includes(node.loc.start.line) +} +export { isNodeEslintDisabled } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-immediately-called.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-immediately-called.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..37482fd93584643260d5833cd86188958e60fffd --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-immediately-called.d.ts @@ -0,0 +1,14 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Checks whether a node is the callee of a call or `new` expression. + * + * Used to treat immediately invoked function expressions as eagerly executed: + * references inside their bodies are read as soon as the surrounding expression + * is evaluated, unlike references inside deferred function bodies. + * + * @param node - The AST node to check. + * @returns Whether the node is immediately called. + */ +export declare function isNodeImmediatelyCalled( + node: TSESTree.Expression, +): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-immediately-called.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-immediately-called.js new file mode 100644 index 0000000000000000000000000000000000000000..dc4ded4e3eb15867f42d35cbdfa344a676c7f762 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-immediately-called.js @@ -0,0 +1,20 @@ +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +/** + * Checks whether a node is the callee of a call or `new` expression. + * + * Used to treat immediately invoked function expressions as eagerly executed: + * references inside their bodies are read as soon as the surrounding expression + * is evaluated, unlike references inside deferred function bodies. + * + * @param node - The AST node to check. + * @returns Whether the node is immediately called. + */ +function isNodeImmediatelyCalled(node) { + let { parent } = node + return ( + (parent.type === AST_NODE_TYPES.CallExpression || + parent.type === AST_NODE_TYPES.NewExpression) && + parent.callee === node + ) +} +export { isNodeImmediatelyCalled } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-on-single-line.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-on-single-line.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5b3a9b3f1e03199100929a51d79880fb3c2144d3 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-on-single-line.d.ts @@ -0,0 +1,8 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Returns if a node is on a single line. + * + * @param node - The node to check. + * @returns True if the node is on a single line, false otherwise. + */ +export declare function isNodeOnSingleLine(node: TSESTree.Node): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-on-single-line.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-on-single-line.js new file mode 100644 index 0000000000000000000000000000000000000000..172fa2fd741a42b2fd87b480a7d2686748724156 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-node-on-single-line.js @@ -0,0 +1,10 @@ +/** + * Returns if a node is on a single line. + * + * @param node - The node to check. + * @returns True if the node is on a single line, false otherwise. + */ +function isNodeOnSingleLine(node) { + return node.loc.start.line === node.loc.end.line +} +export { isNodeOnSingleLine } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-partition-comment.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-partition-comment.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fbdb3a9fda0a963ddcbf8d3341f0fe2bde69866b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-partition-comment.d.ts @@ -0,0 +1,77 @@ +import { TSESTree } from '@typescript-eslint/types' +import { PartitionByCommentOption } from '../types/common-partition-options.js' +/** + * Parameters for checking if a comment is a partition comment. + */ +interface IsPartitionCommentParameters { + /** + * Configuration for partition comments. Can be boolean, string/regex + * pattern, array of patterns, or object with block/line specific settings. + */ + partitionByComment: PartitionByCommentOption + /** + * The comment node to check. + */ + comment: TSESTree.Comment +} +/** + * Determines if a comment should be treated as a partition separator. + * + * Partition comments divide code into independent sections that are sorted + * separately. This prevents elements from being moved across these boundaries + * during sorting operations. + * + * The function handles various configuration formats: + * + * - `true`: All comments are partition comments + * - `false`: No comments are partition comments + * - String/Regex: Comments matching the pattern are partitions + * - Array: Comments matching any pattern in the array are partitions + * - Object: Different patterns for block and line comments. + * + * ESLint disable comments are never treated as partition comments to avoid + * interfering with ESLint's functionality. + * + * @example + * + * ```ts + * // Configuration: partitionByComment: true + * isPartitionComment({ partitionByComment: true, comment }) + * // Returns: true for any non-ESLint-disable comment + * ``` + * + * @example + * + * ```ts + * // Configuration: partitionByComment: 'Section:' + * const comment = { value: ' Section: Utils ', type: 'Line' } + * isPartitionComment({ partitionByComment: 'Section:', comment }) + * // Returns: true (comment contains 'Section:') + * ``` + * + * @example + * + * ```ts + * // Configuration: partitionByComment: { block: true, line: '^-' } + * const blockComment = { value: ' Helper functions ', type: 'Block' } + * const lineComment = { value: '--- Utils ---', type: 'Line' } + * isPartitionComment({ + * partitionByComment: { block: true, line: '^-' }, + * comment: blockComment, + * }) + * // Returns: true (all block comments are partitions) + * isPartitionComment({ + * partitionByComment: { block: true, line: '^-' }, + * comment: lineComment, + * }) + * // Returns: true (line comment starts with '-') + * ``` + * + * @param params - Parameters for partition check. + * @returns True if the comment is a partition separator, false otherwise. + */ +export declare function isPartitionComment({ + partitionByComment, + comment, +}: IsPartitionCommentParameters): boolean +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-partition-comment.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-partition-comment.js new file mode 100644 index 0000000000000000000000000000000000000000..1102238bbbb829c36a329f2a8ff909c03f6f203e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-partition-comment.js @@ -0,0 +1,109 @@ +import { getEslintDisabledRules } from './get-eslint-disabled-rules.js' +import { matches } from './matches.js' +/** + * Determines if a comment should be treated as a partition separator. + * + * Partition comments divide code into independent sections that are sorted + * separately. This prevents elements from being moved across these boundaries + * during sorting operations. + * + * The function handles various configuration formats: + * + * - `true`: All comments are partition comments + * - `false`: No comments are partition comments + * - String/Regex: Comments matching the pattern are partitions + * - Array: Comments matching any pattern in the array are partitions + * - Object: Different patterns for block and line comments. + * + * ESLint disable comments are never treated as partition comments to avoid + * interfering with ESLint's functionality. + * + * @example + * + * ```ts + * // Configuration: partitionByComment: true + * isPartitionComment({ partitionByComment: true, comment }) + * // Returns: true for any non-ESLint-disable comment + * ``` + * + * @example + * + * ```ts + * // Configuration: partitionByComment: 'Section:' + * const comment = { value: ' Section: Utils ', type: 'Line' } + * isPartitionComment({ partitionByComment: 'Section:', comment }) + * // Returns: true (comment contains 'Section:') + * ``` + * + * @example + * + * ```ts + * // Configuration: partitionByComment: { block: true, line: '^-' } + * const blockComment = { value: ' Helper functions ', type: 'Block' } + * const lineComment = { value: '--- Utils ---', type: 'Line' } + * isPartitionComment({ + * partitionByComment: { block: true, line: '^-' }, + * comment: blockComment, + * }) + * // Returns: true (all block comments are partitions) + * isPartitionComment({ + * partitionByComment: { block: true, line: '^-' }, + * comment: lineComment, + * }) + * // Returns: true (line comment starts with '-') + * ``` + * + * @param params - Parameters for partition check. + * @returns True if the comment is a partition separator, false otherwise. + */ +function isPartitionComment({ partitionByComment, comment }) { + if (!partitionByComment || getEslintDisabledRules(comment.value)) { + return false + } + let trimmedComment = comment.value.trim() + if ( + typeof partitionByComment === 'boolean' || + typeof partitionByComment === 'string' || + Array.isArray(partitionByComment) + ) { + return isTrimmedCommentPartitionComment({ + partitionByComment, + trimmedComment, + }) + } + let relevantPartitionByComment + if (comment.type === 'Block' && 'block' in partitionByComment) { + relevantPartitionByComment = partitionByComment.block + } + if (comment.type === 'Line' && 'line' in partitionByComment) { + relevantPartitionByComment = partitionByComment.line + } + return ( + relevantPartitionByComment !== void 0 && + isTrimmedCommentPartitionComment({ + partitionByComment: relevantPartitionByComment, + trimmedComment, + }) + ) +} +/** + * Checks if a trimmed comment matches the partition criteria. + * + * Helper function that performs the actual matching logic against a trimmed + * comment string. Handles both boolean flags and pattern matching. + * + * @param params - Parameters for matching. + * @param params.partitionByComment - Boolean flag or pattern to match against. + * @param params.trimmedComment - Comment text with whitespace trimmed. + * @returns True if the comment matches the partition criteria. + */ +function isTrimmedCommentPartitionComment({ + partitionByComment, + trimmedComment, +}) { + if (typeof partitionByComment === 'boolean') { + return partitionByComment + } + return matches(trimmedComment, partitionByComment) +} +export { isPartitionComment } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-sortable.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-sortable.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..034bd124230fb1eca213fb5c4bac8ac19e7986fe --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-sortable.d.ts @@ -0,0 +1,7 @@ +/** + * Checks if a node is sortable (i.e., an array with more than one element). + * + * @param node - The node to check. + * @returns True if the node is sortable, false otherwise. + */ +export declare function isSortable(node: unknown): node is unknown[] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-sortable.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-sortable.js new file mode 100644 index 0000000000000000000000000000000000000000..7f66c26a48af362a8148cb13f0b4330af2147d7b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/is-sortable.js @@ -0,0 +1,10 @@ +/** + * Checks if a node is sortable (i.e., an array with more than one element). + * + * @param node - The node to check. + * @returns True if the node is sortable, false otherwise. + */ +function isSortable(node) { + return Array.isArray(node) && node.length > 1 +} +export { isSortable } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/common-groups-json-schemas.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/common-groups-json-schemas.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b8a8cca21ee837b05777a1c913cc560e445bbf9a --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/common-groups-json-schemas.d.ts @@ -0,0 +1,113 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +/** + * JSON schema for the newlines between option. Validates configuration for + * adding newlines between different groups. + */ +export declare let newlinesBetweenJsonSchema: JSONSchema4 +/** + * JSON schema for the newlines inside option. + */ +export declare let newlinesInsideJsonSchema: JSONSchema4 +export declare function buildGroupsJsonSchema({ + allowedAdditionalTypeValues, + additionalSortProperties, +}: { + additionalSortProperties: Record | undefined + allowedAdditionalTypeValues: undefined | string[] +}): JSONSchema4 +/** + * Builds JSON schema for custom groups array configuration. + * + * Creates a schema that validates an array of custom group definitions. + * Supports both single custom groups and "anyOf" groups containing multiple + * subgroups. Each group must have a groupName and can include various matching + * criteria. + * + * @example + * + * ```ts + * // Valid configuration: + * ;[ + * { + * groupName: 'react', + * anyOf: [{ elementNamePattern: 'use*' }, { selector: 'hook' }], + * }, + * { + * groupName: 'utils', + * elementNamePattern: '*Utils', + * }, + * ] + * ``` + * + * @param options - Configuration options. + * @param options.additionalSortProperties - Extra properties for sorting. + * @param options.additionalCustomGroupMatchProperties - Extra properties for + * matching custom groups. + * @returns JSON schema for custom groups array validation. + */ +export declare function buildCustomGroupsArrayJsonSchema({ + additionalCustomGroupMatchProperties, + allowedAdditionalTypeValues, + additionalSortProperties, +}: { + additionalCustomGroupMatchProperties: Record | undefined + additionalSortProperties: Record | undefined + allowedAdditionalTypeValues: undefined | string[] +}): JSONSchema4 +export declare function buildCommonGroupsJsonSchemas({ + additionalCustomGroupMatchProperties, + allowedAdditionalTypeValues, + additionalSortProperties, +}?: { + additionalCustomGroupMatchProperties?: Record + additionalSortProperties?: Record + allowedAdditionalTypeValues?: string[] +}): Record +/** + * Builds JSON schema for custom group modifiers configuration. + * + * Creates a schema that validates an array of modifiers that must be present on + * an element for it to match a custom group. + * + * @example + * + * ```ts + * // For TypeScript class members: + * buildCustomGroupModifiersJsonSchema([ + * 'static', + * 'private', + * 'readonly', + * 'async', + * ]) + * ``` + * + * @param modifiers - Array of valid modifier names. + * @returns JSON schema for modifiers array validation. + */ +export declare function buildCustomGroupModifiersJsonSchema( + modifiers: readonly string[], +): JSONSchema4 +/** + * Builds JSON schema for custom group selector configuration. + * + * Creates a schema that validates a selector string used to match specific + * types of elements in a custom group. + * + * @example + * + * ```ts + * // For class members: + * buildCustomGroupSelectorJsonSchema([ + * 'property', + * 'method', + * 'constructor', + * 'accessor', + * ]) + * ``` + * + * @param selectors - Array of valid selector names. + * @returns JSON schema for selector validation. + */ +export declare function buildCustomGroupSelectorJsonSchema( + selectors: readonly string[], +): JSONSchema4 diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/common-groups-json-schemas.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/common-groups-json-schemas.js new file mode 100644 index 0000000000000000000000000000000000000000..0caff220aa9bbb4b542f6fc51020520ee97e9ff1 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/common-groups-json-schemas.js @@ -0,0 +1,302 @@ +import { + buildFallbackSortJsonSchema, + buildRegexJsonSchema, + buildTypeJsonSchema, + orderJsonSchema, +} from './common-json-schemas.js' +/** + * JSON schema for the newlines between option. Validates configuration for + * adding newlines between different groups. + */ +var newlinesBetweenJsonSchema = { + oneOf: [ + { + description: 'Specifies how to handle newlines between groups.', + enum: ['ignore'], + type: 'string', + }, + { + type: 'number', + minimum: 0, + }, + ], +} +/** + * JSON schema for the newlines inside option. + */ +var newlinesInsideJsonSchema = { + oneOf: [ + { + description: 'Specifies how to handle newlines between groups elements', + enum: ['ignore'], + type: 'string', + }, + { + type: 'number', + minimum: 0, + }, + ], +} +function buildGroupsJsonSchema({ + allowedAdditionalTypeValues, + additionalSortProperties, +}) { + return { + items: { + oneOf: [ + { type: 'string' }, + { + items: { type: 'string' }, + type: 'array', + minItems: 1, + }, + { + properties: { newlinesBetween: newlinesBetweenJsonSchema }, + required: ['newlinesBetween'], + additionalProperties: false, + type: 'object', + }, + { + properties: { + group: { + oneOf: [ + { type: 'string' }, + { + items: { type: 'string' }, + type: 'array', + minItems: 1, + }, + ], + }, + fallbackSort: buildFallbackSortJsonSchema({ + additionalProperties: additionalSortProperties, + allowedAdditionalTypeValues, + }), + commentAbove: { + description: 'Specifies a comment to enforce above the group.', + type: 'string', + }, + type: buildTypeJsonSchema({ + allowedAdditionalValues: allowedAdditionalTypeValues, + }), + newlinesInside: newlinesInsideJsonSchema, + order: orderJsonSchema, + ...additionalSortProperties, + }, + additionalProperties: false, + required: ['group'], + minProperties: 2, + type: 'object', + }, + ], + }, + description: 'Specifies a list of groups for sorting.', + type: 'array', + } +} +/** + * Builds JSON schema for custom groups array configuration. + * + * Creates a schema that validates an array of custom group definitions. + * Supports both single custom groups and "anyOf" groups containing multiple + * subgroups. Each group must have a groupName and can include various matching + * criteria. + * + * @example + * + * ```ts + * // Valid configuration: + * ;[ + * { + * groupName: 'react', + * anyOf: [{ elementNamePattern: 'use*' }, { selector: 'hook' }], + * }, + * { + * groupName: 'utils', + * elementNamePattern: '*Utils', + * }, + * ] + * ``` + * + * @param options - Configuration options. + * @param options.additionalSortProperties - Extra properties for sorting. + * @param options.additionalCustomGroupMatchProperties - Extra properties for + * matching custom groups. + * @returns JSON schema for custom groups array validation. + */ +function buildCustomGroupsArrayJsonSchema({ + additionalCustomGroupMatchProperties, + allowedAdditionalTypeValues, + additionalSortProperties, +}) { + let commonCustomGroupJsonSchemas = buildCommonCustomGroupJsonSchemas({ + allowedAdditionalTypeValues, + additionalSortProperties, + }) + let populatedCustomGroupMatchOptionsJsonSchema = + buildPopulatedCustomGroupMatchPropertiesJsonSchema( + additionalCustomGroupMatchProperties, + ) + return { + items: { + oneOf: [ + { + properties: { + ...commonCustomGroupJsonSchemas, + anyOf: { + items: { + properties: populatedCustomGroupMatchOptionsJsonSchema, + description: 'Custom group.', + additionalProperties: false, + type: 'object', + }, + type: 'array', + minItems: 1, + }, + }, + description: 'Custom group block.', + required: ['groupName', 'anyOf'], + additionalProperties: false, + type: 'object', + }, + { + properties: { + ...commonCustomGroupJsonSchemas, + ...populatedCustomGroupMatchOptionsJsonSchema, + }, + description: 'Custom group.', + additionalProperties: false, + required: ['groupName'], + minProperties: 2, + type: 'object', + }, + ], + }, + description: 'Defines custom groups to match specific members.', + type: 'array', + } +} +function buildCommonGroupsJsonSchemas({ + additionalCustomGroupMatchProperties, + allowedAdditionalTypeValues, + additionalSortProperties, +} = {}) { + return { + customGroups: buildCustomGroupsArrayJsonSchema({ + additionalCustomGroupMatchProperties, + allowedAdditionalTypeValues, + additionalSortProperties, + }), + newlinesInside: { + oneOf: [ + newlinesInsideJsonSchema, + { + enum: ['newlinesBetween'], + type: 'string', + }, + ], + }, + groups: buildGroupsJsonSchema({ + allowedAdditionalTypeValues, + additionalSortProperties, + }), + newlinesBetween: newlinesBetweenJsonSchema, + } +} +/** + * Builds JSON schema for custom group modifiers configuration. + * + * Creates a schema that validates an array of modifiers that must be present on + * an element for it to match a custom group. + * + * @example + * + * ```ts + * // For TypeScript class members: + * buildCustomGroupModifiersJsonSchema([ + * 'static', + * 'private', + * 'readonly', + * 'async', + * ]) + * ``` + * + * @param modifiers - Array of valid modifier names. + * @returns JSON schema for modifiers array validation. + */ +function buildCustomGroupModifiersJsonSchema(modifiers) { + return { + items: { + enum: [...modifiers], + type: 'string', + }, + description: 'Modifier filters.', + type: 'array', + } +} +/** + * Builds JSON schema for custom group selector configuration. + * + * Creates a schema that validates a selector string used to match specific + * types of elements in a custom group. + * + * @example + * + * ```ts + * // For class members: + * buildCustomGroupSelectorJsonSchema([ + * 'property', + * 'method', + * 'constructor', + * 'accessor', + * ]) + * ``` + * + * @param selectors - Array of valid selector names. + * @returns JSON schema for selector validation. + */ +function buildCustomGroupSelectorJsonSchema(selectors) { + return { + description: 'Selector filter.', + enum: [...selectors], + type: 'string', + } +} +function buildCommonCustomGroupJsonSchemas({ + allowedAdditionalTypeValues, + additionalSortProperties, +}) { + return { + fallbackSort: buildFallbackSortJsonSchema({ + additionalProperties: additionalSortProperties, + allowedAdditionalTypeValues, + }), + type: buildTypeJsonSchema({ + allowedAdditionalValues: allowedAdditionalTypeValues, + }), + groupName: { + description: 'Custom group name.', + type: 'string', + }, + newlinesInside: newlinesInsideJsonSchema, + order: orderJsonSchema, + ...additionalSortProperties, + } +} +function buildPopulatedCustomGroupMatchPropertiesJsonSchema( + customGroupMatchOptionsJsonSchema, +) { + return { + elementNamePattern: buildRegexJsonSchema(), + ...customGroupMatchOptionsJsonSchema, + } +} +export { + buildCommonGroupsJsonSchemas, + buildCustomGroupModifiersJsonSchema, + buildCustomGroupSelectorJsonSchema, + buildCustomGroupsArrayJsonSchema, + buildGroupsJsonSchema, + newlinesBetweenJsonSchema, + newlinesInsideJsonSchema, +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/common-json-schemas.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/common-json-schemas.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b1da35091f04673896fa779925f081d51dcfebf5 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/common-json-schemas.d.ts @@ -0,0 +1,72 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +/** + * JSON schema for the sort order option. Validates ascending or descending sort + * direction. + */ +export declare let orderJsonSchema: JSONSchema4 +export declare let matchesAstSelectorJsonSchema: JSONSchema4 +/** + * Builds a collection of common JSON schemas used across sorting rules. + * + * Creates schemas for standard sorting options that are shared by multiple + * rules. This ensures consistent validation across the plugin. + * + * @param options - Configuration options. + * @param options.additionalSortProperties - Extra sort-related option schemas + * to add at the root level and inside fallbackSort. + * @returns Object containing common JSON schemas for rule validation. + */ +export declare function buildCommonJsonSchemas({ + allowedAdditionalTypeValues, + additionalSortProperties, +}?: { + additionalSortProperties?: Record + allowedAdditionalTypeValues?: string[] +}): Record +/** + * Builds JSON schema for fallback sort configuration. + * + * Creates a schema for the fallback sorting option that is applied when the + * primary sort results in equality. Allows customization through additional + * properties. + * + * @param options - Configuration options. + * @param options.additionalProperties - Extra properties to include in the + * schema. + * @returns JSON schema for fallback sort validation. + */ +export declare function buildFallbackSortJsonSchema({ + allowedAdditionalTypeValues, + additionalProperties, +}: { + additionalProperties: Record | undefined + allowedAdditionalTypeValues: undefined | string[] +}): JSONSchema4 +/** + * Builds JSON schema for conditional configuration blocks. + * + * Creates a schema for configuration that is applied only when certain + * conditions are met. Used for context-specific sorting rules where different + * configurations apply based on element patterns. + * + * @param options - Configuration options for the conditional block. + * @param options.additionalProperties - Extra properties to include in the + * schema. + * @returns JSON schema for conditional configuration validation. + */ +export declare function buildUseConfigIfJsonSchema({ + additionalProperties, +}?: { + additionalProperties?: Record +}): JSONSchema4 +export declare function buildTypeJsonSchema({ + allowedAdditionalValues, +}: { + allowedAdditionalValues: undefined | string[] +}): JSONSchema4 +export declare function buildRegexJsonSchema({ + additionalProperties, +}?: { + additionalProperties?: Record +}): JSONSchema4 +export declare let useExperimentalDependencyDetectionJsonSchema: JSONSchema4 diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/common-json-schemas.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/common-json-schemas.js new file mode 100644 index 0000000000000000000000000000000000000000..9d55f3b1eeee533d5a24b4553edbda7630530fae --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/common-json-schemas.js @@ -0,0 +1,207 @@ +/** + * JSON schema for the sort order option. Validates ascending or descending sort + * direction. + */ +var orderJsonSchema = { + description: + 'Specifies whether to sort items in ascending or descending order.', + enum: ['asc', 'desc'], + type: 'string', +} +/** + * JSON schema for the custom alphabet option. Used with 'custom' sort type to + * define character ordering. + */ +var alphabetJsonSchema = { + description: + "Used only when the `type` option is set to `'custom'`. Specifies the custom alphabet for sorting.", + type: 'string', +} +/** + * JSON schema for the locales option. Validates locale settings for + * locale-aware string comparison. + */ +var localesJsonSchema = { + oneOf: [ + { type: 'string' }, + { + items: { type: 'string' }, + type: 'array', + }, + ], + description: 'Specifies the sorting locales.', +} +/** + * JSON schema for the ignoreCase option. Controls case sensitivity in string + * comparisons. + */ +var ignoreCaseJsonSchema = { + description: 'Controls whether sorting should be case-sensitive or not.', + type: 'boolean', +} +/** + * JSON schema for the special characters handling option. Defines how special + * characters are treated during sorting. + */ +var specialCharactersJsonSchema = { + description: + 'Specifies whether to trim, remove, or keep special characters before sorting.', + enum: ['remove', 'trim', 'keep'], + type: 'string', +} +var matchesAstSelectorJsonSchema = { + description: + 'Specifies an AST selector to match elements for conditional configuration.', + type: 'string', +} +/** + * Builds a collection of common JSON schemas used across sorting rules. + * + * Creates schemas for standard sorting options that are shared by multiple + * rules. This ensures consistent validation across the plugin. + * + * @param options - Configuration options. + * @param options.additionalSortProperties - Extra sort-related option schemas + * to add at the root level and inside fallbackSort. + * @returns Object containing common JSON schemas for rule validation. + */ +function buildCommonJsonSchemas({ + allowedAdditionalTypeValues, + additionalSortProperties, +} = {}) { + return { + fallbackSort: buildFallbackSortJsonSchema({ + additionalProperties: additionalSortProperties, + allowedAdditionalTypeValues, + }), + type: buildTypeJsonSchema({ + allowedAdditionalValues: allowedAdditionalTypeValues, + }), + specialCharacters: specialCharactersJsonSchema, + ignoreCase: ignoreCaseJsonSchema, + alphabet: alphabetJsonSchema, + locales: localesJsonSchema, + order: orderJsonSchema, + ...additionalSortProperties, + } +} +/** + * Builds JSON schema for fallback sort configuration. + * + * Creates a schema for the fallback sorting option that is applied when the + * primary sort results in equality. Allows customization through additional + * properties. + * + * @param options - Configuration options. + * @param options.additionalProperties - Extra properties to include in the + * schema. + * @returns JSON schema for fallback sort validation. + */ +function buildFallbackSortJsonSchema({ + allowedAdditionalTypeValues, + additionalProperties, +}) { + return { + properties: { + type: buildTypeJsonSchema({ + allowedAdditionalValues: allowedAdditionalTypeValues, + }), + order: orderJsonSchema, + ...additionalProperties, + }, + description: 'Fallback sort order.', + additionalProperties: false, + required: ['type'], + type: 'object', + } +} +/** + * Builds JSON schema for conditional configuration blocks. + * + * Creates a schema for configuration that is applied only when certain + * conditions are met. Used for context-specific sorting rules where different + * configurations apply based on element patterns. + * + * @param options - Configuration options for the conditional block. + * @param options.additionalProperties - Extra properties to include in the + * schema. + * @returns JSON schema for conditional configuration validation. + */ +function buildUseConfigIfJsonSchema({ additionalProperties } = {}) { + return { + description: + 'Specifies filters to match a particular options configuration for a given element to sort.', + properties: { + allNamesMatchPattern: buildRegexJsonSchema(), + ...additionalProperties, + }, + additionalProperties: false, + type: 'object', + } +} +function buildTypeJsonSchema({ allowedAdditionalValues }) { + return { + enum: [ + 'alphabetical', + 'natural', + 'line-length', + 'custom', + 'unsorted', + 'subgroup-order', + ...(allowedAdditionalValues ?? []), + ], + description: 'Specifies the sorting method.', + type: 'string', + } +} +function buildRegexJsonSchema({ additionalProperties } = {}) { + return { + oneOf: [ + { + items: buildSingleRegexJsonSchema({ additionalProperties }), + type: 'array', + }, + buildSingleRegexJsonSchema({ additionalProperties }), + ], + description: 'Regular expression.', + } +} +function buildSingleRegexJsonSchema({ additionalProperties }) { + return { + oneOf: [ + { + properties: { + ...additionalProperties, + pattern: { + description: 'Regular expression pattern.', + type: 'string', + }, + flags: { + description: 'Regular expression flags.', + type: 'string', + }, + }, + additionalProperties: false, + required: ['pattern'], + type: 'object', + }, + { type: 'string' }, + ], + description: 'Regular expression.', + } +} +var useExperimentalDependencyDetectionJsonSchema = { + description: + 'Enables experimental dependency detection for sorting rules that support it.', + type: 'boolean', +} +export { + buildCommonJsonSchemas, + buildFallbackSortJsonSchema, + buildRegexJsonSchema, + buildTypeJsonSchema, + buildUseConfigIfJsonSchema, + matchesAstSelectorJsonSchema, + orderJsonSchema, + useExperimentalDependencyDetectionJsonSchema, +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/common-partition-json-schemas.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/common-partition-json-schemas.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7ace839b7841400f775d7a6ef0798e9a22358c93 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/common-partition-json-schemas.d.ts @@ -0,0 +1,11 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +/** + * JSON schema for the partition by comment option. Validates configuration for + * splitting elements into partitions based on comments. + */ +export declare let partitionByCommentJsonSchema: JSONSchema4 +/** + * JSON schema for the partition by new line option. Controls whether to create + * separate partitions when newlines are encountered. + */ +export declare let partitionByNewlineJsonSchema: JSONSchema4 diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/common-partition-json-schemas.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/common-partition-json-schemas.js new file mode 100644 index 0000000000000000000000000000000000000000..5e9f8482b22dd9c6e2c9d6c3171e5c8714a1d7e9 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/common-partition-json-schemas.js @@ -0,0 +1,41 @@ +import { buildRegexJsonSchema } from './common-json-schemas.js' +var allowedPartitionByCommentJsonSchemas = [ + { type: 'boolean' }, + buildRegexJsonSchema(), +] +/** + * JSON schema for the partition by comment option. Validates configuration for + * splitting elements into partitions based on comments. + */ +var partitionByCommentJsonSchema = { + oneOf: [ + ...allowedPartitionByCommentJsonSchemas, + { + properties: { + block: { + description: 'Enables specific block comments to separate the nodes.', + oneOf: allowedPartitionByCommentJsonSchemas, + }, + line: { + description: 'Enables specific line comments to separate the nodes.', + oneOf: allowedPartitionByCommentJsonSchemas, + }, + }, + additionalProperties: false, + minProperties: 1, + type: 'object', + }, + ], + description: + 'Enables the use of comments to separate the nodes into logical groups.', +} +/** + * JSON schema for the partition by new line option. Controls whether to create + * separate partitions when newlines are encountered. + */ +var partitionByNewlineJsonSchema = { + description: + 'Enables the use of newlines to separate the nodes into logical groups.', + type: 'boolean', +} +export { partitionByCommentJsonSchema, partitionByNewlineJsonSchema } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/scoped-regex-json-schema.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/scoped-regex-json-schema.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3b7744b0cb38b7356bc0d05f638aacbd967f92ae --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/scoped-regex-json-schema.d.ts @@ -0,0 +1,2 @@ +import { JSONSchema4 } from '@typescript-eslint/utils/json-schema' +export declare let scopedRegexJsonSchema: JSONSchema4 diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/scoped-regex-json-schema.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/scoped-regex-json-schema.js new file mode 100644 index 0000000000000000000000000000000000000000..cd52354129b9b961987188889dbe34196ba61813 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/json-schemas/scoped-regex-json-schema.js @@ -0,0 +1,11 @@ +import { buildRegexJsonSchema } from './common-json-schemas.js' +import { regexScopes } from '../../types/scoped-regex-option.js' +var scopedRegexJsonSchema = buildRegexJsonSchema({ + additionalProperties: { + scope: { + enum: [...regexScopes], + type: 'string', + }, + }, +}) +export { scopedRegexJsonSchema } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-comment-above-fixes.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-comment-above-fixes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b083acfb1b124abfc1111c12c0eb5553aa84a235 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-comment-above-fixes.d.ts @@ -0,0 +1,61 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { CommonGroupsOptions } from '../types/common-groups-options.js' +import { SortingNode } from '../types/sorting-node.js' +/** + * Parameters for generating comment-above fixes. + */ +interface MakeCommentAboveFixesParameters { + /** + * Configuration options containing groups and custom groups. + */ + options: Pick< + CommonGroupsOptions, + 'customGroups' | 'groups' + > + /** + * ESLint source code object for accessing comments and tokens. + */ + sourceCode: TSESLint.SourceCode + /** + * Sorted array of nodes to process for comment fixes. + */ + sortedNodes: SortingNode[] + /** + * ESLint fixer object for creating fix operations. + */ + fixer: TSESLint.RuleFixer +} +/** + * Generates fixes for adding or removing comment separators above groups. + * + * Processes sorted nodes to ensure that comment separators defined in the + * groups configuration are properly placed. This includes: + * + * - Adding missing comment separators above groups + * - Removing auto-generated comments that are no longer needed + * - Ensuring comments are in the correct position after sorting. + * + * The function handles the first node specially (checking if it needs a + * comment) and then processes pairs of adjacent nodes to determine comment + * placement. + * + * @example + * + * ```ts + * // Configuration with commentAbove + * const groups = ['imports', { commentAbove: 'Components' }, 'components'] + * + * // Will add '// Components' comment above the components group + * // Will remove any misplaced auto-generated comments + * ``` + * + * @param params - Parameters for generating fixes. + * @returns Array of ESLint fix operations to apply. + */ +export declare function makeCommentAboveFixes({ + sortedNodes, + sourceCode, + options, + fixer, +}: MakeCommentAboveFixesParameters): TSESLint.RuleFix[] +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-comment-above-fixes.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-comment-above-fixes.js new file mode 100644 index 0000000000000000000000000000000000000000..b05c71f257a3939db7f1b3748d109e96c4fae840 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-comment-above-fixes.js @@ -0,0 +1,153 @@ +import { isGroupWithOverridesOption } from './is-group-with-overrides-option.js' +import { getGroupIndex } from './get-group-index.js' +import { getCommentsBefore } from './get-comments-before.js' +import { getCommentAboveThatShouldExist } from './get-comment-above-that-should-exist.js' +/** + * Generates fixes for adding or removing comment separators above groups. + * + * Processes sorted nodes to ensure that comment separators defined in the + * groups configuration are properly placed. This includes: + * + * - Adding missing comment separators above groups + * - Removing auto-generated comments that are no longer needed + * - Ensuring comments are in the correct position after sorting. + * + * The function handles the first node specially (checking if it needs a + * comment) and then processes pairs of adjacent nodes to determine comment + * placement. + * + * @example + * + * ```ts + * // Configuration with commentAbove + * const groups = ['imports', { commentAbove: 'Components' }, 'components'] + * + * // Will add '// Components' comment above the components group + * // Will remove any misplaced auto-generated comments + * ``` + * + * @param params - Parameters for generating fixes. + * @returns Array of ESLint fix operations to apply. + */ +function makeCommentAboveFixes({ sortedNodes, sourceCode, options, fixer }) { + let allAutoAddedComments = new Set( + options.groups + .filter(group => isGroupWithOverridesOption(group)) + .map(({ commentAbove }) => commentAbove) + .filter(comment => comment !== void 0), + ) + let fixes = [] + let firstNodeFixes = makeCommentAboveFix({ + nextSortedSortingNode: sortedNodes[0], + sortedSortingNode: null, + allAutoAddedComments, + sourceCode, + options, + fixer, + }) + fixes.push(...firstNodeFixes) + for (let i = 0; i < sortedNodes.length - 1; i++) { + let sortedSortingNode = sortedNodes.at(i) + let nodeFixes = makeCommentAboveFix({ + nextSortedSortingNode: sortedNodes.at(i + 1), + allAutoAddedComments, + sortedSortingNode, + sourceCode, + options, + fixer, + }) + fixes.push(...nodeFixes) + } + return fixes +} +/** + * Creates fixes for comment placement between two adjacent nodes. + * + * Determines whether a comment separator should exist between two nodes based + * on their group indices and configuration. Handles: + * + * - Adding a new comment if required but missing + * - Removing outdated auto-generated comments + * - Preserving manually added comments. + * + * The function checks if the next node should have a comment above it based on + * the groups configuration, then ensures the comment state matches the expected + * state. + * + * @param params - Parameters for creating fixes. + * @param params.sortedSortingNode - Previous node in sorted order (null for + * first node). + * @param params.nextSortedSortingNode - Current node to potentially add comment + * above. + * @param params.allAutoAddedComments - Set of all auto-generated comment texts. + * @param params.sourceCode - ESLint source code object. + * @param params.options - Groups and configuration options. + * @param params.fixer - ESLint fixer for creating fixes. + * @returns Array of fixes to add/remove comments. + */ +function makeCommentAboveFix({ + nextSortedSortingNode, + allAutoAddedComments, + sortedSortingNode, + sourceCode, + options, + fixer, +}) { + let leftGroupIndex = + sortedSortingNode ? getGroupIndex(options.groups, sortedSortingNode) : -1 + let rightGroupIndex = getGroupIndex(options.groups, nextSortedSortingNode) + let commentAboveThatShouldExist = getCommentAboveThatShouldExist({ + options: { + ...options, + groups: options.groups, + }, + sortingNode: nextSortedSortingNode, + rightGroupIndex, + leftGroupIndex, + sourceCode, + }) + let commentsBefore = getCommentsBefore({ + node: nextSortedSortingNode.node, + sourceCode, + }) + let autoAddedCommentsAboveToRemove = commentsBefore + .filter( + comment => + !commentAboveThatShouldExist?.comment || + comment.value.slice(1) !== commentAboveThatShouldExist.comment, + ) + .filter( + comment => + comment.type === 'Line' && + allAutoAddedComments.has(comment.value.slice(1)), + ) + let fixes = [] + for (let autoAddedCommentAboveToRemove of autoAddedCommentsAboveToRemove) { + let nextToken = sourceCode.getTokenAfter(autoAddedCommentAboveToRemove) + fixes.push( + fixer.removeRange([ + autoAddedCommentAboveToRemove.range[0], + nextToken.range[0], + ]), + ) + } + if (commentAboveThatShouldExist && !commentAboveThatShouldExist.exists) { + let nodeToPutCommentBefore + if ( + !sourceCode.getTokenBefore(nextSortedSortingNode.node) || + !commentsBefore[0] + ) { + nodeToPutCommentBefore = nextSortedSortingNode.node + } else { + ;[nodeToPutCommentBefore] = commentsBefore + } + fixes.push( + fixer.insertTextBeforeRange( + nodeToPutCommentBefore.range, + `// ${commentAboveThatShouldExist.comment}\n`, + ), + ) + } + return fixes +} +export { makeCommentAboveFixes } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-comment-after-fixes.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-comment-after-fixes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..86603a0cf723ee35474f5667afb2d72bbfeefe02 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-comment-after-fixes.d.ts @@ -0,0 +1,59 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { SortingNode } from '../types/sorting-node.js' +/** + * Parameters for generating comment-after fixes. + */ +interface MakeCommentAfterFixesParameters { + /** + * ESLint source code object for accessing comments and tokens. + */ + sourceCode: TSESLint.SourceCode + /** + * Array of nodes in their sorted order. + */ + sortedNodes: SortingNode[] + /** + * ESLint fixer object for creating fix operations. + */ + fixer: TSESLint.RuleFixer + /** + * Array of nodes in their original order. + */ + nodes: SortingNode[] +} +/** + * Generates fixes for handling inline trailing comments during sorting. + * + * Ensures that inline comments (comments on the same line after code) are + * properly moved when their associated nodes are reordered during sorting. This + * maintains the relationship between code and its inline comments. + * + * The function compares the original node positions with the sorted positions + * and creates fixes only for nodes that have actually moved. For each moved + * node, it delegates to `makeSingleNodeCommentAfterFixes` to handle the + * specific comment adjustments. + * + * @example + * + * ```ts + * // Original code: + * const b = 2 // second value + * const a = 1 // first value + * + * // After sorting (with comment fixes): + * const a = 1 // first value + * const b = 2 // second value + * + * // Comments stay with their associated nodes + * ``` + * + * @param params - Parameters for generating fixes. + * @returns Array of ESLint fix operations to apply. + */ +export declare function makeCommentAfterFixes({ + sortedNodes, + sourceCode, + fixer, + nodes, +}: MakeCommentAfterFixesParameters): TSESLint.RuleFix[] +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-comment-after-fixes.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-comment-after-fixes.js new file mode 100644 index 0000000000000000000000000000000000000000..b462edf51015102487919fdadd4351ba4345ac8d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-comment-after-fixes.js @@ -0,0 +1,52 @@ +import { makeSingleNodeCommentAfterFixes } from './make-single-node-comment-after-fixes.js' +/** + * Generates fixes for handling inline trailing comments during sorting. + * + * Ensures that inline comments (comments on the same line after code) are + * properly moved when their associated nodes are reordered during sorting. This + * maintains the relationship between code and its inline comments. + * + * The function compares the original node positions with the sorted positions + * and creates fixes only for nodes that have actually moved. For each moved + * node, it delegates to `makeSingleNodeCommentAfterFixes` to handle the + * specific comment adjustments. + * + * @example + * + * ```ts + * // Original code: + * const b = 2 // second value + * const a = 1 // first value + * + * // After sorting (with comment fixes): + * const a = 1 // first value + * const b = 2 // second value + * + * // Comments stay with their associated nodes + * ``` + * + * @param params - Parameters for generating fixes. + * @returns Array of ESLint fix operations to apply. + */ +function makeCommentAfterFixes({ sortedNodes, sourceCode, fixer, nodes }) { + let fixes = [] + for (let max = nodes.length, i = 0; i < max; i++) { + let sortingNode = nodes.at(i) + let sortedSortingNode = sortedNodes.at(i) + let { node } = sortingNode + let { node: sortedNode } = sortedSortingNode + if (node === sortedNode) { + continue + } + fixes.push( + ...makeSingleNodeCommentAfterFixes({ + sortedNode, + sourceCode, + fixer, + node, + }), + ) + } + return fixes +} +export { makeCommentAfterFixes } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-fixes.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-fixes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4dafbbb46a69d9612d6c79d0217e25ebad1f51be --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-fixes.d.ts @@ -0,0 +1,106 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { CommonPartitionOptions } from '../types/common-partition-options.js' +import { NewlinesBetweenValueGetter } from './get-newlines-between-errors.js' +import { CommonGroupsOptions } from '../types/common-groups-options.js' +import { SortingNode } from '../types/sorting-node.js' +/** + * Parameters for generating all types of fixes during sorting. + * + * @template T - Type of sorting node extending the base SortingNode. + */ +interface MakeFixesParameters { + /** + * Optional configuration for various sorting behaviors. + */ + options?: Pick & + CommonGroupsOptions + /** + * Optional function to customize newlines between specific nodes. + */ + newlinesBetweenValueGetter?: NewlinesBetweenValueGetter + /** + * Whether to ignore the highest block comment for the first node. Useful + * for preserving file-level documentation comments. + */ + ignoreFirstNodeHighestBlockComment?: boolean + /** + * ESLint source code object for accessing comments and tokens. + */ + sourceCode: TSESLint.SourceCode + /** + * Whether any comment-above configuration is missing its comment. + */ + hasCommentAboveMissing: boolean + /** + * ESLint fixer object for creating fix operations. + */ + fixer: TSESLint.RuleFixer + /** + * Array of nodes in their sorted order. + */ + sortedNodes: T[] + /** + * Array of nodes in their original order. + */ + nodes: T[] +} +/** + * Orchestrates the generation of all necessary fixes for sorting operations. + * + * Coordinates different types of fixes in a specific priority order to ensure + * proper code transformation: + * + * 1. Order fixes - Reorders the nodes themselves + * 2. Comment-after fixes - Handles inline trailing comments (if needed) + * 3. Newlines fixes - Adjusts spacing between groups (if configured) + * 4. Comment-above fixes - Adds/removes separator comments (if only these are + * needed). + * + * The function returns early when higher-priority fixes are found, as applying + * multiple fix types simultaneously could cause conflicts. This ensures that + * each auto-fix operation focuses on one type of change at a time. + * + * Notes: + * + * - Order fixes replace node ranges; comment-after/newlines operate on inter-node + * ranges. They are designed not to overlap, but if ESLint discards + * overlapping replacements, a subsequent lint pass will apply the remaining + * fixes. + * - Comment-above fixes are not combined with other fix types to avoid noisy + * changes; they are applied only when nothing else is pending. + * + * @example + * + * ```ts + * // Configuration with groups and newlines + * const fixes = makeFixes({ + * nodes: originalNodes, + * sortedNodes: sortedNodes, + * options: { + * groups: ['imports', 'types', 'functions'], + * newlinesBetween: 1, + * }, + * sourceCode, + * fixer, + * hasCommentAboveMissing: false, + * }) + * // Returns order fixes if nodes need reordering + * // Otherwise returns newlines fixes if spacing needs adjustment + * // Otherwise returns empty array + * ``` + * + * @template T - Type of sorting node. + * @param params - Parameters for generating fixes. + * @returns Array of ESLint fix operations to apply, prioritized by type. + */ +export declare function makeFixes({ + ignoreFirstNodeHighestBlockComment, + newlinesBetweenValueGetter, + hasCommentAboveMissing, + sortedNodes, + sourceCode, + options, + fixer, + nodes, +}: MakeFixesParameters): TSESLint.RuleFix[] +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-fixes.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-fixes.js new file mode 100644 index 0000000000000000000000000000000000000000..ee65335463a68b384a7487e3600b9dd5d2dfcd9a --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-fixes.js @@ -0,0 +1,114 @@ +import { makeNewlinesBetweenFixes } from './make-newlines-between-fixes.js' +import { makeCommentAfterFixes } from './make-comment-after-fixes.js' +import { makeCommentAboveFixes } from './make-comment-above-fixes.js' +import { makeOrderFixes } from './make-order-fixes.js' +/** + * Orchestrates the generation of all necessary fixes for sorting operations. + * + * Coordinates different types of fixes in a specific priority order to ensure + * proper code transformation: + * + * 1. Order fixes - Reorders the nodes themselves + * 2. Comment-after fixes - Handles inline trailing comments (if needed) + * 3. Newlines fixes - Adjusts spacing between groups (if configured) + * 4. Comment-above fixes - Adds/removes separator comments (if only these are + * needed). + * + * The function returns early when higher-priority fixes are found, as applying + * multiple fix types simultaneously could cause conflicts. This ensures that + * each auto-fix operation focuses on one type of change at a time. + * + * Notes: + * + * - Order fixes replace node ranges; comment-after/newlines operate on inter-node + * ranges. They are designed not to overlap, but if ESLint discards + * overlapping replacements, a subsequent lint pass will apply the remaining + * fixes. + * - Comment-above fixes are not combined with other fix types to avoid noisy + * changes; they are applied only when nothing else is pending. + * + * @example + * + * ```ts + * // Configuration with groups and newlines + * const fixes = makeFixes({ + * nodes: originalNodes, + * sortedNodes: sortedNodes, + * options: { + * groups: ['imports', 'types', 'functions'], + * newlinesBetween: 1, + * }, + * sourceCode, + * fixer, + * hasCommentAboveMissing: false, + * }) + * // Returns order fixes if nodes need reordering + * // Otherwise returns newlines fixes if spacing needs adjustment + * // Otherwise returns empty array + * ``` + * + * @template T - Type of sorting node. + * @param params - Parameters for generating fixes. + * @returns Array of ESLint fix operations to apply, prioritized by type. + */ +function makeFixes({ + ignoreFirstNodeHighestBlockComment, + newlinesBetweenValueGetter, + hasCommentAboveMissing, + sortedNodes, + sourceCode, + options, + fixer, + nodes, +}) { + let orderFixes = makeOrderFixes({ + ignoreFirstNodeHighestBlockComment, + sortedNodes, + sourceCode, + options, + nodes, + fixer, + }) + let commentAfterFixes = makeCommentAfterFixes({ + sortedNodes, + sourceCode, + nodes, + fixer, + }) + if (commentAfterFixes.length > 0) { + return [...orderFixes, ...commentAfterFixes] + } + if (options?.groups) { + let newlinesFixes = makeNewlinesBetweenFixes({ + options: { + ...options, + newlinesBetween: options.newlinesBetween, + groups: options.groups, + }, + newlinesBetweenValueGetter, + sortedNodes, + sourceCode, + fixer, + nodes, + }) + if (newlinesFixes.length > 0) { + return [...orderFixes, ...newlinesFixes] + } + } + if (orderFixes.length > 0) { + return orderFixes + } + if (!hasCommentAboveMissing || !options?.groups) { + return [] + } + return makeCommentAboveFixes({ + options: { + ...options, + groups: options.groups, + }, + sortedNodes, + sourceCode, + fixer, + }) +} +export { makeFixes } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-newlines-between-fixes.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-newlines-between-fixes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4eb4460ab440b8aaf8bd0601bf9a3fa802ddebe8 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-newlines-between-fixes.d.ts @@ -0,0 +1,92 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { NewlinesBetweenValueGetter } from './get-newlines-between-errors.js' +import { CommonGroupsOptions } from '../types/common-groups-options.js' +import { SortingNode } from '../types/sorting-node.js' +/** + * Parameters for generating newlines-between fixes. + * + * @template T - Type of sorting node extending the base SortingNode. + */ +interface MakeNewlinesBetweenFixesParameters { + /** + * Optional function to customize newlines between specific nodes. Allows + * overriding the default newlines behavior for specific cases. + */ + newlinesBetweenValueGetter?: NewlinesBetweenValueGetter + /** + * Configuration options for groups and newlines. + */ + options: CommonGroupsOptions + /** + * ESLint source code object for accessing text and locations. + */ + sourceCode: TSESLint.SourceCode + /** + * ESLint fixer object for creating fix operations. + */ + fixer: TSESLint.RuleFixer + /** + * Array of nodes in their sorted order. + */ + sortedNodes: T[] + /** + * Array of nodes in their original order. + */ + nodes: T[] +} +/** + * Generates fixes for adjusting newlines between groups of sorted elements. + * + * Processes pairs of adjacent nodes to ensure the correct number of newlines + * between them based on their group membership and configuration. The + * function: + * + * - Skips nodes in different partitions (they're sorted independently) + * - Skips cases where group order would be violated + * - Respects 'ignore' settings that preserve existing spacing + * - Calculates required newlines based on group configuration + * - Applies custom newlines getter if provided. + * + * @example + * + * ```ts + * // Configuration with newlines between groups + * const options = { + * groups: ['imports', 'types', 'functions'], + * newlinesBetween: 1, // 1 newline between groups + * } + * + * // Original: imports and types with no separation + * // After fix: adds 1 blank line between import and type groups + * ``` + * + * @example + * + * ```ts + * // Custom newlines getter + * const newlinesBetweenValueGetter = ({ + * left, + * right, + * computedNewlinesBetween, + * }) => { + * // Add extra newline before main function + * if (right.name === 'main') { + * return computedNewlinesBetween + 1 + * } + * return computedNewlinesBetween + * } + * ``` + * + * @template T - Type of sorting node. + * @param params - Parameters for generating newlines fixes. + * @returns Array of ESLint fix operations to adjust spacing. + */ +export declare function makeNewlinesBetweenFixes({ + newlinesBetweenValueGetter, + sortedNodes, + sourceCode, + options, + fixer, + nodes, +}: MakeNewlinesBetweenFixesParameters): TSESLint.RuleFix[] +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-newlines-between-fixes.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-newlines-between-fixes.js new file mode 100644 index 0000000000000000000000000000000000000000..79e6274af4d5eca38442f924f3664c8c9cc58925 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-newlines-between-fixes.js @@ -0,0 +1,185 @@ +import { getNewlinesBetweenOption } from './get-newlines-between-option.js' +import { getLinesBetween } from './get-lines-between.js' +import { getGroupIndex } from './get-group-index.js' +import { getNodeRange } from './get-node-range.js' +/** + * Generates fixes for adjusting newlines between groups of sorted elements. + * + * Processes pairs of adjacent nodes to ensure the correct number of newlines + * between them based on their group membership and configuration. The + * function: + * + * - Skips nodes in different partitions (they're sorted independently) + * - Skips cases where group order would be violated + * - Respects 'ignore' settings that preserve existing spacing + * - Calculates required newlines based on group configuration + * - Applies custom newlines getter if provided. + * + * @example + * + * ```ts + * // Configuration with newlines between groups + * const options = { + * groups: ['imports', 'types', 'functions'], + * newlinesBetween: 1, // 1 newline between groups + * } + * + * // Original: imports and types with no separation + * // After fix: adds 1 blank line between import and type groups + * ``` + * + * @example + * + * ```ts + * // Custom newlines getter + * const newlinesBetweenValueGetter = ({ + * left, + * right, + * computedNewlinesBetween, + * }) => { + * // Add extra newline before main function + * if (right.name === 'main') { + * return computedNewlinesBetween + 1 + * } + * return computedNewlinesBetween + * } + * ``` + * + * @template T - Type of sorting node. + * @param params - Parameters for generating newlines fixes. + * @returns Array of ESLint fix operations to adjust spacing. + */ +function makeNewlinesBetweenFixes({ + newlinesBetweenValueGetter, + sortedNodes, + sourceCode, + options, + fixer, + nodes, +}) { + let fixes = [] + for (let i = 0; i < sortedNodes.length - 1; i++) { + let sortingNode = nodes.at(i) + let nextSortingNode = nodes.at(i + 1) + let sortedSortingNode = sortedNodes.at(i) + let nextSortedSortingNode = sortedNodes.at(i + 1) + if (sortedSortingNode.partitionId !== nextSortedSortingNode.partitionId) { + continue + } + let nodeGroupIndex = getGroupIndex(options.groups, sortedSortingNode) + let nextNodeGroupIndex = getGroupIndex( + options.groups, + nextSortedSortingNode, + ) + if (nodeGroupIndex > nextNodeGroupIndex) { + continue + } + let newlinesBetween = getNewlinesBetweenOption({ + nextNodeGroupIndex, + nodeGroupIndex, + options, + }) + newlinesBetween = + newlinesBetweenValueGetter?.({ + computedNewlinesBetween: newlinesBetween, + right: nextSortedSortingNode, + left: sortedSortingNode, + }) ?? newlinesBetween + if (newlinesBetween === 'ignore') { + continue + } + let currentNodeRange = getNodeRange({ + node: sortingNode.node, + sourceCode, + }) + let nextNodeRangeStart = getNodeRange({ + node: nextSortingNode.node, + sourceCode, + }).at(0) + if ( + getLinesBetween(sourceCode, sortingNode, nextSortingNode) === + newlinesBetween + ) { + continue + } + let rangeToReplace = [currentNodeRange.at(1), nextNodeRangeStart] + let textBetweenNodes = sourceCode.text.slice( + currentNodeRange.at(1), + nextNodeRangeStart, + ) + let rangeReplacement = computeRangeReplacement({ + isOnSameLine: + sortingNode.node.loc.end.line === nextSortingNode.node.loc.start.line, + textBetweenNodes, + newlinesBetween, + }) + fixes.push(fixer.replaceTextRange(rangeToReplace, rangeReplacement)) + } + return fixes +} +/** + * Computes the replacement text for adjusting newlines between nodes. + * + * Handles the logic of adding or removing newlines while preserving necessary + * content like comments and semicolons. Special handling for: + * + * - Removing excessive newlines when fewer are needed + * - Adding newlines when more are needed + * - Preserving inline placement when nodes are on the same line. + * + * @param params - Parameters for computing replacement. + * @param params.textBetweenNodes - Original text between the two nodes. + * @param params.newlinesBetween - Number of newlines required (0 or more). + * @param params.isOnSameLine - Whether nodes are currently on the same line. + * @returns Replacement text with correct newlines, or undefined if no change + * needed. + */ +function computeRangeReplacement({ + textBetweenNodes, + newlinesBetween, + isOnSameLine, +}) { + let textBetweenNodesWithoutInvalidNewlines = + getStringWithoutInvalidNewlines(textBetweenNodes) + if (newlinesBetween === 0) { + return textBetweenNodesWithoutInvalidNewlines + } + let rangeReplacement = textBetweenNodesWithoutInvalidNewlines + for (let index = 0; index < newlinesBetween; index++) { + rangeReplacement = addNewlineBeforeFirstNewline(rangeReplacement) + } + if (!isOnSameLine) { + return rangeReplacement + } + return addNewlineBeforeFirstNewline(rangeReplacement) +} +/** + * Adds a newline before the first existing newline or at the end of string. + * + * Used to incrementally add newlines while preserving existing content. If no + * newline exists, appends one at the end. Otherwise, inserts before the first + * newline to maintain proper spacing. + * + * @param value - String to add a newline to. + * @returns String with an additional newline. + */ +function addNewlineBeforeFirstNewline(value) { + let firstNewlineIndex = value.indexOf('\n') + if (firstNewlineIndex === -1) { + return `${value}\n` + } + return `${value.slice(0, firstNewlineIndex)}\n${value.slice(firstNewlineIndex)}` +} +/** + * Removes excessive newlines from a string. + * + * Normalizes spacing by collapsing multiple consecutive newlines into single + * newlines and removing empty lines that contain only whitespace. + * + * @param value - String potentially containing excessive newlines. + * @returns String with normalized newlines. + */ +function getStringWithoutInvalidNewlines(value) { + return value.replaceAll(/\n\s*\n/gu, '\n').replaceAll(/\n+/gu, '\n') +} +export { makeNewlinesBetweenFixes } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-order-fixes.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-order-fixes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee3a0337404f22b2fb2f40f2933b499905ea0705 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-order-fixes.d.ts @@ -0,0 +1,85 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { CommonPartitionOptions } from '../types/common-partition-options.js' +import { SortingNode } from '../types/sorting-node.js' +/** + * Parameters for generating order fixes. + */ +interface MakeOrderFixesParameters { + /** + * Optional configuration options. + */ + options?: Pick + /** + * Whether to ignore the highest block comment for the first node. Useful + * for preserving file-level documentation comments. + */ + ignoreFirstNodeHighestBlockComment?: boolean + /** + * ESLint source code object for accessing text and ranges. + */ + sourceCode: TSESLint.SourceCode + /** + * Array of nodes in their sorted order. + */ + sortedNodes: SortingNode[] + /** + * ESLint fixer object for creating fix operations. + */ + fixer: TSESLint.RuleFixer + /** + * Array of nodes in their original order. + */ + nodes: SortingNode[] +} +/** + * Generates fixes for reordering nodes to their sorted positions. + * + * Creates text replacement fixes that swap node positions to achieve the + * desired sort order. The function handles several important edge cases: + * + * - Preserves leading comments and documentation + * - Maintains file-level block comments for the first node + * - Adds safety semicolons when needed to prevent ASI issues + * - Respects partition boundaries defined by comments. + * + * The function iterates through each node position and replaces the original + * node text with the text from the node that should be in that position + * according to the sorted order. + * + * @example + * + * ```ts + * // Original order: + * const b = 2 + * const a = 1 + * + * // After applying order fixes: + * const a = 1 + * const b = 2 + * ``` + * + * @example + * + * ```ts + * // Safety semicolon example + * // Original: + * const b = 2 + * const a = 1 // 'a' will move to first position + * + * // After fix (semicolon added to prevent ASI issues): + * const a = 1 + * const b = 2 + * ``` + * + * @param params - Parameters for generating order fixes. + * @returns Array of ESLint fix operations to reorder nodes. + */ +export declare function makeOrderFixes({ + ignoreFirstNodeHighestBlockComment, + sortedNodes, + sourceCode, + options, + fixer, + nodes, +}: MakeOrderFixesParameters): TSESLint.RuleFix[] +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-order-fixes.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-order-fixes.js new file mode 100644 index 0000000000000000000000000000000000000000..f47a64e58280b52a83c8e4c5e3471eb7bb32ff88 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-order-fixes.js @@ -0,0 +1,111 @@ +import { getNodeRange } from './get-node-range.js' +/** + * Generates fixes for reordering nodes to their sorted positions. + * + * Creates text replacement fixes that swap node positions to achieve the + * desired sort order. The function handles several important edge cases: + * + * - Preserves leading comments and documentation + * - Maintains file-level block comments for the first node + * - Adds safety semicolons when needed to prevent ASI issues + * - Respects partition boundaries defined by comments. + * + * The function iterates through each node position and replaces the original + * node text with the text from the node that should be in that position + * according to the sorted order. + * + * @example + * + * ```ts + * // Original order: + * const b = 2 + * const a = 1 + * + * // After applying order fixes: + * const a = 1 + * const b = 2 + * ``` + * + * @example + * + * ```ts + * // Safety semicolon example + * // Original: + * const b = 2 + * const a = 1 // 'a' will move to first position + * + * // After fix (semicolon added to prevent ASI issues): + * const a = 1 + * const b = 2 + * ``` + * + * @param params - Parameters for generating order fixes. + * @returns Array of ESLint fix operations to reorder nodes. + */ +function makeOrderFixes({ + ignoreFirstNodeHighestBlockComment, + sortedNodes, + sourceCode, + options, + fixer, + nodes, +}) { + let fixes = [] + for (let max = nodes.length, i = 0; i < max; i++) { + let sortingNode = nodes.at(i) + let sortedSortingNode = sortedNodes.at(i) + let { implicitDecorators, node } = sortingNode + let { addSafetySemicolonWhenInline, node: sortedNode } = sortedSortingNode + let isNodeFirstNode = node === nodes.at(0).node + let isSortedNodeFirstNode = sortedNode === nodes.at(0).node + if (node === sortedNode) { + continue + } + let sortedNodeCode = sourceCode.text.slice( + ...getNodeRange({ + ignoreHighestBlockComment: + ignoreFirstNodeHighestBlockComment && isSortedNodeFirstNode, + implicitDecorators: sortedSortingNode.implicitDecorators, + node: sortedNode, + sourceCode, + options, + }), + ) + let sortedNodeText = sourceCode.getText(sortedNode) + let nextToken = sourceCode + .getTokensAfter(node, { + includeComments: false, + count: 1, + }) + .at(0) + let sortedNextNodeEndsWithSafeCharacter = + sortedNodeText.endsWith(';') || sortedNodeText.endsWith(',') + let isNextTokenOnSameLineAsNode = + nextToken?.loc.start.line === node.loc.end.line + let isNextTokenSafeCharacter = + nextToken?.value === ';' || nextToken?.value === ',' + if ( + addSafetySemicolonWhenInline && + isNextTokenOnSameLineAsNode && + !sortedNextNodeEndsWithSafeCharacter && + !isNextTokenSafeCharacter + ) { + sortedNodeCode += ';' + } + fixes.push( + fixer.replaceTextRange( + getNodeRange({ + ignoreHighestBlockComment: + ignoreFirstNodeHighestBlockComment && isNodeFirstNode, + implicitDecorators, + sourceCode, + options, + node, + }), + sortedNodeCode, + ), + ) + } + return fixes +} +export { makeOrderFixes } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-single-node-comment-after-fixes.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-single-node-comment-after-fixes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3d84e044c2c579721cdc9446018db16af98aaf8e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-single-node-comment-after-fixes.d.ts @@ -0,0 +1,59 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { TSESTree } from '@typescript-eslint/types' +/** + * Parameters for generating comment-after fixes for a single node. + */ +interface MakeSingleNodeCommentAfterFixesParameters { + /** + * The node in its sorted position. + */ + sortedNode: TSESTree.Token | TSESTree.Node + /** + * The node in its original position. + */ + node: TSESTree.Token | TSESTree.Node + /** + * ESLint source code object for accessing comments and tokens. + */ + sourceCode: TSESLint.SourceCode + /** + * ESLint fixer object for creating fix operations. + */ + fixer: TSESLint.RuleFixer +} +/** + * Generates fixes to move inline trailing comments with their associated nodes. + * + * When a node is moved during sorting, this function ensures that any inline + * comment on the same line (trailing comment) is moved along with it. This + * preserves the relationship between code and its inline documentation. + * + * The function: + * + * - Detects inline comments after the sorted node + * - Skips processing if nodes would end up on the same line + * - Removes the comment from its original position + * - Inserts it after the node's new position. + * + * @example + * + * ```ts + * // Original: + * const b = 2 // second value + * const a = 1 // first value + * + * // After sorting (with comment fixes): + * const a = 1 // first value + * const b = 2 // second value + * ``` + * + * @param params - Parameters for generating comment fixes. + * @returns Array of ESLint fix operations, empty if no inline comment exists. + */ +export declare function makeSingleNodeCommentAfterFixes({ + sortedNode, + sourceCode, + fixer, + node, +}: MakeSingleNodeCommentAfterFixesParameters): TSESLint.RuleFix[] +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-single-node-comment-after-fixes.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-single-node-comment-after-fixes.js new file mode 100644 index 0000000000000000000000000000000000000000..31f48445b185d96e27f5adacd0d7b50e8f613f65 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/make-single-node-comment-after-fixes.js @@ -0,0 +1,131 @@ +/** + * Generates fixes to move inline trailing comments with their associated nodes. + * + * When a node is moved during sorting, this function ensures that any inline + * comment on the same line (trailing comment) is moved along with it. This + * preserves the relationship between code and its inline documentation. + * + * The function: + * + * - Detects inline comments after the sorted node + * - Skips processing if nodes would end up on the same line + * - Removes the comment from its original position + * - Inserts it after the node's new position. + * + * @example + * + * ```ts + * // Original: + * const b = 2 // second value + * const a = 1 // first value + * + * // After sorting (with comment fixes): + * const a = 1 // first value + * const b = 2 // second value + * ``` + * + * @param params - Parameters for generating comment fixes. + * @returns Array of ESLint fix operations, empty if no inline comment exists. + */ +function makeSingleNodeCommentAfterFixes({ + sortedNode, + sourceCode, + fixer, + node, +}) { + let commentAfter = getCommentAfter(sortedNode, sourceCode) + let areNodesOnSameLine = node.loc.start.line === sortedNode.loc.end.line + if (!commentAfter || areNodesOnSameLine) { + return [] + } + let fixes = [] + let range = [ + sourceCode.getTokenBefore(commentAfter).range.at(1), + commentAfter.range.at(1), + ] + fixes.push(fixer.replaceTextRange(range, '')) + let nodeToInsertAfter = computeNodeToInsertAfter({ + sourceCode, + node, + }) + let commentText = computeCommentTextToInsertAfter({ + nodeToInsertAfter, + commentAfter, + sourceCode, + range, + }) + fixes.push(fixer.insertTextAfter(nodeToInsertAfter, commentText)) + return fixes +} +function computeNodeToInsertAfter({ sourceCode, node }) { + let tokenAfterNode = sourceCode.getTokenAfter(node) + if (tokenAfterNode?.type !== 'Punctuator') { + return node + } + if (!isRelevantPunctuator(tokenAfterNode)) { + return node + } + if (tokenAfterNode.loc.end.line !== node.loc.end.line) { + return node + } + return tokenAfterNode + function isRelevantPunctuator(punctuatorToken) { + switch (punctuatorToken.value) { + case ',': + case ':': + return true + default: + return false + } + } +} +function computeCommentTextToInsertAfter({ + nodeToInsertAfter, + commentAfter, + sourceCode, + range, +}) { + let commentText = sourceCode.text.slice(...range) + if (commentAfter.type !== 'Line') { + return commentText + } + if ( + sourceCode.getTokenAfter(nodeToInsertAfter)?.loc.start.line !== + nodeToInsertAfter.loc.end.line + ) { + return commentText + } + commentText += '\n' + return commentText +} +/** + * Retrieves an inline comment that appears after a node on the same line. + * + * Searches for a comment token that: + * + * - Appears after the given node + * - Is on the same line as the node's end + * - Skips over punctuation like commas, semicolons, and colons. + * + * This helps identify inline trailing comments that should move with the node + * during sorting operations. + * + * @param node - The node to check for trailing comments. + * @param source - ESLint source code object. + * @returns The inline comment if found, null otherwise. + */ +function getCommentAfter(node, source) { + let token = source.getTokenAfter(node, { + filter: ({ value, type }) => + type !== 'Punctuator' || ![',', ';', ':'].includes(value), + includeComments: true, + }) + if ( + (token?.type === 'Block' || token?.type === 'Line') && + node.loc.end.line === token.loc.end.line + ) { + return token + } + return null +} +export { makeSingleNodeCommentAfterFixes } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/matches.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/matches.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e5b8221871b99350c0b745561487cd05158f259a --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/matches.d.ts @@ -0,0 +1,50 @@ +import { RegexOption } from '../types/common-options.js' +/** + * Tests if a string matches a regular expression pattern. + * + * Supports multiple formats for regex options: + * + * - String: Treated as a regex pattern (e.g., "^foo$") + * - Array: Matches if any pattern in the array matches (OR logic) + * - Object: Pattern with optional flags (e.g., { pattern: "^foo$", flags: "i" }). + * + * The function recursively processes arrays of patterns and includes error + * handling for invalid regex configurations (e.g., passing RegExp objects + * instead of strings). + * + * @example + * + * ```ts + * // String pattern + * matches('foo', '^foo$') // Returns: true + * matches('foobar', '^foo$') // Returns: false + * ``` + * + * @example + * + * ```ts + * // Array of patterns (OR logic) + * matches('foo', ['bar', '^foo$']) // Returns: true (matches second pattern) + * matches('baz', ['bar', '^foo$']) // Returns: false (matches neither) + * ``` + * + * @example + * + * ```ts + * // Pattern with flags + * matches('FOO', { + * pattern: '^foo$', + * flags: 'i', + * }) // Returns: true (case-insensitive) + * matches('FOO', '^foo$') // Returns: false (case-sensitive) + * ``` + * + * @param value - The string to test against the pattern(s). + * @param regexOption - The regex pattern(s) to match against. + * @returns True if the value matches the pattern(s), false otherwise. + * @throws {Error} If a RegExp object is passed instead of a string pattern. + */ +export declare function matches( + value: string, + regexOption: RegexOption, +): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/matches.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/matches.js new file mode 100644 index 0000000000000000000000000000000000000000..c04da9b8a6cd5a2bfc134f4d00778a875a8edb7d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/matches.js @@ -0,0 +1,60 @@ +/** + * Tests if a string matches a regular expression pattern. + * + * Supports multiple formats for regex options: + * + * - String: Treated as a regex pattern (e.g., "^foo$") + * - Array: Matches if any pattern in the array matches (OR logic) + * - Object: Pattern with optional flags (e.g., { pattern: "^foo$", flags: "i" }). + * + * The function recursively processes arrays of patterns and includes error + * handling for invalid regex configurations (e.g., passing RegExp objects + * instead of strings). + * + * @example + * + * ```ts + * // String pattern + * matches('foo', '^foo$') // Returns: true + * matches('foobar', '^foo$') // Returns: false + * ``` + * + * @example + * + * ```ts + * // Array of patterns (OR logic) + * matches('foo', ['bar', '^foo$']) // Returns: true (matches second pattern) + * matches('baz', ['bar', '^foo$']) // Returns: false (matches neither) + * ``` + * + * @example + * + * ```ts + * // Pattern with flags + * matches('FOO', { + * pattern: '^foo$', + * flags: 'i', + * }) // Returns: true (case-insensitive) + * matches('FOO', '^foo$') // Returns: false (case-sensitive) + * ``` + * + * @param value - The string to test against the pattern(s). + * @param regexOption - The regex pattern(s) to match against. + * @returns True if the value matches the pattern(s), false otherwise. + * @throws {Error} If a RegExp object is passed instead of a string pattern. + */ +function matches(value, regexOption) { + if (Array.isArray(regexOption)) { + return regexOption.some(opt => matches(value, opt)) + } + if (typeof regexOption === 'string') { + return new RegExp(regexOption).test(value) + } + if ('source' in regexOption) { + throw new Error( + 'Invalid configuration: please enter your RegExp expressions as strings.\nFor example, write ".*foo" instead of /.*foo/', + ) + } + return new RegExp(regexOption.pattern, regexOption.flags).test(value) +} +export { matches } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/overload-signature/build-overload-signature-newlines-between-value-getter.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/overload-signature/build-overload-signature-newlines-between-value-getter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..be21fe1ecc13673bcfca4311ddc2a3505af696a7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/overload-signature/build-overload-signature-newlines-between-value-getter.d.ts @@ -0,0 +1,16 @@ +import { TSESTree } from '@typescript-eslint/types' +import { SortingNodeWithOverloadSignatureImplementation } from './overload-signature-group.js' +import { NewlinesBetweenValueGetter } from '../get-newlines-between-errors.js' +import { NewlinesBetweenOption } from '../../types/common-groups-options.js' +/** + * Newlines between value getter for overload signatures. + * + * @param newlinesBetweenOverloadSignatures - Newlines between overload + * signatures option value. + * @returns NewlinesBetween option value. + */ +export declare function buildOverloadSignatureNewlinesBetweenValueGetter< + T extends TSESTree.Node, +>( + newlinesBetweenOverloadSignatures: NewlinesBetweenOption, +): NewlinesBetweenValueGetter> diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/overload-signature/build-overload-signature-newlines-between-value-getter.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/overload-signature/build-overload-signature-newlines-between-value-getter.js new file mode 100644 index 0000000000000000000000000000000000000000..d319fa1d3f1d77836e167c5c58ffb497c7b923e4 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/overload-signature/build-overload-signature-newlines-between-value-getter.js @@ -0,0 +1,22 @@ +/** + * Newlines between value getter for overload signatures. + * + * @param newlinesBetweenOverloadSignatures - Newlines between overload + * signatures option value. + * @returns NewlinesBetween option value. + */ +function buildOverloadSignatureNewlinesBetweenValueGetter( + newlinesBetweenOverloadSignatures, +) { + return ({ computedNewlinesBetween, right, left }) => { + if ( + left.overloadSignatureImplementation && + left.overloadSignatureImplementation === + right.overloadSignatureImplementation + ) { + return newlinesBetweenOverloadSignatures + } + return computedNewlinesBetween + } +} +export { buildOverloadSignatureNewlinesBetweenValueGetter } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/overload-signature/overload-signature-group.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/overload-signature/overload-signature-group.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ff7a749c4679a351165507fded7f11d3bf3e2c2a --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/overload-signature/overload-signature-group.d.ts @@ -0,0 +1,23 @@ +import { TSESTree } from '@typescript-eslint/utils' +import { SortingNode } from '../../types/sorting-node.js' +export type SortingNodeWithOverloadSignatureImplementation< + T extends TSESTree.Node, +> = OverloadSignatureImplementation & SortingNode +export interface OverloadSignatureImplementation { + overloadSignatureImplementation: null | T +} +/** + * Represents a group of overload signatures along with their implementation. + */ +export declare class OverloadSignatureGroup { + readonly implementation: T + private readonly _overloadSignatures + constructor({ + overloadSignatures, + implementation, + }: { + overloadSignatures: T[] + implementation: T + }) + doesNodeBelongToGroup(node: TSESTree.Node): boolean +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/overload-signature/overload-signature-group.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/overload-signature/overload-signature-group.js new file mode 100644 index 0000000000000000000000000000000000000000..35426fa2f7b24046e74bf9a94c812c14b089613f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/overload-signature/overload-signature-group.js @@ -0,0 +1,15 @@ +/** + * Represents a group of overload signatures along with their implementation. + */ +var OverloadSignatureGroup = class { + implementation + _overloadSignatures + constructor({ overloadSignatures, implementation }) { + this._overloadSignatures = new Set(overloadSignatures) + this.implementation = implementation + } + doesNodeBelongToGroup(node) { + return this._overloadSignatures.has(node) || this.implementation === node + } +} +export { OverloadSignatureGroup } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/overload-signature/populate-sorting-node-groups-with-overload-signature.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/overload-signature/populate-sorting-node-groups-with-overload-signature.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a36ea31fad72f2c2895d1f2fbd9169aedadfa344 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/overload-signature/populate-sorting-node-groups-with-overload-signature.d.ts @@ -0,0 +1,25 @@ +import { TSESTree } from '@typescript-eslint/types' +import { + OverloadSignatureImplementation, + OverloadSignatureGroup, +} from './overload-signature-group.js' +import { SortingNode } from '../../types/sorting-node.js' +/** + * Populate sorting node groups with their corresponding overload signature + * implementations fields if they exist. + * + * @param params - The parameters. + * @param params.overloadSignatureGroups - List of overload signature groups. + * @param params.sortingNodeGroups - List of sorting node groups. + * @returns The populated sorting node groups. + */ +export declare function populateSortingNodeGroupsWithOverloadSignature< + OverloadSignatureNode extends TSESTree.Node, + T extends SortingNode, +>({ + overloadSignatureGroups, + sortingNodeGroups, +}: { + overloadSignatureGroups: OverloadSignatureGroup[] + sortingNodeGroups: T[][] +}): (OverloadSignatureImplementation & T)[][] diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/overload-signature/populate-sorting-node-groups-with-overload-signature.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/overload-signature/populate-sorting-node-groups-with-overload-signature.js new file mode 100644 index 0000000000000000000000000000000000000000..366ac0677423b320283c28d9749df693c95a2e5b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/overload-signature/populate-sorting-node-groups-with-overload-signature.js @@ -0,0 +1,85 @@ +import { buildSortingNodeByNodeMap } from '../build-sorting-node-by-node-map.js' +/** + * Populate sorting node groups with their corresponding overload signature + * implementations fields if they exist. + * + * @param params - The parameters. + * @param params.overloadSignatureGroups - List of overload signature groups. + * @param params.sortingNodeGroups - List of sorting node groups. + * @returns The populated sorting node groups. + */ +function populateSortingNodeGroupsWithOverloadSignature({ + overloadSignatureGroups, + sortingNodeGroups, +}) { + return sortingNodeGroups.map(sortingNodes => + populateSortingNodeGroupWithOverloadSignature({ + overloadSignatureGroups, + sortingNodes, + }), + ) +} +function buildUpdatedSortingNode({ + overloadSignatureGroups, + sortingNodeByNode, + sortingNode, +}) { + let overloadSignatureImplementation = computeOverloadSignatureImplementation({ + overloadSignatureGroups, + node: sortingNode.node, + }) + if (!overloadSignatureImplementation) { + return { + ...sortingNode, + overloadSignatureImplementation: null, + } + } + let implementationSortingNode = sortingNodeByNode.get( + overloadSignatureImplementation, + ) + /* v8 ignore if -- @preserve Unsure how we can reach that case */ + if (!implementationSortingNode) { + return { + ...sortingNode, + overloadSignatureImplementation: null, + } + } + let { + addSafetySemicolonWhenInline, + isEslintDisabled, + node, + ...relevantImplementationSortingNodeFields + } = implementationSortingNode + return { + ...sortingNode, + ...relevantImplementationSortingNodeFields, + overloadSignatureImplementation, + } +} +function populateSortingNodeGroupWithOverloadSignature({ + overloadSignatureGroups, + sortingNodes, +}) { + let sortingNodeByNode = buildSortingNodeByNodeMap(sortingNodes) + return sortingNodes.map(sortingNode => + buildUpdatedSortingNode({ + overloadSignatureGroups, + sortingNodeByNode, + sortingNode, + }), + ) +} +function computeOverloadSignatureImplementation({ + overloadSignatureGroups, + node, +}) { + let matchingOverloadSignature = overloadSignatureGroups.find( + overloadSignatureGroup => + overloadSignatureGroup.doesNodeBelongToGroup(node), + ) + if (!matchingOverloadSignature) { + return null + } + return matchingOverloadSignature.implementation +} +export { populateSortingNodeGroupsWithOverloadSignature } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/pairwise.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/pairwise.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d07929ff234ec6fe0dc8ecd2d59d1ad6c3688d72 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/pairwise.d.ts @@ -0,0 +1,35 @@ +/** + * Iterates through an array calling a callback for each adjacent pair. + * + * Processes elements in pairs where: + * + * - First call: left is null, right is the first element + * - Subsequent calls: left and right are adjacent elements. + * + * This pattern is particularly useful for comparing adjacent elements in + * sorting validation, where each element needs to be compared with its + * predecessor to ensure correct ordering. + * + * @example + * + * ```ts + * // Common use case: checking sort order + * const numbers = [1, 3, 2, 4] + * const errors: string[] = [] + * + * pairwise(numbers, (left, right) => { + * if (left !== null && left > right) { + * errors.push(`${left} should come after ${right}`) + * } + * }) + * // errors = ['3 should come after 2'] + * ``` + * + * @template T - Type of array elements. + * @param nodes - Array to iterate through. + * @param callback - Function called for each pair (including null for first). + */ +export declare function pairwise( + nodes: T[], + callback: (left: null | T, right: T) => void, +): void diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/pairwise.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/pairwise.js new file mode 100644 index 0000000000000000000000000000000000000000..ad02b380d8a7725ef11ab64d84b4e7552cf32e0f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/pairwise.js @@ -0,0 +1,41 @@ +/** + * Iterates through an array calling a callback for each adjacent pair. + * + * Processes elements in pairs where: + * + * - First call: left is null, right is the first element + * - Subsequent calls: left and right are adjacent elements. + * + * This pattern is particularly useful for comparing adjacent elements in + * sorting validation, where each element needs to be compared with its + * predecessor to ensure correct ordering. + * + * @example + * + * ```ts + * // Common use case: checking sort order + * const numbers = [1, 3, 2, 4] + * const errors: string[] = [] + * + * pairwise(numbers, (left, right) => { + * if (left !== null && left > right) { + * errors.push(`${left} should come after ${right}`) + * } + * }) + * // errors = ['3 should come after 2'] + * ``` + * + * @template T - Type of array elements. + * @param nodes - Array to iterate through. + * @param callback - Function called for each pair (including null for first). + */ +function pairwise(nodes, callback) { + if (nodes.length === 0) { + return + } + callback(null, nodes.at(0)) + for (let i = 1; i < nodes.length; i++) { + callback(nodes.at(i - 1), nodes.at(i)) + } +} +export { pairwise } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/populate-sorting-node-groups-with-dependencies.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/populate-sorting-node-groups-with-dependencies.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d48f221dfd8c582d214a718f65634e4bde77dab0 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/populate-sorting-node-groups-with-dependencies.d.ts @@ -0,0 +1,25 @@ +import { TSESTree } from '@typescript-eslint/types' +import { SortingNodeWithDependencies } from './sort-nodes-by-dependencies.js' +type WithDependencies = { + dependencies: string[] +} & T +/** + * Populate sorting node groups based on the dependencies matrix. + * + * @param params - The parameters object. + * @param params.dependenciesBySortingNode - A map of sorting nodes to their + * dependencies. + * @param params.sortingNodeGroups - An array of sorting node groups. + * @returns An array of sorting node groups with their dependencies. + */ +export declare function populateSortingNodeGroupsWithDependencies< + Node extends TSESTree.Node, + T extends Pick, 'dependencyNames' | 'node'>, +>({ + dependenciesBySortingNode, + sortingNodeGroups, +}: { + dependenciesBySortingNode: Map + sortingNodeGroups: T[][] +}): WithDependencies[][] +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/populate-sorting-node-groups-with-dependencies.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/populate-sorting-node-groups-with-dependencies.js new file mode 100644 index 0000000000000000000000000000000000000000..7f703d5fdc9da3134334bee588900f71246e687d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/populate-sorting-node-groups-with-dependencies.js @@ -0,0 +1,46 @@ +/** + * Populate sorting node groups based on the dependencies matrix. + * + * @param params - The parameters object. + * @param params.dependenciesBySortingNode - A map of sorting nodes to their + * dependencies. + * @param params.sortingNodeGroups - An array of sorting node groups. + * @returns An array of sorting node groups with their dependencies. + */ +function populateSortingNodeGroupsWithDependencies({ + dependenciesBySortingNode, + sortingNodeGroups, +}) { + return sortingNodeGroups.map(sortingNodes => + computeSortingNodeGroupWithDependencies({ + dependenciesBySortingNode, + sortingNodes, + }), + ) +} +function computeSortingNodeGroupWithDependencies({ + dependenciesBySortingNode, + sortingNodes, +}) { + return sortingNodes.map(computeSortingNodeWithDependencies) + function computeSortingNodeWithDependencies(sortingNode) { + return { + ...sortingNode, + dependencies: computeSortingNodeDependencies({ + dependenciesBySortingNode, + sortingNode, + }), + } + } +} +function computeSortingNodeDependencies({ + dependenciesBySortingNode, + sortingNode, +}) { + let dependencies = dependenciesBySortingNode.get(sortingNode) + if (!dependencies) { + return [] + } + return dependencies.flatMap(({ dependencyNames }) => dependencyNames) +} +export { populateSortingNodeGroupsWithDependencies } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/range-contains-range.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/range-contains-range.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b63fd0a3b80ce4cf7a8a49db41e32db321ae724 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/range-contains-range.d.ts @@ -0,0 +1,12 @@ +import { TSESTree } from '@typescript-eslint/types' +/** + * Check if a range contains another range. + * + * @param includingRange - The range that may include the other range. + * @param subRange - The range to check if it is included. + * @returns True if the includingRange contains the subRange, false otherwise. + */ +export declare function rangeContainsRange( + includingRange: TSESTree.Range, + subRange: TSESTree.Range, +): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/range-contains-range.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/range-contains-range.js new file mode 100644 index 0000000000000000000000000000000000000000..11f7cdc0c7b9df5900a9b888c65be9827359c2f9 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/range-contains-range.js @@ -0,0 +1,11 @@ +/** + * Check if a range contains another range. + * + * @param includingRange - The range that may include the other range. + * @param subRange - The range to check if it is included. + * @returns True if the includingRange contains the subRange, false otherwise. + */ +function rangeContainsRange(includingRange, subRange) { + return includingRange[0] <= subRange[0] && includingRange[1] >= subRange[1] +} +export { rangeContainsRange } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/range-to-diff.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/range-to-diff.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dcbacef7b31e8a63c47e560040c53b6c7db347e0 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/range-to-diff.d.ts @@ -0,0 +1,43 @@ +import { TSESTree } from '@typescript-eslint/types' +import { TSESLint } from '@typescript-eslint/utils' +/** + * Calculates the size of a node excluding trailing punctuation. + * + * Computes the character length of a node's text representation, automatically + * subtracting trailing commas or semicolons from the size. This provides a more + * accurate measure of the actual content size, which is useful for sorting by + * line length. + * + * The function is widely used across all sorting rules when the sort type is + * set to 'line-length', ensuring consistent size calculation that ignores + * syntactic punctuation. + * + * @example + * + * ```ts + * // Node text: "const foo = 'bar';" + * rangeToDiff(node, sourceCode) // Returns: 17 (18 - 1 for semicolon) + * ``` + * + * @example + * + * ```ts + * // Node text: "{ name: 'John', age: 30 }," + * rangeToDiff(node, sourceCode) // Returns: 26 (27 - 1 for comma) + * ``` + * + * @example + * + * ```ts + * // Node text: "const value = 42" + * rangeToDiff(node, sourceCode) // Returns: 16 (no trailing punctuation) + * ``` + * + * @param node - AST node to measure. + * @param sourceCode - ESLint source code object for text extraction. + * @returns Character count of the node excluding trailing comma or semicolon. + */ +export declare function rangeToDiff( + node: TSESTree.Node, + sourceCode: TSESLint.SourceCode, +): number diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/range-to-diff.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/range-to-diff.js new file mode 100644 index 0000000000000000000000000000000000000000..af40d15e768a5b663fc3374ac0924b75ba8b9946 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/range-to-diff.js @@ -0,0 +1,45 @@ +/** + * Calculates the size of a node excluding trailing punctuation. + * + * Computes the character length of a node's text representation, automatically + * subtracting trailing commas or semicolons from the size. This provides a more + * accurate measure of the actual content size, which is useful for sorting by + * line length. + * + * The function is widely used across all sorting rules when the sort type is + * set to 'line-length', ensuring consistent size calculation that ignores + * syntactic punctuation. + * + * @example + * + * ```ts + * // Node text: "const foo = 'bar';" + * rangeToDiff(node, sourceCode) // Returns: 17 (18 - 1 for semicolon) + * ``` + * + * @example + * + * ```ts + * // Node text: "{ name: 'John', age: 30 }," + * rangeToDiff(node, sourceCode) // Returns: 26 (27 - 1 for comma) + * ``` + * + * @example + * + * ```ts + * // Node text: "const value = 42" + * rangeToDiff(node, sourceCode) // Returns: 16 (no trailing punctuation) + * ``` + * + * @param node - AST node to measure. + * @param sourceCode - ESLint source code object for text extraction. + * @returns Character count of the node excluding trailing comma or semicolon. + */ +function rangeToDiff(node, sourceCode) { + let nodeText = sourceCode.getText(node) + let endsWithCommaOrSemicolon = + nodeText.endsWith(';') || nodeText.endsWith(',') + let [from, to] = node.range + return to - from - (endsWithCommaOrSemicolon ? 1 : 0) +} +export { rangeToDiff } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/report-all-errors.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/report-all-errors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ec04bf589f448515ad9e99b0dc164e9af59ea62e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/report-all-errors.d.ts @@ -0,0 +1,205 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { NewlinesBetweenValueGetter } from './get-newlines-between-errors.js' +import { CommonPartitionOptions } from '../types/common-partition-options.js' +import { CommonGroupsOptions } from '../types/common-groups-options.js' +import { SortingNode } from '../types/sorting-node.js' +/** + * Parameters for comprehensive error reporting across all sorting rules. + * + * @template MessageIds - Union of available message IDs for the rule. + * @template T - Type of sorting node extending the base SortingNode. + */ +interface ReportAllErrorsParameters< + MessageIds extends string, + T extends SortingNode, +> { + /** + * Available message IDs for different types of violations. + * + * Each rule can customize these messages to provide context-specific error + * descriptions. Not all message types are required - only provide those + * relevant to the specific rule. + * + * @example + * + * ```ts + * // Class members rule with all message types + * availableMessageIds: { + * unexpectedOrder: 'unexpectedClassesOrder', + * unexpectedGroupOrder: 'unexpectedClassesGroupOrder', + * unexpectedDependencyOrder: 'unexpectedClassesDependencyOrder', + * missedSpacingBetweenMembers: 'missedSpacingBetweenClassMembers', + * extraSpacingBetweenMembers: 'extraSpacingBetweenClassMembers', + * missedCommentAbove: 'missedCommentAboveClassMember' + * } + * ``` + */ + availableMessageIds: { + /** + * Message when required spacing between members is missing. + */ + missedSpacingBetweenMembers?: MessageIds + /** + * Message when there's extra spacing where it shouldn't be. + */ + extraSpacingBetweenMembers?: MessageIds + /** + * Message when a dependency order is violated. + */ + unexpectedDependencyOrder?: MessageIds + /** + * Message when elements are in wrong groups. + */ + unexpectedGroupOrder: MessageIds + /** + * Message when a required comment above a group is missing. + */ + missedCommentAbove?: MessageIds + /** + * Message for general ordering violations within a group. + */ + unexpectedOrder: MessageIds + } + /** + * Configuration options for sorting and grouping. + * + * Extends MakeFixesParameters options with groups configuration. Includes + * all sorting preferences, partition settings, newlines configuration, and + * custom group definitions. + * + * @example + * + * ```ts + * options: { + * type: 'alphabetical', + * order: 'asc', + * groups: ['static-property', 'property', 'constructor', 'method'], + * newlinesBetween: 1, + * partitionByComment: true + * } + * ``` + */ + options: Pick & + CommonGroupsOptions + /** + * Function to get sorted nodes with or without ESLint-disabled nodes. + * + * This function is called twice by reportAllErrors: + * + * 1. With `false` to get all nodes for position mapping + * 2. With `true` to get nodes excluding disabled ones for error checking. + * + * This dual-call pattern ensures that ESLint-disabled nodes maintain their + * positions while not being considered for ordering violations. + * + * @param ignoreEslintDisabledNodes - Whether to exclude ESLint-disabled + * nodes. + * @returns Array of sorted nodes. + */ + sortNodesExcludingEslintDisabled(ignoreEslintDisabledNodes: boolean): T[] + /** + * Optional function to determine newlines between specific node pairs. + * + * Allows rules to customize spacing logic for special cases, such as + * overload signatures in TypeScript or getter/setter pairs. + * + * @example + * + * ```ts + * // Classes: Keep overload signatures together + * newlinesBetweenValueGetter: ({ + * left, + * right, + * computedNewlinesBetween, + * }) => { + * if ( + * left.overloadSignaturesGroupId === + * right.overloadSignaturesGroupId + * ) { + * return 0 // No newlines between overloads + * } + * return computedNewlinesBetween + * } + * ``` + */ + newlinesBetweenValueGetter?: NewlinesBetweenValueGetter + /** + * ESLint rule context for reporting errors. + * + * Used to access rule configuration, report violations, and provide fixes. + * The context includes the rule ID, options, settings, and methods for + * interacting with ESLint. + */ + context: TSESLint.RuleContext + /** + * Whether to ignore the highest block comment above the first node. + * + * When true, preserves file-level documentation comments at the top of + * sorted blocks. This is useful for maintaining copyright headers, file + * descriptions, or other important documentation. + */ + ignoreFirstNodeHighestBlockComment?: boolean + /** + * Array of all nodes to check for ordering violations. + * + * These are the nodes in their current order in the source code. The + * function will compare this order against the sorted order to identify and + * report all violations. + */ + nodes: T[] +} +/** + * Detects and reports all sorting violations in a comprehensive manner. + * + * Performs a complete analysis of sorting errors including: + * + * - Order violations (elements in wrong positions) + * - Group order violations (elements in wrong groups) + * - Dependency violations (dependent elements before their dependencies) + * - Spacing issues (missing or extra newlines between groups) + * - Missing comment separators above groups. + * + * The function uses pairwise comparison to check each adjacent pair of nodes + * and accumulates all applicable error messages for each violation. + * + * @example + * + * ```ts + * // Import statements with violations + * import { useState } from 'react' // Should be after React import + * import React from 'react' // Group order violation + * import type { User } from './types.js' // Missing newline between groups + * ``` + * + * @example + * + * ```ts + * // Object properties with dependency violation + * const config = { + * apiUrl: process.env.API_URL, + * baseUrl: this.apiUrl + '/v1', // Depends on apiUrl + * timeout: 5000, + * headers: { + * Authorization: this.token, // Should be after token definition + * }, + * token: getAuthToken(), + * } + * ``` + * + * @template MessageIds - Union of available message IDs. + * @template T - Type of sorting node. + * @param params - Parameters for error detection and reporting. + */ +export declare function reportAllErrors< + MessageIds extends string, + T extends SortingNode = SortingNode, +>({ + ignoreFirstNodeHighestBlockComment, + sortNodesExcludingEslintDisabled, + newlinesBetweenValueGetter, + availableMessageIds, + context, + options, + nodes, +}: ReportAllErrorsParameters): void +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/report-all-errors.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/report-all-errors.js new file mode 100644 index 0000000000000000000000000000000000000000..cce3409822431da3f941bf13f639d02ff80c8265 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/report-all-errors.js @@ -0,0 +1,212 @@ +import { getGroupIndex } from './get-group-index.js' +import { getCommentAboveThatShouldExist } from './get-comment-above-that-should-exist.js' +import { reportErrors } from './report-errors.js' +import { computeNodesInCircularDependencies } from './compute-nodes-in-circular-dependencies.js' +import { isNodeDependentOnOtherNode } from './is-node-dependent-on-other-node.js' +import { getNewlinesBetweenErrors } from './get-newlines-between-errors.js' +import { createNodeIndexMap } from './create-node-index-map.js' +import { pairwise } from './pairwise.js' +/** + * Detects and reports all sorting violations in a comprehensive manner. + * + * Performs a complete analysis of sorting errors including: + * + * - Order violations (elements in wrong positions) + * - Group order violations (elements in wrong groups) + * - Dependency violations (dependent elements before their dependencies) + * - Spacing issues (missing or extra newlines between groups) + * - Missing comment separators above groups. + * + * The function uses pairwise comparison to check each adjacent pair of nodes + * and accumulates all applicable error messages for each violation. + * + * @example + * + * ```ts + * // Import statements with violations + * import { useState } from 'react' // Should be after React import + * import React from 'react' // Group order violation + * import type { User } from './types' // Missing newline between groups + * ``` + * + * @example + * + * ```ts + * // Object properties with dependency violation + * const config = { + * apiUrl: process.env.API_URL, + * baseUrl: this.apiUrl + '/v1', // Depends on apiUrl + * timeout: 5000, + * headers: { + * Authorization: this.token, // Should be after token definition + * }, + * token: getAuthToken(), + * } + * ``` + * + * @template MessageIds - Union of available message IDs. + * @template T - Type of sorting node. + * @param params - Parameters for error detection and reporting. + */ +function reportAllErrors({ + ignoreFirstNodeHighestBlockComment, + sortNodesExcludingEslintDisabled, + newlinesBetweenValueGetter, + availableMessageIds, + context, + options, + nodes, +}) { + let { sourceCode } = context + let sortedNodes = sortNodesExcludingEslintDisabled(false) + let sortedNodesExcludingEslintDisabled = + sortNodesExcludingEslintDisabled(true) + let nodeIndexMap = createNodeIndexMap(sortedNodes) + let nodesInCircularDependencies = + availableMessageIds.unexpectedDependencyOrder ? + computeNodesInCircularDependencies(nodes) + : /* @__PURE__ */ new Set() + pairwise(nodes, (left, right) => { + let leftInfo = + left ? + { + groupIndex: getGroupIndex(options.groups, left), + index: nodeIndexMap.get(left), + } + : null + let rightGroupIndex = getGroupIndex(options.groups, right) + let rightIndex = nodeIndexMap.get(right) + let indexOfRightExcludingEslintDisabled = + sortedNodesExcludingEslintDisabled.indexOf(right) + let messageIds = [] + let firstUnorderedNodeDependentOnRight + if (availableMessageIds.unexpectedDependencyOrder) { + firstUnorderedNodeDependentOnRight = getFirstUnorderedNodeDependentOn({ + nodes, + node: right, + nodesInCircularDependencies, + }) + } + if ( + leftInfo && + (firstUnorderedNodeDependentOnRight || + leftInfo.index > rightIndex || + (left?.isEslintDisabled && + leftInfo.index >= indexOfRightExcludingEslintDisabled)) + ) { + if (firstUnorderedNodeDependentOnRight) { + messageIds.push(availableMessageIds.unexpectedDependencyOrder) + } else { + messageIds.push( + ( + leftInfo.groupIndex === rightGroupIndex || + !availableMessageIds.unexpectedGroupOrder + ) ? + availableMessageIds.unexpectedOrder + : availableMessageIds.unexpectedGroupOrder, + ) + } + } + if ( + left && + availableMessageIds.missedSpacingBetweenMembers && + availableMessageIds.extraSpacingBetweenMembers + ) { + messageIds.push( + ...getNewlinesBetweenErrors({ + options: { + ...options, + newlinesBetween: options.newlinesBetween, + }, + missedSpacingError: availableMessageIds.missedSpacingBetweenMembers, + extraSpacingError: availableMessageIds.extraSpacingBetweenMembers, + leftGroupIndex: leftInfo.groupIndex, + newlinesBetweenValueGetter, + rightGroupIndex, + sourceCode, + right, + left, + }), + ) + } + let commentAboveMissing + if (availableMessageIds.missedCommentAbove) { + let commentAboveThatShouldExist = getCommentAboveThatShouldExist({ + leftGroupIndex: leftInfo?.groupIndex ?? null, + sortingNode: right, + rightGroupIndex, + sourceCode, + options, + }) + if (commentAboveThatShouldExist && !commentAboveThatShouldExist.exists) { + commentAboveMissing = commentAboveThatShouldExist.comment + messageIds.push(availableMessageIds.missedCommentAbove) + } + } + reportErrors({ + sortedNodes: sortedNodesExcludingEslintDisabled, + ignoreFirstNodeHighestBlockComment, + firstUnorderedNodeDependentOnRight, + newlinesBetweenValueGetter, + commentAboveMissing, + messageIds, + sourceCode, + options, + context, + nodes, + right, + left, + }) + }) +} +/** + * Finds the first node that depends on the given node but appears before it. + * + * Detects dependency violations where a dependent element appears before its + * dependency in the current order. This is crucial for maintaining logical + * ordering in code where some elements reference others. + * + * Nodes in circular dependencies are excluded from this check as they cannot be + * properly ordered. + * + * @example + * + * ```ts + * // TypeScript interface extending another + * interface AdminUser extends User { + * // This depends on User + * permissions: string[] + * } + * interface User { + * // But User appears after AdminUser + * id: string + * name: string + * } + * // Returns: AdminUser node (appears before its dependency). + * ``` + * + * @template T - Type of sorting node with dependencies. + * @param params - Parameters for finding dependent nodes. + * @param params.nodesInCircularDependencies - Set of nodes in circular + * dependencies. + * @param params.nodes - All nodes in current order. + * @param params.node - The node to check for dependents. + * @returns First dependent node appearing before its dependency, or undefined. + */ +function getFirstUnorderedNodeDependentOn({ + nodesInCircularDependencies, + nodes, + node, +}) { + return nodes + .filter( + currentlyOrderedNode => + !nodesInCircularDependencies.has(currentlyOrderedNode) && + isNodeDependentOnOtherNode(node, currentlyOrderedNode), + ) + .find(firstNodeDependentOnNode => { + let currentIndexOfNode = nodes.indexOf(node) + return nodes.indexOf(firstNodeDependentOnNode) < currentIndexOfNode + }) +} +export { reportAllErrors } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/report-errors.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/report-errors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f51af00b81703910bba9700df95e67b77029e2e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/report-errors.d.ts @@ -0,0 +1,112 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { NewlinesBetweenValueGetter } from './get-newlines-between-errors.js' +import { CommonPartitionOptions } from '../types/common-partition-options.js' +import { CommonGroupsOptions } from '../types/common-groups-options.js' +import { SortingNode } from '../types/sorting-node.js' +export declare const RIGHT = 'right' +export declare const LEFT = 'left' +export declare const ORDER_ERROR: 'Expected "{{right}}" to come before "{{left}}".' +export declare const DEPENDENCY_ORDER_ERROR: 'Expected dependency "{{right}}" to come before "{{nodeDependentOnRight}}".' +export declare const GROUP_ORDER_ERROR: 'Expected "{{right}}" ({{rightGroup}}) to come before "{{left}}" ({{leftGroup}}).' +export declare const EXTRA_SPACING_ERROR: 'Extra spacing between "{{left}}" and "{{right}}".' +export declare const MISSED_SPACING_ERROR: 'Missed spacing between "{{left}}" and "{{right}}".' +export declare const MISSED_COMMENT_ABOVE_ERROR: 'Missed comment "{{missedCommentAbove}}" above "{{right}}".' +/** + * Parameters for reporting ESLint errors with auto-fix support. + * + * @template MessageIds - Union of available message IDs for the rule. + * @template T - Type of sorting node extending the base SortingNode. + */ +interface ReportErrorsParameters< + MessageIds extends string, + T extends SortingNode, +> { + options?: Pick & + CommonGroupsOptions + newlinesBetweenValueGetter?: NewlinesBetweenValueGetter + context: TSESLint.RuleContext + ignoreFirstNodeHighestBlockComment?: boolean + firstUnorderedNodeDependentOnRight?: T + sourceCode: TSESLint.SourceCode + commentAboveMissing?: string + messageIds: MessageIds[] + sortedNodes: T[] + left: null | T + nodes: T[] + right: T +} +/** + * Reports ESLint errors with contextual data and auto-fix support. + * + * Generates ESLint error reports for each provided message ID, including: + * + * - Contextual data for error messages (element names, groups, dependencies) + * - Auto-fix function that applies all necessary corrections + * - Node location for error highlighting. + * + * The function supports dynamic message templates with placeholders that are + * replaced with actual values: + * + * - {{left}} / {{right}} - Element names in the comparison + * - {{leftGroup}} / {{rightGroup}} - Group names + * - {{nodeDependentOnRight}} - Name of dependent element + * - {{missedCommentAbove}} - Missing comment text. + * + * @example + * + * ```ts + * // Reporting import order violation + * reportErrors({ + * messageIds: ['unexpectedOrder'], + * left: { name: 'useState', group: 'react' }, + * right: { name: 'React', group: 'react' }, + * // Error: "Expected 'React' to come before 'useState'" + * }) + * ``` + * + * @example + * + * ```ts + * // Reporting dependency violation in TypeScript interfaces + * reportErrors({ + * messageIds: ['unexpectedDependencyOrder'], + * right: { name: 'User', ... }, + * firstUnorderedNodeDependentOnRight: { name: 'AdminUser extends User', ... }, + * // Error: "Expected 'User' to come before 'AdminUser extends User' due to dependency" + * }); + * ``` + * + * @example + * + * ```ts + * // Reporting missing newlines between import groups + * reportErrors({ + * messageIds: ['missedSpacingBetweenMembers'], + * left: { name: 'React', group: 'external' }, + * right: { name: './utils', group: 'internal' }, + * // Error: "Expected newline between external and internal imports" + * }) + * ``` + * + * @template MessageIds - Union of message IDs. + * @template T - Type of sorting node. + * @param params - Parameters for error reporting. + */ +export declare function reportErrors< + MessageIds extends string, + T extends SortingNode, +>({ + firstUnorderedNodeDependentOnRight, + ignoreFirstNodeHighestBlockComment, + newlinesBetweenValueGetter, + commentAboveMissing, + sortedNodes, + messageIds, + sourceCode, + context, + options, + nodes, + right, + left, +}: ReportErrorsParameters): void +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/report-errors.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/report-errors.js new file mode 100644 index 0000000000000000000000000000000000000000..d5046aa7866197ca8ce6d1f6d7188582c4ffa4cf --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/report-errors.js @@ -0,0 +1,145 @@ +import { makeFixes } from './make-fixes.js' +var NODE_DEPENDENT_ON_RIGHT = 'nodeDependentOnRight' +var RIGHT = 'right' +var RIGHT_GROUP = 'rightGroup' +var LEFT = 'left' +var LEFT_GROUP = 'leftGroup' +var MISSED_COMMENT_ABOVE = 'missedCommentAbove' +var ORDER_ERROR = `Expected "{{${RIGHT}}}" to come before "{{${LEFT}}}".` +var DEPENDENCY_ORDER_ERROR = `Expected dependency "{{${RIGHT}}}" to come before "{{${NODE_DEPENDENT_ON_RIGHT}}}".` +var GROUP_ORDER_ERROR = `Expected "{{${RIGHT}}}" ({{${RIGHT_GROUP}}}) to come before "{{${LEFT}}}" ({{${LEFT_GROUP}}}).` +var EXTRA_SPACING_ERROR = `Extra spacing between "{{${LEFT}}}" and "{{${RIGHT}}}".` +var MISSED_SPACING_ERROR = `Missed spacing between "{{${LEFT}}}" and "{{${RIGHT}}}".` +var MISSED_COMMENT_ABOVE_ERROR = `Missed comment "{{${MISSED_COMMENT_ABOVE}}}" above "{{${RIGHT}}}".` +/** + * Reports ESLint errors with contextual data and auto-fix support. + * + * Generates ESLint error reports for each provided message ID, including: + * + * - Contextual data for error messages (element names, groups, dependencies) + * - Auto-fix function that applies all necessary corrections + * - Node location for error highlighting. + * + * The function supports dynamic message templates with placeholders that are + * replaced with actual values: + * + * - {{left}} / {{right}} - Element names in the comparison + * - {{leftGroup}} / {{rightGroup}} - Group names + * - {{nodeDependentOnRight}} - Name of dependent element + * - {{missedCommentAbove}} - Missing comment text. + * + * @example + * + * ```ts + * // Reporting import order violation + * reportErrors({ + * messageIds: ['unexpectedOrder'], + * left: { name: 'useState', group: 'react' }, + * right: { name: 'React', group: 'react' }, + * // Error: "Expected 'React' to come before 'useState'" + * }) + * ``` + * + * @example + * + * ```ts + * // Reporting dependency violation in TypeScript interfaces + * reportErrors({ + * messageIds: ['unexpectedDependencyOrder'], + * right: { name: 'User', ... }, + * firstUnorderedNodeDependentOnRight: { name: 'AdminUser extends User', ... }, + * // Error: "Expected 'User' to come before 'AdminUser extends User' due to dependency" + * }); + * ``` + * + * @example + * + * ```ts + * // Reporting missing newlines between import groups + * reportErrors({ + * messageIds: ['missedSpacingBetweenMembers'], + * left: { name: 'React', group: 'external' }, + * right: { name: './utils', group: 'internal' }, + * // Error: "Expected newline between external and internal imports" + * }) + * ``` + * + * @template MessageIds - Union of message IDs. + * @template T - Type of sorting node. + * @param params - Parameters for error reporting. + */ +function reportErrors({ + firstUnorderedNodeDependentOnRight, + ignoreFirstNodeHighestBlockComment, + newlinesBetweenValueGetter, + commentAboveMissing, + sortedNodes, + messageIds, + sourceCode, + context, + options, + nodes, + right, + left, +}) { + for (let messageId of messageIds) { + context.report({ + data: { + [NODE_DEPENDENT_ON_RIGHT]: firstUnorderedNodeDependentOnRight?.name, + [MISSED_COMMENT_ABOVE]: commentAboveMissing, + [LEFT]: toSingleLine(left?.name ?? ''), + [RIGHT]: toSingleLine(right.name), + [RIGHT_GROUP]: right.group, + [LEFT_GROUP]: left?.group, + }, + fix: fixer => + makeFixes({ + hasCommentAboveMissing: !!commentAboveMissing, + ignoreFirstNodeHighestBlockComment, + newlinesBetweenValueGetter, + sortedNodes, + sourceCode, + options, + fixer, + nodes, + }), + node: right.node, + messageId, + }) + } +} +/** + * Converts multi-line strings to single-line for error messages. + * + * Normalizes element names that may span multiple lines (like template + * literals, multi-line imports, or complex expressions) into a single line + * format suitable for error messages. + * + * @example + * + * ```ts + * toSingleLine(` + * import { + * Component + * } from 'react' + * `) + * // Returns: "import { Component } from 'react'" + * ``` + * + * @param string - Multi-line string to normalize. + * @returns Single-line string with normalized whitespace. + */ +function toSingleLine(string) { + return string.replaceAll(/\s{2,}/gu, ' ').trim() +} +export { + DEPENDENCY_ORDER_ERROR, + EXTRA_SPACING_ERROR, + GROUP_ORDER_ERROR, + LEFT, + MISSED_COMMENT_ABOVE_ERROR, + MISSED_SPACING_ERROR, + ORDER_ERROR, + RIGHT, + reportErrors, +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/scoped-regex/matches-scoped-expressions.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/scoped-regex/matches-scoped-expressions.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..82be99924a04c437b53e6ed453b4d8a2c4a2960c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/scoped-regex/matches-scoped-expressions.d.ts @@ -0,0 +1,30 @@ +import { AST_NODE_TYPES } from '@typescript-eslint/utils' +import { TSESTree } from '@typescript-eslint/types' +import { ScopedRegexOption } from '../../types/scoped-regex-option.js' +import { NodeOfType } from '../../types/node-of-type.js' +export type NodeValuesComputer = ( + node: NodeOfType, +) => string[] +/** + * Checks whether any of the parent nodes match the scoped regex patterns. + * + * @param params - The parameters object. + * @param params.nodeValuesComputer - Function to compute the string values of a + * node to match against. + * @param params.scopedRegexOption - The scoped regex option to match against. + * @param params.allowedNodeTypes - The set of allowed node types to consider. + * @param params.parentNodes - The parent nodes to check. + * @returns True if any parent node matches the scoped regex patterns, false + * otherwise. + */ +export declare function matchesScopedExpressions({ + nodeValuesComputer, + scopedRegexOption, + allowedNodeTypes, + parentNodes, +}: { + scopedRegexOption: ScopedRegexOption | undefined + nodeValuesComputer: NodeValuesComputer + parentNodes: TSESTree.Node[] + allowedNodeTypes: Set +}): boolean diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/scoped-regex/matches-scoped-expressions.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/scoped-regex/matches-scoped-expressions.js new file mode 100644 index 0000000000000000000000000000000000000000..7c362c7a981bea7eab64c51f13fccebeca62e6ff --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/scoped-regex/matches-scoped-expressions.js @@ -0,0 +1,87 @@ +import { matches } from '../matches.js' +import { partitionPatternsByScope } from './partition-patterns-by-scope.js' +/** + * Checks whether any of the parent nodes match the scoped regex patterns. + * + * @param params - The parameters object. + * @param params.nodeValuesComputer - Function to compute the string values of a + * node to match against. + * @param params.scopedRegexOption - The scoped regex option to match against. + * @param params.allowedNodeTypes - The set of allowed node types to consider. + * @param params.parentNodes - The parent nodes to check. + * @returns True if any parent node matches the scoped regex patterns, false + * otherwise. + */ +function matchesScopedExpressions({ + nodeValuesComputer, + scopedRegexOption, + allowedNodeTypes, + parentNodes, +}) { + if (!scopedRegexOption) { + return true + } + let { shallowScopePatterns, deepScopePatterns } = + partitionPatternsByScope(scopedRegexOption) + return ( + matchesShallowScopedExpressions({ + patterns: shallowScopePatterns, + nodeValuesComputer, + allowedNodeTypes, + parentNodes, + }) || + matchesDeepScopedExpressions({ + patterns: deepScopePatterns, + nodeValuesComputer, + allowedNodeTypes, + parentNodes, + }) + ) +} +function matchesShallowScopedExpressions({ + nodeValuesComputer, + allowedNodeTypes, + parentNodes, + patterns, +}) { + let [firstParent] = parentNodes + // v8 ignore if -- @preserve Unsure how we can reach that case + if (!firstParent) { + return false + } + if (!isNodeTypeAmong(firstParent, allowedNodeTypes)) { + return false + } + return matchesParentExpression({ + parentNode: firstParent, + nodeValuesComputer, + patterns, + }) +} +function matchesDeepScopedExpressions({ + nodeValuesComputer, + allowedNodeTypes, + parentNodes, + patterns, +}) { + return parentNodes + .filter(parent => isNodeTypeAmong(parent, allowedNodeTypes)) + .some(parentNode => + matchesParentExpression({ + nodeValuesComputer, + parentNode, + patterns, + }), + ) +} +function matchesParentExpression({ nodeValuesComputer, parentNode, patterns }) { + let nodeValues = nodeValuesComputer(parentNode) + return patterns.some(nodeValueMatchesPattern) + function nodeValueMatchesPattern(pattern) { + return nodeValues.some(nodeValue => matches(nodeValue, pattern)) + } +} +function isNodeTypeAmong(node, types) { + return types.has(node.type) +} +export { matchesScopedExpressions } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/scoped-regex/partition-patterns-by-scope.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/scoped-regex/partition-patterns-by-scope.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..43dcb25ae6566e8e1f32414790936d2766f5b8a9 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/scoped-regex/partition-patterns-by-scope.d.ts @@ -0,0 +1,20 @@ +import { ScopedRegexOption, Scope } from '../../types/scoped-regex-option.js' +export type SingleRegexOption = + | { + pattern: string + flags?: string + scope?: Scope + } + | string +/** + * Partitions patterns by their scope (shallow or deep). + * + * @param patternOrPatterns - A single pattern or an array of patterns. + * @returns An object containing arrays of shallow and deep scope patterns. + */ +export declare function partitionPatternsByScope( + patternOrPatterns: ScopedRegexOption, +): { + shallowScopePatterns: SingleRegexOption[] + deepScopePatterns: SingleRegexOption[] +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/scoped-regex/partition-patterns-by-scope.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/scoped-regex/partition-patterns-by-scope.js new file mode 100644 index 0000000000000000000000000000000000000000..18baf97f570015384ffcb12b58fadab3fce6f3a1 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/scoped-regex/partition-patterns-by-scope.js @@ -0,0 +1,38 @@ +/** + * Partitions patterns by their scope (shallow or deep). + * + * @param patternOrPatterns - A single pattern or an array of patterns. + * @returns An object containing arrays of shallow and deep scope patterns. + */ +function partitionPatternsByScope(patternOrPatterns) { + if (!Array.isArray(patternOrPatterns)) { + let isDeepScopePattern = isDeepScopedPattern(patternOrPatterns) + return { + shallowScopePatterns: isDeepScopePattern ? [] : [patternOrPatterns], + deepScopePatterns: isDeepScopePattern ? [patternOrPatterns] : [], + } + } + let deepScopedPatterns = [] + let shallowScopedPatterns = [] + for (let pattern of patternOrPatterns) { + if (isDeepScopedPattern(pattern)) { + deepScopedPatterns.push(pattern) + } else { + shallowScopedPatterns.push(pattern) + } + } + return { + shallowScopePatterns: shallowScopedPatterns, + deepScopePatterns: deepScopedPatterns, + } +} +function isDeepScopedPattern(pattern) { + if (typeof pattern !== 'object') { + return false + } + if (!('scope' in pattern)) { + return false + } + return pattern.scope === 'deep' +} +export { partitionPatternsByScope } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/should-partition.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/should-partition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..261bdda852db9b73555aee51d6a0f84150db2cc0 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/should-partition.d.ts @@ -0,0 +1,76 @@ +import { TSESLint } from '@typescript-eslint/utils' +import { CommonPartitionOptions } from '../types/common-partition-options.js' +import { SortingNode } from '../types/sorting-node.js' +/** + * Parameters for determining if a new partition should start. + */ +interface ShouldPartitionParameters { + lastSortingNode: Pick | undefined + sortingNode: Pick + tokenValueToIgnoreBefore?: string + options: CommonPartitionOptions + sourceCode: TSESLint.SourceCode +} +/** + * Determines if a new partition (independent sorting section) should start. + * + * Partitions divide code into independent sections that are sorted separately, + * preventing elements from being moved across partition boundaries. This is + * critical for preserving logical groupings in code. + * + * A new partition is created when: + * + * - A partition comment is found before the current node + * - An empty line exists between nodes (when partitionByNewLine is enabled). + * + * @example + * + * ```ts + * // React component with partition comments + * import React from 'react' + * import { useState, useEffect } from 'react' + * // --- Utils --- <- This comment creates a partition + * import { formatDate } from './utils/date.js' + * import { apiClient } from './utils/api.js' + * ``` + * + * @example + * + * ```ts + * // Object with newline partitions + * const config = { + * // API settings + * apiUrl: 'https://api.example.com', + * timeout: 5000, + * // <- Empty line creates partition + * // UI settings + * theme: 'dark', + * language: 'en', + * } + * ``` + * + * @example + * + * ```ts + * // Class members with sections + * class UserService { + * private cache: Map; + * private logger: Logger; + * + * // Public methods section + * async getUser(id: string) { ... } + * async updateUser(id: string, data: Partial) { ... } + * } + * ``` + * + * @param params - Parameters for partition detection. + * @returns True if a new partition should start at the current node. + */ +export declare function shouldPartition({ + tokenValueToIgnoreBefore, + lastSortingNode, + sortingNode, + sourceCode, + options, +}: ShouldPartitionParameters): boolean +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/should-partition.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/should-partition.js new file mode 100644 index 0000000000000000000000000000000000000000..75be6dc9812f6793d1e023921e2203e08dbe0b66 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/should-partition.js @@ -0,0 +1,118 @@ +import { getLinesBetween } from './get-lines-between.js' +import { isPartitionComment } from './is-partition-comment.js' +import { getCommentsBefore } from './get-comments-before.js' +/** + * Determines if a new partition (independent sorting section) should start. + * + * Partitions divide code into independent sections that are sorted separately, + * preventing elements from being moved across partition boundaries. This is + * critical for preserving logical groupings in code. + * + * A new partition is created when: + * + * - A partition comment is found before the current node + * - An empty line exists between nodes (when partitionByNewLine is enabled). + * + * @example + * + * ```ts + * // React component with partition comments + * import React from 'react' + * import { useState, useEffect } from 'react' + * // --- Utils --- <- This comment creates a partition + * import { formatDate } from './utils/date' + * import { apiClient } from './utils/api' + * ``` + * + * @example + * + * ```ts + * // Object with newline partitions + * const config = { + * // API settings + * apiUrl: 'https://api.example.com', + * timeout: 5000, + * // <- Empty line creates partition + * // UI settings + * theme: 'dark', + * language: 'en', + * } + * ``` + * + * @example + * + * ```ts + * // Class members with sections + * class UserService { + * private cache: Map; + * private logger: Logger; + * + * // Public methods section + * async getUser(id: string) { ... } + * async updateUser(id: string, data: Partial) { ... } + * } + * ``` + * + * @param params - Parameters for partition detection. + * @returns True if a new partition should start at the current node. + */ +function shouldPartition({ + tokenValueToIgnoreBefore, + lastSortingNode, + sortingNode, + sourceCode, + options, +}) { + if ( + options.partitionByComment && + hasPartitionComment({ + comments: getCommentsBefore({ + tokenValueToIgnoreBefore, + node: sortingNode.node, + sourceCode, + }), + partitionByComment: options.partitionByComment, + }) + ) { + return true + } + return !!( + lastSortingNode && + options.partitionByNewLine && + getLinesBetween(sourceCode, lastSortingNode, sortingNode) + ) +} +/** + * Checks if any of the provided comments is a partition comment. + * + * Helper function that iterates through comments to find if any matches the + * partition comment criteria defined in options. + * + * @example + * + * ```ts + * // Comments that create partitions + * const comments = [ + * { value: ' --- Components --- ', type: 'Line' }, + * { value: ' Section: Utils ', type: 'Line' }, + * ] + * hasPartitionComment({ + * partitionByComment: '---', + * comments, + * }) // Returns: true + * ``` + * + * @param params - Parameters for checking partition comments. + * @param params.partitionByComment - Configuration for partition comments. + * @param params.comments - Array of comments to check. + * @returns True if at least one partition comment is found. + */ +function hasPartitionComment({ partitionByComment, comments }) { + return comments.some(comment => + isPartitionComment({ + partitionByComment, + comment, + }), + ) +} +export { shouldPartition } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/sort-nodes-by-dependencies.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/sort-nodes-by-dependencies.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f22fe494e4c3d6476abe07c3bfb4af120914ca7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/sort-nodes-by-dependencies.d.ts @@ -0,0 +1,115 @@ +import { TSESTree } from '@typescript-eslint/types' +import { SortingNode } from '../types/sorting-node.js' +/** + * Sorting node enhanced with dependency information. + * + * Extends the base SortingNode with arrays tracking what this node depends on + * and what it represents as a dependency. + * + * @template Node - Type of the AST node. + */ +export interface SortingNodeWithDependencies< + Node extends TSESTree.Node = TSESTree.Node, +> extends SortingNode { + dependencyNames: string[] + dependencies: string[] +} +/** + * Additional options for dependency-based sorting. + */ +interface ExtraOptions { + /** + * Whether to exclude ESLint-disabled nodes from dependency resolution. + */ + ignoreEslintDisabledNodes: boolean +} +/** + * Returns nodes topologically sorted by their dependencies. + * + * @param nodes - The nodes to sort. + * @param [extraOptions] - Additional sorting options. + * @returns The nodes sorted in topological order. + */ +/** + * Sorts nodes using topological sorting based on their dependencies. + * + * Implements a depth-first search algorithm to ensure that dependencies appear + * before the nodes that depend on them. This is crucial for maintaining logical + * order in code where some elements reference others. + * + * Nodes involved in circular dependencies are excluded from dependency-based + * ordering and retain their original relative positions. + * + * @example + * + * ```ts + * // TypeScript interfaces with inheritance + * const nodes = [ + * { + * name: 'AdminUser', + * dependencies: ['AdminUser'], + * dependencyNames: ['User'], + * }, + * { name: 'User', dependencies: ['User'], dependencyNames: [] }, + * { + * name: 'GuestUser', + * dependencies: ['GuestUser'], + * dependencyNames: ['User'], + * }, + * ] + * sortNodesByDependencies(nodes) + * // Returns: [User, AdminUser, GuestUser] + * // User must come first as others depend on it + * ``` + * + * @example + * + * ```ts + * // React components with hook dependencies + * const nodes = [ + * { + * name: 'MyComponent', + * dependencies: ['MyComponent'], + * dependencyNames: ['useAuth', 'useData'], + * }, + * { + * name: 'useData', + * dependencies: ['useData'], + * dependencyNames: ['useApi'], + * }, + * { name: 'useApi', dependencies: ['useApi'], dependencyNames: [] }, + * { name: 'useAuth', dependencies: ['useAuth'], dependencyNames: [] }, + * ] + * sortNodesByDependencies(nodes) + * // Returns: [useApi, useData, useAuth, MyComponent] + * // Hooks are ordered by their dependency chain + * ``` + * + * @example + * + * ```ts + * // Object properties with computed values + * const config = { + * baseUrl: 'https://api.example.com', + * apiUrl: `${this.baseUrl}/v1`, // Depends on baseUrl + * authUrl: `${this.apiUrl}/auth`, // Depends on apiUrl + * headers: { + * 'API-Key': this.apiKey, // Depends on apiKey + * }, + * apiKey: process.env.API_KEY, + * } + * // After sorting: baseUrl, apiKey, apiUrl, authUrl, headers + * ``` + * + * @template T - Type of sorting node with dependencies. + * @param nodes - Array of nodes to sort by dependencies. + * @param extraOptions - Additional sorting options. + * @returns Topologically sorted array of nodes. + */ +export declare function sortNodesByDependencies< + T extends Pick< + SortingNodeWithDependencies, + 'isEslintDisabled' | 'dependencyNames' | 'dependencies' + >, +>(nodes: T[], extraOptions: ExtraOptions): T[] +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/sort-nodes-by-dependencies.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/sort-nodes-by-dependencies.js new file mode 100644 index 0000000000000000000000000000000000000000..a05f37d6c2c74ab1d04564242a758b4d9c7055f7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/sort-nodes-by-dependencies.js @@ -0,0 +1,121 @@ +import { computeNodesInCircularDependencies } from './compute-nodes-in-circular-dependencies.js' +import { isNodeDependentOnOtherNode } from './is-node-dependent-on-other-node.js' +/** + * Returns nodes topologically sorted by their dependencies. + * + * @param nodes - The nodes to sort. + * @param [extraOptions] - Additional sorting options. + * @returns The nodes sorted in topological order. + */ +/** + * Sorts nodes using topological sorting based on their dependencies. + * + * Implements a depth-first search algorithm to ensure that dependencies appear + * before the nodes that depend on them. This is crucial for maintaining logical + * order in code where some elements reference others. + * + * Nodes involved in circular dependencies are excluded from dependency-based + * ordering and retain their original relative positions. + * + * @example + * + * ```ts + * // TypeScript interfaces with inheritance + * const nodes = [ + * { + * name: 'AdminUser', + * dependencies: ['AdminUser'], + * dependencyNames: ['User'], + * }, + * { name: 'User', dependencies: ['User'], dependencyNames: [] }, + * { + * name: 'GuestUser', + * dependencies: ['GuestUser'], + * dependencyNames: ['User'], + * }, + * ] + * sortNodesByDependencies(nodes) + * // Returns: [User, AdminUser, GuestUser] + * // User must come first as others depend on it + * ``` + * + * @example + * + * ```ts + * // React components with hook dependencies + * const nodes = [ + * { + * name: 'MyComponent', + * dependencies: ['MyComponent'], + * dependencyNames: ['useAuth', 'useData'], + * }, + * { + * name: 'useData', + * dependencies: ['useData'], + * dependencyNames: ['useApi'], + * }, + * { name: 'useApi', dependencies: ['useApi'], dependencyNames: [] }, + * { name: 'useAuth', dependencies: ['useAuth'], dependencyNames: [] }, + * ] + * sortNodesByDependencies(nodes) + * // Returns: [useApi, useData, useAuth, MyComponent] + * // Hooks are ordered by their dependency chain + * ``` + * + * @example + * + * ```ts + * // Object properties with computed values + * const config = { + * baseUrl: 'https://api.example.com', + * apiUrl: `${this.baseUrl}/v1`, // Depends on baseUrl + * authUrl: `${this.apiUrl}/auth`, // Depends on apiUrl + * headers: { + * 'API-Key': this.apiKey, // Depends on apiKey + * }, + * apiKey: process.env.API_KEY, + * } + * // After sorting: baseUrl, apiKey, apiUrl, authUrl, headers + * ``` + * + * @template T - Type of sorting node with dependencies. + * @param nodes - Array of nodes to sort by dependencies. + * @param extraOptions - Additional sorting options. + * @returns Topologically sorted array of nodes. + */ +function sortNodesByDependencies(nodes, extraOptions) { + let nodesInCircularDependencies = computeNodesInCircularDependencies(nodes) + let result = [] + let visitedNodes = /* @__PURE__ */ new Set() + /** + * Recursively visits nodes in dependency order (depth-first). + * + * Ensures all dependencies of a node are visited and added to the result + * before the node itself. This creates the correct topological ordering. + * + * @param sortingNode - The node to visit. + */ + function visitNode(sortingNode) { + if (visitedNodes.has(sortingNode)) { + return + } + let dependentNodes = nodes + .filter(node => !nodesInCircularDependencies.has(node)) + .filter(node => isNodeDependentOnOtherNode(node, sortingNode)) + for (let dependentNode of dependentNodes) { + if ( + !extraOptions.ignoreEslintDisabledNodes || + !dependentNode.isEslintDisabled + ) { + visitNode(dependentNode) + } + } + visitedNodes.add(sortingNode) + result.push(sortingNode) + } + for (let node of nodes) { + visitNode(node) + } + return result +} +export { sortNodesByDependencies } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/sort-nodes-by-groups.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/sort-nodes-by-groups.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..10bd8e27da6cf9dbea8e6e38b49da10e09852380 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/sort-nodes-by-groups.d.ts @@ -0,0 +1,112 @@ +import { ComparatorByOptionsComputer } from './compare/default-comparator-by-options-computer.js' +import { GroupsOptions } from '../types/common-groups-options.js' +import { CommonOptions } from '../types/common-options.js' +import { SortingNode } from '../types/sorting-node.js' +export type OptionsByGroupIndexComputer = ( + groupIndex: number, +) => Options +/** + * Parameters for sorting nodes by groups. + * + * @template Node - Type of sorting node. + * @template Options - Sorting options type extending common options. + */ +interface SortNodesByGroupsParameters { + isNodeIgnoredForGroup?(props: { + groupOptions: Options + groupIndex: number + node: Node + }): boolean + comparatorByOptionsComputer: ComparatorByOptionsComputer + optionsByGroupIndexComputer: OptionsByGroupIndexComputer + isNodeIgnored?(node: Node): boolean + ignoreEslintDisabledNodes: boolean + groups: GroupsOptions + nodes: Node[] +} +/** + * Sorts nodes by distributing them into groups and sorting each group + * independently. + * + * This is the core sorting function used by all Perfectionist rules. It + * implements a two-phase sorting strategy: + * + * 1. Distribute nodes into their respective groups based on group configuration + * 2. Sort each group independently using group-specific options. + * + * Ignored nodes (ESLint-disabled or manually ignored) maintain their original + * positions to preserve intentional code organization. + * + * @example + * + * ```ts + * // React component with grouped imports + * const nodes = [ + * { name: './Button', group: 'internal' }, + * { name: 'react', group: 'external' }, + * { name: '@mui/material', group: 'external' }, + * { name: './utils', group: 'internal' }, + * ] + * + * sortNodesByGroups({ + * groups: ['external', 'internal'], + * nodes, + * optionsByGroupIndexComputer: index => ({ + * options: { type: 'alphabetical', order: 'asc' }, + * }), + * }) + * // Returns: ['@mui/material', 'react', './Button', './utils'] + * // External group sorted first, then internal group + * ``` + * + * @example + * + * ```ts + * // Class members with different sorting for each group + * class UserService { + * // Static members group - sorted alphabetically + * static VERSION = '1.0.0'; + * static API_URL = 'https://api.example.com'; + * + * // Properties group - sorted by line length + * id: string; + * cache: Map; + * + * // Methods group - sorted naturally + * async getUser() { ... } + * async updateUser() { ... } + * } + * ``` + * + * @example + * + * ```ts + * // Object with ignored properties + * const config = { + * apiUrl: 'https://api.example.com', + * timeout: 5000, + * // eslint-disable-next-line + * DEBUG_MODE: true, // This stays in place due to ESLint disable + * retries: 3, + * } + * // DEBUG_MODE maintains its position despite sorting + * ``` + * + * @template T - Type of sorting node. + * @template Options - Type of sorting options. + * @param params - Parameters for group-based sorting. + * @returns Array of nodes sorted within their groups. + */ +export declare function sortNodesByGroups< + T extends SortingNode, + Options extends Pick, +>({ + comparatorByOptionsComputer, + optionsByGroupIndexComputer, + ignoreEslintDisabledNodes, + isNodeIgnoredForGroup, + isNodeIgnored, + groups, + nodes, +}: SortNodesByGroupsParameters): T[] +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/sort-nodes-by-groups.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/sort-nodes-by-groups.js new file mode 100644 index 0000000000000000000000000000000000000000..3308a9ec978ff8adf33bf0e146e52235dfbb3fc7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/sort-nodes-by-groups.js @@ -0,0 +1,131 @@ +import { getGroupIndex } from './get-group-index.js' +import { sortNodes } from './sort-nodes.js' +/** + * Sorts nodes by distributing them into groups and sorting each group + * independently. + * + * This is the core sorting function used by all Perfectionist rules. It + * implements a two-phase sorting strategy: + * + * 1. Distribute nodes into their respective groups based on group configuration + * 2. Sort each group independently using group-specific options. + * + * Ignored nodes (ESLint-disabled or manually ignored) maintain their original + * positions to preserve intentional code organization. + * + * @example + * + * ```ts + * // React component with grouped imports + * const nodes = [ + * { name: './Button', group: 'internal' }, + * { name: 'react', group: 'external' }, + * { name: '@mui/material', group: 'external' }, + * { name: './utils', group: 'internal' }, + * ] + * + * sortNodesByGroups({ + * groups: ['external', 'internal'], + * nodes, + * optionsByGroupIndexComputer: index => ({ + * options: { type: 'alphabetical', order: 'asc' }, + * }), + * }) + * // Returns: ['@mui/material', 'react', './Button', './utils'] + * // External group sorted first, then internal group + * ``` + * + * @example + * + * ```ts + * // Class members with different sorting for each group + * class UserService { + * // Static members group - sorted alphabetically + * static VERSION = '1.0.0'; + * static API_URL = 'https://api.example.com'; + * + * // Properties group - sorted by line length + * id: string; + * cache: Map; + * + * // Methods group - sorted naturally + * async getUser() { ... } + * async updateUser() { ... } + * } + * ``` + * + * @example + * + * ```ts + * // Object with ignored properties + * const config = { + * apiUrl: 'https://api.example.com', + * timeout: 5000, + * // eslint-disable-next-line + * DEBUG_MODE: true, // This stays in place due to ESLint disable + * retries: 3, + * } + * // DEBUG_MODE maintains its position despite sorting + * ``` + * + * @template T - Type of sorting node. + * @template Options - Type of sorting options. + * @param params - Parameters for group-based sorting. + * @returns Array of nodes sorted within their groups. + */ +function sortNodesByGroups({ + comparatorByOptionsComputer, + optionsByGroupIndexComputer, + ignoreEslintDisabledNodes, + isNodeIgnoredForGroup, + isNodeIgnored, + groups, + nodes, +}) { + let nodesByNonIgnoredGroupIndex = {} + let ignoredNodeIndices = [] + for (let [index, sortingNode] of nodes.entries()) { + if ( + (ignoreEslintDisabledNodes && sortingNode.isEslintDisabled) || + isNodeIgnored?.(sortingNode) + ) { + ignoredNodeIndices.push(index) + continue + } + let groupIndex = getGroupIndex(groups, sortingNode) + nodesByNonIgnoredGroupIndex[groupIndex] ??= [] + nodesByNonIgnoredGroupIndex[groupIndex].push(sortingNode) + } + let sortedNodes = [] + let sortedGroupIndexStrings = Object.keys( + nodesByNonIgnoredGroupIndex, + ).toSorted((a, b) => Number(a) - Number(b)) + for (let groupIndexString of sortedGroupIndexStrings) { + let groupIndex = Number(groupIndexString) + let options = optionsByGroupIndexComputer(groupIndex) + let nodesToPush = nodesByNonIgnoredGroupIndex[groupIndex] + let groupIgnoredNodes = new Set( + nodesToPush.filter(node => + isNodeIgnoredForGroup?.({ + groupOptions: options, + groupIndex, + node, + }), + ), + ) + sortedNodes.push( + ...sortNodes({ + isNodeIgnored: node => groupIgnoredNodes.has(node), + ignoreEslintDisabledNodes: false, + comparatorByOptionsComputer, + nodes: nodesToPush, + options, + }), + ) + } + for (let ignoredIndex of ignoredNodeIndices) { + sortedNodes.splice(ignoredIndex, 0, nodes[ignoredIndex]) + } + return sortedNodes +} +export { sortNodesByGroups } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/sort-nodes.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/sort-nodes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5399584dea6b577680632e8f3db57318f0757b5c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/sort-nodes.d.ts @@ -0,0 +1,47 @@ +import { ComparatorByOptionsComputer } from './compare/default-comparator-by-options-computer.js' +import { CommonOptions } from '../types/common-options.js' +import { SortingNode } from '../types/sorting-node.js' +/** + * Parameters for the core sorting operation. + * + * @template Node - Type of sorting node. + * @template Options - Sorting options type extending common options. + */ +interface SortNodesParameters< + Node extends SortingNode, + Options extends Pick, +> { + comparatorByOptionsComputer: ComparatorByOptionsComputer + isNodeIgnored?(node: Node): boolean + ignoreEslintDisabledNodes: boolean + options: Options + nodes: Node[] +} +/** + * Core sorting function that performs the actual node sorting. + * + * This is the fundamental sorting engine of the Perfectionist plugin. It + * handles the actual comparison and ordering of nodes while preserving the + * positions of ignored elements. The function separates nodes into two + * categories: + * + * 1. Nodes to be sorted (non-ignored) + * 2. Nodes to keep in place (ignored or ESLint-disabled). + * + * After sorting, ignored nodes are reinserted at their original positions, + * ensuring that intentionally placed elements remain untouched. + * + * @param params - Parameters for sorting operation. + * @returns Sorted array with ignored nodes preserved at original positions. + */ +export declare function sortNodes< + Node extends SortingNode, + Options extends Pick, +>({ + comparatorByOptionsComputer, + ignoreEslintDisabledNodes, + isNodeIgnored, + options, + nodes, +}: SortNodesParameters): Node[] +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/sort-nodes.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/sort-nodes.js new file mode 100644 index 0000000000000000000000000000000000000000..befb21b6b57ee8004e00e642e15e5a5947f61599 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/sort-nodes.js @@ -0,0 +1,53 @@ +import { computeComparators } from './compare/compute-comparators.js' +/** + * Core sorting function that performs the actual node sorting. + * + * This is the fundamental sorting engine of the Perfectionist plugin. It + * handles the actual comparison and ordering of nodes while preserving the + * positions of ignored elements. The function separates nodes into two + * categories: + * + * 1. Nodes to be sorted (non-ignored) + * 2. Nodes to keep in place (ignored or ESLint-disabled). + * + * After sorting, ignored nodes are reinserted at their original positions, + * ensuring that intentionally placed elements remain untouched. + * + * @param params - Parameters for sorting operation. + * @returns Sorted array with ignored nodes preserved at original positions. + */ +function sortNodes({ + comparatorByOptionsComputer, + ignoreEslintDisabledNodes, + isNodeIgnored, + options, + nodes, +}) { + let nonIgnoredNodes = [] + let ignoredNodeIndices = [] + for (let [index, sortingNode] of nodes.entries()) { + if ( + (ignoreEslintDisabledNodes && sortingNode.isEslintDisabled) || + isNodeIgnored?.(sortingNode) + ) { + ignoredNodeIndices.push(index) + } else { + nonIgnoredNodes.push(sortingNode) + } + } + let comparators = computeComparators(comparatorByOptionsComputer, options) + let sortedNodes = [...nonIgnoredNodes].toSorted((a, b) => { + for (let comparator of comparators) { + let result = comparator(a, b) + if (result) { + return result + } + } + return 0 + }) + for (let ignoredIndex of ignoredNodeIndices) { + sortedNodes.splice(ignoredIndex, 0, nodes[ignoredIndex]) + } + return sortedNodes +} +export { sortNodes } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/unreachable-case-error.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/unreachable-case-error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3f2cf3b478e6d004f7a7e987560c65749fba6f2c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/unreachable-case-error.d.ts @@ -0,0 +1,44 @@ +/** + * Error class for exhaustive type checking in switch statements and + * conditionals. + * + * Ensures at compile-time that all possible cases of a union type are handled. + * When TypeScript's type system proves all cases are covered, the variable in + * the default case has type `never`, making this error theoretically + * unreachable in correctly typed code. + * + * This pattern is crucial for maintaining type safety when adding new options + * to existing types - TypeScript will error if a new case isn't handled. + * + * @example + * + * ```ts + * // Exhaustive handling of sorting types + * function getSortingAlgorithm( + * type: 'alphabetical' | 'natural' | 'custom', + * ) { + * switch (type) { + * case 'alphabetical': + * return alphabeticalSort + * case 'natural': + * return naturalSort + * case 'custom': + * return customSort + * default: + * throw new UnreachableCaseError(type) + * // TypeScript ensures 'type' is 'never' here + * } + * } + * ``` + */ +export declare class UnreachableCaseError extends Error { + /** + * Creates an error indicating that an supposedly unreachable case was + * reached. + * + * @param value - The value that should have type `never` if all cases are + * handled. In practice, this will contain the unhandled case value. + * @param options - Standard error options, such as `cause`. + */ + constructor(value: never, options?: ErrorOptions) +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/unreachable-case-error.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/unreachable-case-error.js new file mode 100644 index 0000000000000000000000000000000000000000..fbf86fefbc6e6970d49ff6624879471976bf675c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/unreachable-case-error.js @@ -0,0 +1,48 @@ +/** + * Error class for exhaustive type checking in switch statements and + * conditionals. + * + * Ensures at compile-time that all possible cases of a union type are handled. + * When TypeScript's type system proves all cases are covered, the variable in + * the default case has type `never`, making this error theoretically + * unreachable in correctly typed code. + * + * This pattern is crucial for maintaining type safety when adding new options + * to existing types - TypeScript will error if a new case isn't handled. + * + * @example + * + * ```ts + * // Exhaustive handling of sorting types + * function getSortingAlgorithm( + * type: 'alphabetical' | 'natural' | 'custom', + * ) { + * switch (type) { + * case 'alphabetical': + * return alphabeticalSort + * case 'natural': + * return naturalSort + * case 'custom': + * return customSort + * default: + * throw new UnreachableCaseError(type) + * // TypeScript ensures 'type' is 'never' here + * } + * } + * ``` + */ +var UnreachableCaseError = class extends Error { + /** + * Creates an error indicating that an supposedly unreachable case was + * reached. + * + * @param value - The value that should have type `never` if all cases are + * handled. In practice, this will contain the unhandled case value. + * @param options - Standard error options, such as `cause`. + */ + constructor(value, options) { + super(`Unreachable case: ${value}`, options) + this.name = 'UnreachableCaseError' + } +} +export { UnreachableCaseError } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-custom-sort-config.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-custom-sort-config.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..76c26c75c823e55760c1bbac4137b0cb1c52fb7e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-custom-sort-config.d.ts @@ -0,0 +1,23 @@ +import { CommonGroupsOptions } from '../types/common-groups-options.js' +import { CommonOptions } from '../types/common-options.js' +/** + * Options for custom sort configuration validation. + */ +type Options = { + groups?: CommonGroupsOptions['groups'] +} & Pick +/** + * Validates configuration when using custom sort type. + * + * Ensures that when a user selects 'custom' sorting type, they provide a valid + * alphabet string. This prevents runtime errors and ensures the custom sorting + * has a defined order to follow. + * + * The function is called at the beginning of every sorting rule's execution to + * catch configuration errors early and provide clear error messages. + * + * @param options - Configuration options to validate. + * @throws {Error} If type is 'custom' but alphabet is empty. + */ +export declare function validateCustomSortConfig(options: Options): void +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-custom-sort-config.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-custom-sort-config.js new file mode 100644 index 0000000000000000000000000000000000000000..1c2be4a74de8621d83eb069215749f35d8c6911d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-custom-sort-config.js @@ -0,0 +1,37 @@ +import { isGroupWithOverridesOption } from './is-group-with-overrides-option.js' +/** + * Validates configuration when using custom sort type. + * + * Ensures that when a user selects 'custom' sorting type, they provide a valid + * alphabet string. This prevents runtime errors and ensures the custom sorting + * has a defined order to follow. + * + * The function is called at the beginning of every sorting rule's execution to + * catch configuration errors early and provide clear error messages. + * + * @param options - Configuration options to validate. + * @throws {Error} If type is 'custom' but alphabet is empty. + */ +function validateCustomSortConfig(options) { + if (!usesCustomSort(options)) { + return + } + if (options.alphabet.length === 0) { + throw new Error('`alphabet` option must not be empty') + } +} +function usesCustomSortInGroups(groups) { + if (!groups) { + return false + } + return groups + .filter(isGroupWithOverridesOption) + .some(groupWithSettings => groupWithSettings.type === 'custom') +} +function usesCustomSort(options) { + if (options.type === 'custom') { + return true + } + return usesCustomSortInGroups(options.groups) +} +export { validateCustomSortConfig } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-groups-config.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-groups-config.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..370351753116702dc040cd3d8fc5638d75add9c4 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-groups-config.d.ts @@ -0,0 +1,85 @@ +import { CommonGroupsOptions } from '../types/common-groups-options.js' +/** + * Parameters for validating generated groups configuration. + */ +interface ValidateGenerateGroupsConfigParameters { + options: Pick< + CommonGroupsOptions, + 'customGroups' | 'groups' + > + selectors: readonly string[] + modifiers: readonly string[] +} +/** + * Validates that all groups in configuration are either predefined or custom. + * + * Ensures that every group specified in the configuration either: + * + * 1. Is a valid predefined group (combination of modifiers and selectors) + * 2. Is defined in customGroups + * 3. Is the special 'unknown' group. + * + * Also validates that there are no duplicate groups. + * + * @example + * + * ```ts + * // Valid predefined groups for React imports + * validateGeneratedGroupsConfiguration({ + * options: { + * groups: ['react', 'external', 'internal', 'side-effect-import'], + * customGroups: [], + * }, + * selectors: ['import', 'export'], + * modifiers: ['side-effect', 'type', 'value'], + * }) + * // All groups are valid predefined groups + * ``` + * + * @example + * + * ```ts + * // Invalid group that doesn't exist + * validateGeneratedGroupsConfiguration({ + * options: { + * groups: ['my-special-group'], // Not predefined, not in customGroups + * customGroups: [], + * }, + * selectors: ['property', 'method'], + * modifiers: ['static', 'private'], + * }) + * // Throws: Error: Invalid group(s): my-special-group + * ``` + * + * @example + * + * ```ts + * // Valid with custom groups for class members + * validateGeneratedGroupsConfiguration({ + * options: { + * groups: ['static-property', 'constructor', 'lifecycle-methods'], + * customGroups: [ + * { + * groupName: 'lifecycle-methods', + * elementNamePattern: [ + * /^componentDidMount$/, + * /^componentWillUnmount$/, + * ], + * }, + * ], + * }, + * selectors: ['property', 'method', 'constructor'], + * modifiers: ['static', 'private', 'public'], + * }) + * // 'static-property' is predefined, 'lifecycle-methods' is custom + * ``` + * + * @param params - Configuration parameters to validate. + * @throws {Error} If any group is neither predefined nor custom. + */ +export declare function validateGroupsConfig({ + selectors, + modifiers, + options, +}: ValidateGenerateGroupsConfigParameters): void +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-groups-config.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-groups-config.js new file mode 100644 index 0000000000000000000000000000000000000000..77ece33c89a69fe10a7bdabfd49316ea3ac4fef7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-groups-config.js @@ -0,0 +1,223 @@ +import { computeGroupsNames } from './compute-groups-names.js' +import { validateObjectsInsideGroups } from './validate-objects-inside-groups.js' +import { validateNoDuplicatedGroups } from './validate-no-duplicated-groups.js' +/** + * Validates that all groups in configuration are either predefined or custom. + * + * Ensures that every group specified in the configuration either: + * + * 1. Is a valid predefined group (combination of modifiers and selectors) + * 2. Is defined in customGroups + * 3. Is the special 'unknown' group. + * + * Also validates that there are no duplicate groups. + * + * @example + * + * ```ts + * // Valid predefined groups for React imports + * validateGeneratedGroupsConfiguration({ + * options: { + * groups: ['react', 'external', 'internal', 'side-effect-import'], + * customGroups: [], + * }, + * selectors: ['import', 'export'], + * modifiers: ['side-effect', 'type', 'value'], + * }) + * // All groups are valid predefined groups + * ``` + * + * @example + * + * ```ts + * // Invalid group that doesn't exist + * validateGeneratedGroupsConfiguration({ + * options: { + * groups: ['my-special-group'], // Not predefined, not in customGroups + * customGroups: [], + * }, + * selectors: ['property', 'method'], + * modifiers: ['static', 'private'], + * }) + * // Throws: Error: Invalid group(s): my-special-group + * ``` + * + * @example + * + * ```ts + * // Valid with custom groups for class members + * validateGeneratedGroupsConfiguration({ + * options: { + * groups: ['static-property', 'constructor', 'lifecycle-methods'], + * customGroups: [ + * { + * groupName: 'lifecycle-methods', + * elementNamePattern: [ + * /^componentDidMount$/, + * /^componentWillUnmount$/, + * ], + * }, + * ], + * }, + * selectors: ['property', 'method', 'constructor'], + * modifiers: ['static', 'private', 'public'], + * }) + * // 'static-property' is predefined, 'lifecycle-methods' is custom + * ``` + * + * @param params - Configuration parameters to validate. + * @throws {Error} If any group is neither predefined nor custom. + */ +function validateGroupsConfig({ selectors, modifiers, options }) { + let availableCustomGroupNames = new Set( + options.customGroups.map(customGroup => customGroup.groupName), + ) + let invalidGroups = computeGroupsNames(options.groups).filter( + group => + !isPredefinedGroup(selectors, modifiers, group) && + !availableCustomGroupNames.has(group), + ) + if (invalidGroups.length > 0) { + throw new Error(`Invalid group(s): ${invalidGroups.join(', ')}`) + } + validateNoDuplicatedGroups(options) + validateObjectsInsideGroups(options) +} +/** + * Checks if a group name is a valid predefined group. + * + * Predefined groups are formed by combining modifiers and selectors with + * dashes. The function parses the group name from right to left, first + * extracting the selector (which can be up to 3 words), then the modifiers. + * + * @example + * + * ```ts + * // Valid predefined groups + * isPredefinedGroup( + * ['property', 'method'], + * ['static', 'private'], + * 'static-private-property', + * ) + * // Returns: true (static + private + property) + * ``` + * + * @example + * + * ```ts + * // Special 'unknown' group + * isPredefinedGroup([], [], 'unknown') + * // Returns: true (always valid) + * ``` + * + * @example + * + * ```ts + * // Invalid group - not matching selectors + * isPredefinedGroup( + * ['import', 'export'], + * ['type', 'value'], + * 'custom-group', + * ) + * // Returns: false ('group' is not a valid selector) + * ``` + * + * @param allSelectors - Available selectors for the rule. + * @param allModifiers - Available modifiers for the rule. + * @param input - Group name to validate. + * @returns True if the group is a valid predefined combination. + */ +function isPredefinedGroup(allSelectors, allModifiers, input) { + if (input === 'unknown') { + return true + } + let elementsSeparatedWithDash = input.split('-') + let longestAllowedSelector = computeLongestAllowedWord({ + allowedValues: allSelectors, + elementsSeparatedWithDash, + }) + if (!longestAllowedSelector) { + return false + } + let modifiersToParse = elementsSeparatedWithDash.slice( + 0, + -longestAllowedSelector.wordCount, + ) + let parsedModifiers = /* @__PURE__ */ new Set() + while (modifiersToParse.length > 0) { + let longestAllowedModifier = computeLongestAllowedWord({ + elementsSeparatedWithDash: modifiersToParse, + allowedValues: allModifiers, + }) + if (!longestAllowedModifier) { + return false + } + if (parsedModifiers.has(longestAllowedModifier.word)) { + return false + } + parsedModifiers.add(longestAllowedModifier.word) + modifiersToParse = modifiersToParse.slice( + 0, + -longestAllowedModifier.wordCount, + ) + } + return true +} +/** + * Finds the longest valid word from the end of a dash-separated array. + * + * Attempts to match 3-word, 2-word, then 1-word combinations from the end of + * the array against allowed values. This is used to parse selectors and + * modifiers from group names. + * + * @example + * + * ```ts + * // Matching a multi-word selector + * computeLongestAllowedWord({ + * elementsSeparatedWithDash: ['static', 'get', 'accessor'], + * allowedValues: ['accessor', 'get-accessor', 'property'], + * }) + * // Returns: { word: 'get-accessor', wordCount: 2 } + * ``` + * + * @example + * + * ```ts + * // Matching a single-word modifier + * computeLongestAllowedWord({ + * elementsSeparatedWithDash: ['private', 'static'], + * allowedValues: ['static', 'private', 'public'], + * }) + * // Returns: { word: 'static', wordCount: 1 } + * ``` + * + * @param params - Parameters for word matching. + * @returns Matched word with its word count, or null if no match. + */ +function computeLongestAllowedWord({ + elementsSeparatedWithDash, + allowedValues, +}) { + let match = [ + { + word: elementsSeparatedWithDash.slice(-3).join('-'), + wordCount: 3, + }, + { + word: elementsSeparatedWithDash.slice(-2).join('-'), + wordCount: 2, + }, + { + word: elementsSeparatedWithDash.at(-1), + wordCount: 1, + }, + ] + .filter(({ wordCount }) => elementsSeparatedWithDash.length >= wordCount) + .find(({ word }) => word && allowedValues.includes(word)) + if (!match) { + return null + } + return match +} +export { validateGroupsConfig } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-newlines-and-partition-config.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-newlines-and-partition-config.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..289ccb178e57a7126ca83fc7f91a5e0f3139241e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-newlines-and-partition-config.d.ts @@ -0,0 +1,111 @@ +import { CommonGroupsOptions } from '../types/common-groups-options.js' +import { CommonPartitionOptions } from '../types/common-partition-options.js' +/** + * Options for validating newlines and partition configuration. + */ +type Options = Pick< + CommonGroupsOptions, + 'newlinesBetween' | 'newlinesInside' | 'customGroups' | 'groups' +> & + Pick +/** + * Validates that newline-related options don't conflict with each other. + * + * Ensures mutual exclusivity between partition-based and newline-insertion + * approaches to managing spacing. These options conflict because: + * + * - `partitionByNewLine` preserves existing newlines as partition boundaries + * - `newlinesBetween` actively manages newlines between groups. + * + * Using both would create ambiguous behavior where the plugin doesn't know + * whether to preserve or modify existing newlines. + * + * @example + * + * ```ts + * // Valid: Using partitionByNewLine alone + * validateNewlinesAndPartitionConfig({ + * partitionByNewLine: true, + * newlinesBetween: 'ignore', // Must be 'ignore' with partitions + * groups: ['external', 'internal'], + * }) + * // Preserves existing blank lines as boundaries + * ``` + * + * @example + * + * ```ts + * // Invalid: Conflicting options + * validateNewlinesAndPartitionConfig({ + * partitionByNewLine: true, + * newlinesBetween: 1, // Conflicts with partitionByNewLine + * groups: ['react', 'external', 'internal'], + * }) + * // Throws: The 'partitionByNewLine' and 'newlinesBetween' options cannot be used together + * ``` + * + * @example + * + * ```ts + * // Invalid: newlinesBetween in groups with partitions + * validateNewlinesAndPartitionConfig({ + * partitionByNewLine: true, + * newlinesBetween: 'ignore', + * groups: [ + * 'external', + * { newlinesBetween: 1 }, // Can't use with partitions + * 'internal', + * ], + * }) + * // Throws: 'newlinesBetween' objects can not be used in 'groups' alongside 'partitionByNewLine' + * ``` + * + * @example + * + * ```ts + * // Valid: Using newlinesBetween without partitions + * validateNewlinesAndPartitionConfig({ + * partitionByNewLine: false, + * newlinesBetween: 1, + * groups: [ + * 'react', + * { newlinesBetween: 1 }, + * 'external', + * { newlinesBetween: 1 }, + * 'internal', + * ], + * }) + * // Actively manages spacing between import groups + * ``` + * + * @example + * + * ```ts + * // Real-world React imports configuration + * // Option 1: Preserve developer's spacing + * validateNewlinesAndPartitionConfig({ + * partitionByNewLine: true, + * newlinesBetween: 'ignore', + * groups: ['react', 'external', '@company', 'internal', 'relative'], + * }) + * + * // Option 2: Enforce consistent spacing + * validateNewlinesAndPartitionConfig({ + * partitionByNewLine: false, + * newlinesBetween: 1, + * groups: ['react', 'external', '@company', 'internal', 'relative'], + * }) + * // Choose one approach, not both + * ``` + * + * @param options - Configuration options to validate. + * @throws {Error} If partitionByNewLine and newlinesBetween conflict. + */ +export declare function validateNewlinesAndPartitionConfig({ + partitionByNewLine, + newlinesBetween, + newlinesInside, + customGroups, + groups, +}: Options): void +export {} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-newlines-and-partition-config.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-newlines-and-partition-config.js new file mode 100644 index 0000000000000000000000000000000000000000..1c95caba9794ae790a841408a50f24f68cc42138 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-newlines-and-partition-config.js @@ -0,0 +1,170 @@ +import { isGroupWithOverridesOption } from './is-group-with-overrides-option.js' +import { isNewlinesBetweenOption } from './is-newlines-between-option.js' +var NEWLINES_INSIDE_ERROR_MESSAGE = + "The 'partitionByNewLine' and 'newlinesInside' options cannot be used together" +var NEWLINES_BETWEEN_ERROR_MESSAGE = + "The 'partitionByNewLine' and 'newlinesBetween' options cannot be used together" +/** + * Validates that newline-related options don't conflict with each other. + * + * Ensures mutual exclusivity between partition-based and newline-insertion + * approaches to managing spacing. These options conflict because: + * + * - `partitionByNewLine` preserves existing newlines as partition boundaries + * - `newlinesBetween` actively manages newlines between groups. + * + * Using both would create ambiguous behavior where the plugin doesn't know + * whether to preserve or modify existing newlines. + * + * @example + * + * ```ts + * // Valid: Using partitionByNewLine alone + * validateNewlinesAndPartitionConfig({ + * partitionByNewLine: true, + * newlinesBetween: 'ignore', // Must be 'ignore' with partitions + * groups: ['external', 'internal'], + * }) + * // Preserves existing blank lines as boundaries + * ``` + * + * @example + * + * ```ts + * // Invalid: Conflicting options + * validateNewlinesAndPartitionConfig({ + * partitionByNewLine: true, + * newlinesBetween: 1, // Conflicts with partitionByNewLine + * groups: ['react', 'external', 'internal'], + * }) + * // Throws: The 'partitionByNewLine' and 'newlinesBetween' options cannot be used together + * ``` + * + * @example + * + * ```ts + * // Invalid: newlinesBetween in groups with partitions + * validateNewlinesAndPartitionConfig({ + * partitionByNewLine: true, + * newlinesBetween: 'ignore', + * groups: [ + * 'external', + * { newlinesBetween: 1 }, // Can't use with partitions + * 'internal', + * ], + * }) + * // Throws: 'newlinesBetween' objects can not be used in 'groups' alongside 'partitionByNewLine' + * ``` + * + * @example + * + * ```ts + * // Valid: Using newlinesBetween without partitions + * validateNewlinesAndPartitionConfig({ + * partitionByNewLine: false, + * newlinesBetween: 1, + * groups: [ + * 'react', + * { newlinesBetween: 1 }, + * 'external', + * { newlinesBetween: 1 }, + * 'internal', + * ], + * }) + * // Actively manages spacing between import groups + * ``` + * + * @example + * + * ```ts + * // Real-world React imports configuration + * // Option 1: Preserve developer's spacing + * validateNewlinesAndPartitionConfig({ + * partitionByNewLine: true, + * newlinesBetween: 'ignore', + * groups: ['react', 'external', '@company', 'internal', 'relative'], + * }) + * + * // Option 2: Enforce consistent spacing + * validateNewlinesAndPartitionConfig({ + * partitionByNewLine: false, + * newlinesBetween: 1, + * groups: ['react', 'external', '@company', 'internal', 'relative'], + * }) + * // Choose one approach, not both + * ``` + * + * @param options - Configuration options to validate. + * @throws {Error} If partitionByNewLine and newlinesBetween conflict. + */ +function validateNewlinesAndPartitionConfig({ + partitionByNewLine, + newlinesBetween, + newlinesInside, + customGroups, + groups, +}) { + if (!partitionByNewLine) { + return + } + validateNewlinesBetweenConfig({ + newlinesBetween, + groups, + }) + validateNewlinesInsideConfig({ + newlinesInside, + customGroups, + groups, + }) +} +function validateNewlinesInsideConfig({ + newlinesInside, + customGroups, + groups, +}) { + switch (newlinesInside) { + case 'newlinesBetween': + case 'ignore': + break + default: + throw new Error(NEWLINES_INSIDE_ERROR_MESSAGE) + } + validateGroups() + validateCustomGroups() + function validateCustomGroups() { + for (let customGroup of customGroups) { + throwErrorIfNeeded(customGroup.newlinesInside) + } + } + function validateGroups() { + for (let group of groups) { + if (!isGroupWithOverridesOption(group)) { + continue + } + throwErrorIfNeeded(group.newlinesInside) + } + } + function throwErrorIfNeeded(newlinesInsideOptions) { + switch (newlinesInsideOptions) { + case void 0: + case 'ignore': + return + default: + throw new Error(NEWLINES_INSIDE_ERROR_MESSAGE) + } + } +} +function validateNewlinesBetweenConfig({ newlinesBetween, groups }) { + if (newlinesBetween !== 'ignore') { + throw new Error(NEWLINES_BETWEEN_ERROR_MESSAGE) + } + if ( + groups.some( + group => + isNewlinesBetweenOption(group) && group.newlinesBetween !== 'ignore', + ) + ) { + throw new Error(NEWLINES_BETWEEN_ERROR_MESSAGE) + } +} +export { validateNewlinesAndPartitionConfig } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-no-duplicated-groups.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-no-duplicated-groups.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..83b4cbe9d8c3c4a62be6b895133e86da811689c7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-no-duplicated-groups.d.ts @@ -0,0 +1,13 @@ +import { GroupsOptions } from '../types/common-groups-options.js' +/** + * Throws an error if a group is specified more than once. + * + * @param parameters - Parameters object. + * @param parameters.groups - The groups to check for duplicates. + * @throws Error Will throw an error if duplicated groups are found. + */ +export declare function validateNoDuplicatedGroups({ + groups, +}: { + groups: GroupsOptions +}): void diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-no-duplicated-groups.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-no-duplicated-groups.js new file mode 100644 index 0000000000000000000000000000000000000000..719c59a68bb46a22f79cb878e83d374d9dc94c69 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-no-duplicated-groups.js @@ -0,0 +1,24 @@ +import { computeGroupsNames } from './compute-groups-names.js' +/** + * Throws an error if a group is specified more than once. + * + * @param parameters - Parameters object. + * @param parameters.groups - The groups to check for duplicates. + * @throws Error Will throw an error if duplicated groups are found. + */ +function validateNoDuplicatedGroups({ groups }) { + let groupNames = computeGroupsNames(groups) + let seenGroups = /* @__PURE__ */ new Set() + let duplicatedGroups = /* @__PURE__ */ new Set() + for (let groupName of groupNames) { + if (seenGroups.has(groupName)) { + duplicatedGroups.add(groupName) + } else { + seenGroups.add(groupName) + } + } + if (duplicatedGroups.size > 0) { + throw new Error(`Duplicated group(s): ${[...duplicatedGroups].join(', ')}`) + } +} +export { validateNoDuplicatedGroups } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-objects-inside-groups.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-objects-inside-groups.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..47addd16303f327d4f72359e28c4fd80d80fdb88 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-objects-inside-groups.d.ts @@ -0,0 +1,64 @@ +import { GroupsOptions } from '../types/common-groups-options.js' +/** + * Validates that consecutive objects in groups are merged into single objects. + * + * Prevents configuration confusion by ensuring that spacing and object-based + * groups are consolidated. + * + * @example + * + * ```ts + * // Invalid: Consecutive objects + * validateObjectsInsideGroups({ + * groups: [ + * 'react', + * { newlinesBetween: 1 }, + * { newlinesBetween: 2 }, // Error: consecutive objects + * { group: 'group', commentAbove: '// External libraries' }, + * 'external', + * ], + * }) + * // Throws: Consecutive `newlinesBetween` objects are not allowed + * ``` + * + * @example + * + * ```ts + * // Valid: Merged into single object + * validateObjectsInsideGroups({ + * groups: [ + * 'react', + * { + * newlinesBetween: 1, + * commentAbove: '// External libraries', + * }, + * 'external', + * ], + * }) + * // Correct: Single object with both directives + * ``` + * + * @example + * + * ```ts + * // Valid: Non-consecutive objects + * validateObjectsInsideGroups({ + * groups: [ + * 'react', + * { newlinesBetween: 1 }, + * 'external', + * { newlinesBetween: 1 }, + * 'internal', + * ], + * }) + * // OK: Objects separated by string groups + * ``` + * + * @param options - Configuration object containing groups. + * @throws {Error} If consecutive objects are found in groups. + */ +export declare function validateObjectsInsideGroups({ + groups, +}: { + groups: GroupsOptions +}): void diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-objects-inside-groups.js b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-objects-inside-groups.js new file mode 100644 index 0000000000000000000000000000000000000000..ce46ba5d5206d315dbefb823243fc052d52ce999 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/dist/utils/validate-objects-inside-groups.js @@ -0,0 +1,74 @@ +import { computeGroupsNames } from './compute-groups-names.js' +/** + * Validates that consecutive objects in groups are merged into single objects. + * + * Prevents configuration confusion by ensuring that spacing and object-based + * groups are consolidated. + * + * @example + * + * ```ts + * // Invalid: Consecutive objects + * validateObjectsInsideGroups({ + * groups: [ + * 'react', + * { newlinesBetween: 1 }, + * { newlinesBetween: 2 }, // Error: consecutive objects + * { group: 'group', commentAbove: '// External libraries' }, + * 'external', + * ], + * }) + * // Throws: Consecutive `newlinesBetween` objects are not allowed + * ``` + * + * @example + * + * ```ts + * // Valid: Merged into single object + * validateObjectsInsideGroups({ + * groups: [ + * 'react', + * { + * newlinesBetween: 1, + * commentAbove: '// External libraries', + * }, + * 'external', + * ], + * }) + * // Correct: Single object with both directives + * ``` + * + * @example + * + * ```ts + * // Valid: Non-consecutive objects + * validateObjectsInsideGroups({ + * groups: [ + * 'react', + * { newlinesBetween: 1 }, + * 'external', + * { newlinesBetween: 1 }, + * 'internal', + * ], + * }) + * // OK: Objects separated by string groups + * ``` + * + * @param options - Configuration object containing groups. + * @throws {Error} If consecutive objects are found in groups. + */ +function validateObjectsInsideGroups({ groups }) { + let isPreviousElementNonGroupBased = false + for (let group of groups) { + let [groupName] = computeGroupsNames([group]) + if (groupName) { + isPreviousElementNonGroupBased = false + continue + } + if (isPreviousElementNonGroupBased) { + throw new Error('Consecutive `newlinesBetween` objects are not allowed') + } + isPreviousElementNonGroupBased = true + } +} +export { validateObjectsInsideGroups } diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/license.md b/tools/ui/node_modules/eslint-plugin-perfectionist/license.md new file mode 100644 index 0000000000000000000000000000000000000000..5e85c8f53f5400b06c1e74e72b49d9e755ef1ce0 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/license.md @@ -0,0 +1,20 @@ +# The MIT License (MIT) + +Copyright 2023 Azat S. + +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/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/LICENSE b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..310a18f8a6cbbe878d7c2874d6e3323827709b99 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 typescript-eslint and other 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/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/README.md b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cf1a671681d63076a2ffc04b25ab3f8a86cd7f07 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/README.md @@ -0,0 +1,12 @@ +# `@typescript-eslint/project-service` + +> Standalone TypeScript project service wrapper for linting. + +[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/project-service.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/project-service) +[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/project-service.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/project-service) + +A standalone export of the "Project Service" that powers typed linting for typescript-eslint. + +> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code. + + diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/dist/createProjectService.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/dist/createProjectService.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee5ec3b90f44de580f14365cd8fd91abc76c82b4 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/dist/createProjectService.d.ts @@ -0,0 +1,65 @@ +import type { ProjectServiceOptions } from '@typescript-eslint/types'; +import type * as ts from 'typescript/lib/tsserverlibrary'; +/** + * Shortcut type to refer to TypeScript's server ProjectService. + */ +export type TypeScriptProjectService = ts.server.ProjectService; +/** + * A created Project Service instance, as well as metadata on its creation. + */ +export interface ProjectServiceAndMetadata { + /** + * Files allowed to be loaded from the default project, if any were specified. + */ + allowDefaultProject: string[] | undefined; + /** + * The performance.now() timestamp of the last reload of the project service. + */ + lastReloadTimestamp: number; + /** + * The maximum number of files that can be matched by the default project. + */ + maximumDefaultProjectFileMatchCount: number; + /** + * The created TypeScript Project Service instance. + */ + service: TypeScriptProjectService; +} +/** + * Settings to create a new Project Service instance with {@link createProjectService}. + */ +export interface CreateProjectServiceSettings { + /** + * Granular options to configure the project service. + */ + options?: ProjectServiceOptions; + /** + * How aggressively (and slowly) to parse JSDoc comments. + */ + jsDocParsingMode?: ts.JSDocParsingMode; + /** + * Root directory for the tsconfig.json file, if not the current directory. + */ + tsconfigRootDir?: string; + /** + * Custom project service host. + * + * @default `ts.sys` with stub watchers + */ + host?: Partial; +} +/** + * Creates a new Project Service instance, as well as metadata on its creation. + * @param settings Settings to create a new Project Service instance. + * @returns A new Project Service instance, as well as metadata on its creation. + * @example + * ```ts + * import { createProjectService } from '@typescript-eslint/project-service'; + * + * const { service } = createProjectService(); + * + * service.openClientFile('index.ts'); + * ``` + */ +export declare function createProjectService({ host, jsDocParsingMode, options: optionsRaw, tsconfigRootDir, }?: CreateProjectServiceSettings): ProjectServiceAndMetadata; +export { type ProjectServiceOptions } from '@typescript-eslint/types'; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/dist/createProjectService.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/dist/createProjectService.js new file mode 100644 index 0000000000000000000000000000000000000000..3f569a8a15dc1c5bbacb0971ecc790bef427aa58 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/dist/createProjectService.js @@ -0,0 +1,138 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createProjectService = createProjectService; +const debug_1 = __importDefault(require("debug")); +const getParsedConfigFileFromTSServer_js_1 = require("./getParsedConfigFileFromTSServer.js"); +const DEFAULT_PROJECT_MATCHED_FILES_THRESHOLD = 8; +const log = (0, debug_1.default)('typescript-eslint:project-service:createProjectService'); +const logTsserverErr = (0, debug_1.default)('typescript-eslint:project-service:tsserver:err'); +const logTsserverInfo = (0, debug_1.default)('typescript-eslint:project-service:tsserver:info'); +const logTsserverPerf = (0, debug_1.default)('typescript-eslint:project-service:tsserver:perf'); +const logTsserverEvent = (0, debug_1.default)('typescript-eslint:project-service:tsserver:event'); +// For TypeScript APIs that expect a function to be passed in +// eslint-disable-next-line @typescript-eslint/no-empty-function +const doNothing = () => { }; +const createStubFileWatcher = () => ({ + close: doNothing, +}); +/** + * Creates a new Project Service instance, as well as metadata on its creation. + * @param settings Settings to create a new Project Service instance. + * @returns A new Project Service instance, as well as metadata on its creation. + * @example + * ```ts + * import { createProjectService } from '@typescript-eslint/project-service'; + * + * const { service } = createProjectService(); + * + * service.openClientFile('index.ts'); + * ``` + */ +function createProjectService({ host, jsDocParsingMode, options: optionsRaw = {}, tsconfigRootDir, } = {}) { + const options = { + defaultProject: 'tsconfig.json', + ...optionsRaw, + }; + // We import this lazily to avoid its cost for users who don't use the service + // TODO: Once we drop support for TS<5.3 we can import from "typescript" directly + // eslint-disable-next-line @typescript-eslint/no-require-imports + const tsserver = require('typescript/lib/tsserverlibrary'); + // TODO: see getWatchProgramsForProjects + // We don't watch the disk, we just refer to these when ESLint calls us + // there's a whole separate update pass in maybeInvalidateProgram at the bottom of getWatchProgramsForProjects + // (this "goes nuclear on TypeScript") + const system = { + ...tsserver.sys, + clearImmediate, + clearTimeout, + setImmediate, + setTimeout, + watchDirectory: createStubFileWatcher, + watchFile: createStubFileWatcher, + // We stop loading any TypeScript plugins by default, to prevent them from attaching disk watchers + // See https://github.com/typescript-eslint/typescript-eslint/issues/9905 + ...(!options.loadTypeScriptPlugins && { + require: () => ({ + error: { + message: 'TypeScript plugins are not required when using parserOptions.projectService.', + }, + module: undefined, + }), + }), + ...host, + }; + const logger = { + close: doNothing, + endGroup: doNothing, + getLogFileName: () => undefined, + // The debug library doesn't use levels without creating a namespace for each. + // Log levels are not passed to the writer so we wouldn't be able to forward + // to a respective namespace. Supporting would require an additional flag for + // granular control. Defaulting to all levels for now. + hasLevel: () => true, + info(s) { + this.msg(s, tsserver.server.Msg.Info); + }, + loggingEnabled: () => + // if none of the debug namespaces are enabled, then don't enable logging in tsserver + logTsserverInfo.enabled || + logTsserverErr.enabled || + logTsserverPerf.enabled, + msg: (s, type) => { + switch (type) { + case tsserver.server.Msg.Err: + logTsserverErr(s); + break; + case tsserver.server.Msg.Perf: + logTsserverPerf(s); + break; + default: + logTsserverInfo(s); + } + }, + perftrc(s) { + this.msg(s, tsserver.server.Msg.Perf); + }, + startGroup: doNothing, + }; + log('Creating Project Service with: %o', options); + const service = new tsserver.server.ProjectService({ + cancellationToken: { isCancellationRequested: () => false }, + eventHandler: logTsserverEvent.enabled + ? (e) => { + logTsserverEvent(e); + } + : undefined, + host: system, + jsDocParsingMode, + logger, + session: undefined, + useInferredProjectPerProjectRoot: false, + useSingleInferredProject: false, + }); + service.setHostConfiguration({ + preferences: { + includePackageJsonAutoImports: 'off', + }, + }); + log('Enabling default project: %s', options.defaultProject); + const configFile = (0, getParsedConfigFileFromTSServer_js_1.getParsedConfigFileFromTSServer)(tsserver, options.defaultProject, !!optionsRaw.defaultProject, tsconfigRootDir); + if (configFile) { + service.setCompilerOptionsForInferredProjects( + // NOTE: The inferred projects API is not intended for source files when a tsconfig + // exists. There is no API that generates an InferredProjectCompilerOptions suggesting + // it is meant for hard coded options passed in. Hard asserting as a work around. + // See https://github.com/microsoft/TypeScript/blob/27bcd4cb5a98bce46c9cdd749752703ead021a4b/src/server/protocol.ts#L1904 + configFile.options); + } + return { + allowDefaultProject: options.allowDefaultProject, + lastReloadTimestamp: performance.now(), + maximumDefaultProjectFileMatchCount: options.maximumDefaultProjectFileMatchCount_THIS_WILL_SLOW_DOWN_LINTING ?? + DEFAULT_PROJECT_MATCHED_FILES_THRESHOLD, + service, + }; +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/dist/getParsedConfigFileFromTSServer.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/dist/getParsedConfigFileFromTSServer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c1ea9e4c5c530fe79945f8095cd99c4611a79885 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/dist/getParsedConfigFileFromTSServer.d.ts @@ -0,0 +1,2 @@ +import type * as ts from 'typescript/lib/tsserverlibrary'; +export declare function getParsedConfigFileFromTSServer(tsserver: typeof ts, defaultProject: string, throwOnFailure: boolean, tsconfigRootDir?: string): ts.ParsedCommandLine | undefined; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/dist/getParsedConfigFileFromTSServer.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/dist/getParsedConfigFileFromTSServer.js new file mode 100644 index 0000000000000000000000000000000000000000..9e6d3fb312e0c0a5a592126cbbb6da7d19a2427f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/dist/getParsedConfigFileFromTSServer.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getParsedConfigFileFromTSServer = getParsedConfigFileFromTSServer; +const tsconfig_utils_1 = require("@typescript-eslint/tsconfig-utils"); +function getParsedConfigFileFromTSServer(tsserver, defaultProject, throwOnFailure, tsconfigRootDir) { + try { + return (0, tsconfig_utils_1.getParsedConfigFile)(tsserver, defaultProject, tsconfigRootDir); + } + catch (error) { + if (throwOnFailure) { + throw new Error(`Could not read Project Service default project '${defaultProject}': ${error.message}`, { cause: error }); + } + } + return undefined; +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/dist/index.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..943c04088b69dd7893a20b07baf109c0faf35726 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/dist/index.d.ts @@ -0,0 +1 @@ +export * from './createProjectService'; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/dist/index.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f574a9b9df5c75fe597982723879744b624754e9 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/dist/index.js @@ -0,0 +1,17 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./createProjectService"), exports); diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/package.json b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3369973bdcd6a9fbc6d1f6ac1c314cde36e8dfa5 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/project-service/package.json @@ -0,0 +1,82 @@ +{ + "name": "@typescript-eslint/project-service", + "version": "8.66.0", + "description": "Standalone TypeScript project service wrapper for linting.", + "files": [ + "dist", + "!**/*.tsbuildinfo" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "types": "./dist/index.d.ts", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/project-service" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io", + "license": "MIT", + "keywords": [ + "eslint", + "typescript", + "estree" + ], + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + }, + "dependencies": { + "debug": "^4.4.3", + "@typescript-eslint/tsconfig-utils": "^8.66.0", + "@typescript-eslint/types": "^8.66.0" + }, + "devDependencies": { + "@typescript/native-preview": "7.0.0-dev.20260518.1", + "@vitest/coverage-v8": "^4.0.18", + "rimraf": "^5.0.10", + "typescript": ">=4.8.4 <6.1.0", + "vitest": "^4.0.18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "publishConfig": { + "access": "public" + }, + "nx": { + "name": "project-service", + "includedScripts": [ + "clean" + ], + "targets": { + "lint": { + "command": "eslint" + }, + "typecheck:tsgo": {}, + "attw-check": {} + } + }, + "scripts": { + "//": "These package scripts are mostly here for convenience. Task running is handled by Nx at the root level.", + "build": "pnpm exec nx build", + "clean": "rimraf dist/ coverage/", + "format": "pnpm -w run format", + "lint": "pnpm -w exec nx lint", + "test": "pnpm -w exec nx test", + "typecheck": "pnpm -w exec nx typecheck", + "typecheck:tsgo": "pnpm -w exec nx typecheck:tsgo", + "attw-check": "pnpm -w exec nx attw-check" + } +} \ No newline at end of file diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/LICENSE b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a1164108d4d6037cb976384c16e5493917d87157 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 typescript-eslint and other 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/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/README.md b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b730e9d83a99b3c3422018d0a3f2b4289aaeb5d8 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/README.md @@ -0,0 +1,10 @@ +# `@typescript-eslint/scope-manager` + +[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/scope-manager.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/scope-manager) +[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/scope-manager.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/scope-manager) + +👉 See **https://typescript-eslint.io/packages/scope-manager** for documentation on this package. + +> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code. + + diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/ID.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/ID.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5198dff5096e65e8baecc55cf6146ceab24707e8 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/ID.d.ts @@ -0,0 +1,2 @@ +export declare function createIdGenerator(): () => number; +export declare function resetIds(): void; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/ID.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/ID.js new file mode 100644 index 0000000000000000000000000000000000000000..587fa9173697d6fa2125f5419fcd36daa77ecbbe --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/ID.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createIdGenerator = createIdGenerator; +exports.resetIds = resetIds; +const ID_CACHE = new Map(); +let NEXT_KEY = 0; +function createIdGenerator() { + const key = (NEXT_KEY += 1); + ID_CACHE.set(key, 0); + return () => { + const current = ID_CACHE.get(key) ?? 0; + const next = current + 1; + ID_CACHE.set(key, next); + return next; + }; +} +function resetIds() { + ID_CACHE.clear(); +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/ScopeManager.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/ScopeManager.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..438d6360dac3365d974e3d597c3edcdf1dcefcb2 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/ScopeManager.d.ts @@ -0,0 +1,77 @@ +import type { SourceType, TSESTree } from '@typescript-eslint/types'; +import type { Scope } from './scope'; +import type { Variable } from './variable'; +import { BlockScope, CatchScope, ClassScope, ConditionalTypeScope, ForScope, FunctionExpressionNameScope, FunctionScope, FunctionTypeScope, GlobalScope, MappedTypeScope, ModuleScope, SwitchScope, TSEnumScope, TSModuleScope, TypeScope, WithScope } from './scope'; +import { ClassFieldInitializerScope } from './scope/ClassFieldInitializerScope'; +import { ClassStaticBlockScope } from './scope/ClassStaticBlockScope'; +interface ScopeManagerOptions { + globalReturn?: boolean; + impliedStrict?: boolean; + sourceType?: SourceType; +} +/** + * @see https://eslint.org/docs/latest/developer-guide/scope-manager-interface#scopemanager-interface + */ +export declare class ScopeManager { + #private; + currentScope: Scope | null; + readonly declaredVariables: WeakMap; + /** + * The root scope + */ + globalScope: GlobalScope | null; + readonly nodeToScope: WeakMap; + /** + * All scopes + * @public + */ + readonly scopes: Scope[]; + constructor(options: ScopeManagerOptions); + isES6(): boolean; + isGlobalReturn(): boolean; + isImpliedStrict(): boolean; + isModule(): boolean; + isStrictModeSupported(): boolean; + get variables(): Variable[]; + /** + * Get the variables that a given AST node defines. The gotten variables' `def[].node`/`def[].parent` property is the node. + * If the node does not define any variable, this returns an empty array. + * @param node An AST node to get their variables. + */ + getDeclaredVariables(node: TSESTree.Node): Variable[]; + /** + * Get the scope of a given AST node. The gotten scope's `block` property is the node. + * This method never returns `function-expression-name` scope. If the node does not have their scope, this returns `null`. + * + * @param node An AST node to get their scope. + * @param inner If the node has multiple scopes, this returns the outermost scope normally. + * If `inner` is `true` then this returns the innermost scope. + */ + acquire(node: TSESTree.Node, inner?: boolean): Scope | null; + /** + * Adds dynamically created globals to the global scope and resolve their references. + * This method is called by ESLint. + * @param names Names of the globals to create + */ + addGlobals(names: string[]): void; + nestBlockScope(node: BlockScope['block']): BlockScope; + nestCatchScope(node: CatchScope['block']): CatchScope; + nestClassFieldInitializerScope(node: ClassFieldInitializerScope['block']): ClassFieldInitializerScope; + nestClassScope(node: ClassScope['block']): ClassScope; + nestClassStaticBlockScope(node: ClassStaticBlockScope['block']): ClassStaticBlockScope; + nestConditionalTypeScope(node: ConditionalTypeScope['block']): ConditionalTypeScope; + nestForScope(node: ForScope['block']): ForScope; + nestFunctionExpressionNameScope(node: FunctionExpressionNameScope['block']): FunctionExpressionNameScope; + nestFunctionScope(node: FunctionScope['block'], isMethodDefinition: boolean): FunctionScope; + nestFunctionTypeScope(node: FunctionTypeScope['block']): FunctionTypeScope; + nestGlobalScope(node: GlobalScope['block']): GlobalScope; + nestMappedTypeScope(node: MappedTypeScope['block']): MappedTypeScope; + nestModuleScope(node: ModuleScope['block']): ModuleScope; + nestSwitchScope(node: SwitchScope['block']): SwitchScope; + nestTSEnumScope(node: TSEnumScope['block']): TSEnumScope; + nestTSModuleScope(node: TSModuleScope['block']): TSModuleScope; + nestTypeScope(node: TypeScope['block']): TypeScope; + nestWithScope(node: WithScope['block']): WithScope; + protected nestScope(scope: T): T; +} +export {}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/ScopeManager.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/ScopeManager.js new file mode 100644 index 0000000000000000000000000000000000000000..0f06a7dfff8326d7ba7f16ee572cc97814629585 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/ScopeManager.js @@ -0,0 +1,189 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ScopeManager = void 0; +const assert_1 = require("./assert"); +const scope_1 = require("./scope"); +const ClassFieldInitializerScope_1 = require("./scope/ClassFieldInitializerScope"); +const ClassStaticBlockScope_1 = require("./scope/ClassStaticBlockScope"); +/** + * @see https://eslint.org/docs/latest/developer-guide/scope-manager-interface#scopemanager-interface + */ +class ScopeManager { + #options; + currentScope; + declaredVariables; + /** + * The root scope + */ + globalScope; + nodeToScope; + /** + * All scopes + * @public + */ + scopes; + constructor(options) { + this.scopes = []; + this.globalScope = null; + this.nodeToScope = new WeakMap(); + this.currentScope = null; + this.#options = options; + this.declaredVariables = new WeakMap(); + } + isES6() { + return true; + } + isGlobalReturn() { + return this.#options.globalReturn === true; + } + isImpliedStrict() { + return this.#options.impliedStrict === true; + } + isModule() { + return this.#options.sourceType === 'module'; + } + isStrictModeSupported() { + return true; + } + get variables() { + const variables = new Set(); + function recurse(scope) { + scope.variables.forEach(v => variables.add(v)); + scope.childScopes.forEach(recurse); + } + this.scopes.forEach(recurse); + return [...variables].sort((a, b) => a.$id - b.$id); + } + /** + * Get the variables that a given AST node defines. The gotten variables' `def[].node`/`def[].parent` property is the node. + * If the node does not define any variable, this returns an empty array. + * @param node An AST node to get their variables. + */ + getDeclaredVariables(node) { + return this.declaredVariables.get(node) ?? []; + } + /** + * Get the scope of a given AST node. The gotten scope's `block` property is the node. + * This method never returns `function-expression-name` scope. If the node does not have their scope, this returns `null`. + * + * @param node An AST node to get their scope. + * @param inner If the node has multiple scopes, this returns the outermost scope normally. + * If `inner` is `true` then this returns the innermost scope. + */ + acquire(node, inner = false) { + function predicate(testScope) { + if (testScope.type === scope_1.ScopeType.function && + testScope.functionExpressionScope) { + return false; + } + return true; + } + const scopes = this.nodeToScope.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; + } + } + return null; + } + return scopes.find(predicate) ?? null; + } + /** + * Adds dynamically created globals to the global scope and resolve their references. + * This method is called by ESLint. + * @param names Names of the globals to create + */ + addGlobals(names) { + this.globalScope?.addVariables(names); + } + nestBlockScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.BlockScope(this, this.currentScope, node)); + } + nestCatchScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.CatchScope(this, this.currentScope, node)); + } + nestClassFieldInitializerScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new ClassFieldInitializerScope_1.ClassFieldInitializerScope(this, this.currentScope, node)); + } + nestClassScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.ClassScope(this, this.currentScope, node)); + } + nestClassStaticBlockScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new ClassStaticBlockScope_1.ClassStaticBlockScope(this, this.currentScope, node)); + } + nestConditionalTypeScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.ConditionalTypeScope(this, this.currentScope, node)); + } + nestForScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.ForScope(this, this.currentScope, node)); + } + nestFunctionExpressionNameScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.FunctionExpressionNameScope(this, this.currentScope, node)); + } + nestFunctionScope(node, isMethodDefinition) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.FunctionScope(this, this.currentScope, node, isMethodDefinition)); + } + nestFunctionTypeScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.FunctionTypeScope(this, this.currentScope, node)); + } + nestGlobalScope(node) { + return this.nestScope(new scope_1.GlobalScope(this, node)); + } + nestMappedTypeScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.MappedTypeScope(this, this.currentScope, node)); + } + nestModuleScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.ModuleScope(this, this.currentScope, node)); + } + nestSwitchScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.SwitchScope(this, this.currentScope, node)); + } + nestTSEnumScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.TSEnumScope(this, this.currentScope, node)); + } + nestTSModuleScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.TSModuleScope(this, this.currentScope, node)); + } + nestTypeScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.TypeScope(this, this.currentScope, node)); + } + nestWithScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.WithScope(this, this.currentScope, node)); + } + nestScope(scope) { + if (scope instanceof scope_1.GlobalScope) { + (0, assert_1.assert)(this.currentScope == null); + this.globalScope = scope; + } + this.currentScope = scope; + return scope; + } +} +exports.ScopeManager = ScopeManager; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/analyze.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/analyze.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7313bafae92cdbdd8b11d88280349c1493d37f43 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/analyze.d.ts @@ -0,0 +1,53 @@ +import type { Lib, SourceType, TSESTree } from '@typescript-eslint/types'; +import type { ReferencerOptions } from './referencer'; +import { ScopeManager } from './ScopeManager'; +export interface AnalyzeOptions { + /** + * Known visitor keys. + */ + childVisitorKeys?: ReferencerOptions['childVisitorKeys']; + /** + * Whether the whole script is executed under node.js environment. + * When enabled, the scope manager adds a function scope immediately following the global scope. + * Defaults to `false`. + */ + globalReturn?: boolean; + /** + * Implied strict mode. + * Defaults to `false`. + */ + impliedStrict?: boolean; + /** + * The identifier that's used for JSX Element creation (after transpilation). + * This should not be a member expression - just the root identifier (i.e. use "React" instead of "React.createElement"). + * Defaults to `"React"`. + */ + jsxPragma?: string | null; + /** + * The identifier that's used for JSX fragment elements (after transpilation). + * If `null`, assumes transpilation will always use a member on `jsxFactory` (i.e. React.Fragment). + * This should not be a member expression - just the root identifier (i.e. use "h" instead of "h.Fragment"). + * Defaults to `null`. + */ + jsxFragmentName?: string | null; + /** + * The lib used by the project. + * This automatically defines a type variable for any types provided by the configured TS libs. + * Defaults to ['esnext']. + * + * https://www.typescriptlang.org/tsconfig#lib + */ + lib?: Lib[]; + /** + * The source type of the script. + */ + sourceType?: SourceType; + /** + * @deprecated This option never did what it was intended for and will be removed in a future major release. + */ + emitDecoratorMetadata?: boolean; +} +/** + * Takes an AST and returns the analyzed scopes. + */ +export declare function analyze(tree: TSESTree.Program, providedOptions?: AnalyzeOptions): ScopeManager; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/analyze.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/analyze.js new file mode 100644 index 0000000000000000000000000000000000000000..dfedd03c3c500621e959a472a3e9cb9b97ce9ad8 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/analyze.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.analyze = analyze; +const visitor_keys_1 = require("@typescript-eslint/visitor-keys"); +const referencer_1 = require("./referencer"); +const ScopeManager_1 = require("./ScopeManager"); +const DEFAULT_OPTIONS = { + childVisitorKeys: visitor_keys_1.visitorKeys, + emitDecoratorMetadata: false, + globalReturn: false, + impliedStrict: false, + jsxFragmentName: null, + jsxPragma: 'React', + lib: ['es2018'], + sourceType: 'script', +}; +/** + * Takes an AST and returns the analyzed scopes. + */ +function analyze(tree, providedOptions) { + const options = { + childVisitorKeys: providedOptions?.childVisitorKeys ?? DEFAULT_OPTIONS.childVisitorKeys, + emitDecoratorMetadata: false, + globalReturn: providedOptions?.globalReturn ?? DEFAULT_OPTIONS.globalReturn, + impliedStrict: providedOptions?.impliedStrict ?? DEFAULT_OPTIONS.impliedStrict, + jsxFragmentName: providedOptions?.jsxFragmentName ?? DEFAULT_OPTIONS.jsxFragmentName, + jsxPragma: + // eslint-disable-next-line @typescript-eslint/internal/eqeq-nullish + providedOptions?.jsxPragma === undefined + ? DEFAULT_OPTIONS.jsxPragma + : providedOptions.jsxPragma, + lib: providedOptions?.lib ?? ['esnext'], + sourceType: providedOptions?.sourceType ?? DEFAULT_OPTIONS.sourceType, + }; + // ensure the option is lower cased + options.lib = options.lib.map(l => l.toLowerCase()); + const scopeManager = new ScopeManager_1.ScopeManager(options); + const referencer = new referencer_1.Referencer(options, scopeManager); + referencer.visit(tree); + return scopeManager; +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/assert.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/assert.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..daee0d5f1a2b3e3773215b52ace54302bb4f6807 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/assert.d.ts @@ -0,0 +1 @@ +export declare function assert(value: unknown, message?: string): asserts value; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/assert.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/assert.js new file mode 100644 index 0000000000000000000000000000000000000000..24c3c196a6da99702d95659420fe11735c7581e6 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/assert.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.assert = assert; +// the base assert module doesn't use ts assertion syntax +function assert(value, message) { + if (value == null) { + throw new Error(message); + } +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/CatchClauseDefinition.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/CatchClauseDefinition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..10c9e9088b793e5720fe8f5157944e1c93683383 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/CatchClauseDefinition.d.ts @@ -0,0 +1,8 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class CatchClauseDefinition extends DefinitionBase { + readonly isTypeDefinition = false; + readonly isVariableDefinition = true; + constructor(name: TSESTree.Identifier, node: CatchClauseDefinition['node']); +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/CatchClauseDefinition.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/CatchClauseDefinition.js new file mode 100644 index 0000000000000000000000000000000000000000..a1816c5fbd93c53e049ad7ea544dcb06ea647962 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/CatchClauseDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CatchClauseDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class CatchClauseDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = false; + isVariableDefinition = true; + constructor(name, node) { + super(DefinitionType_1.DefinitionType.CatchClause, name, node, null); + } +} +exports.CatchClauseDefinition = CatchClauseDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ClassNameDefinition.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ClassNameDefinition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ca02c8192e20584a302d84f92fdcde13f74d51f6 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ClassNameDefinition.d.ts @@ -0,0 +1,8 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class ClassNameDefinition extends DefinitionBase { + readonly isTypeDefinition = true; + readonly isVariableDefinition = true; + constructor(name: TSESTree.Identifier, node: ClassNameDefinition['node']); +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ClassNameDefinition.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ClassNameDefinition.js new file mode 100644 index 0000000000000000000000000000000000000000..55e6cc5ef5c060350f50f70f1f095d922399f071 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ClassNameDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ClassNameDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class ClassNameDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = true; + isVariableDefinition = true; + constructor(name, node) { + super(DefinitionType_1.DefinitionType.ClassName, name, node, null); + } +} +exports.ClassNameDefinition = ClassNameDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/Definition.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/Definition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..95fe4a5571cd08c01f1fbda8449251e529673ad3 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/Definition.d.ts @@ -0,0 +1,12 @@ +import type { CatchClauseDefinition } from './CatchClauseDefinition'; +import type { ClassNameDefinition } from './ClassNameDefinition'; +import type { FunctionNameDefinition } from './FunctionNameDefinition'; +import type { ImplicitGlobalVariableDefinition } from './ImplicitGlobalVariableDefinition'; +import type { ImportBindingDefinition } from './ImportBindingDefinition'; +import type { ParameterDefinition } from './ParameterDefinition'; +import type { TSEnumMemberDefinition } from './TSEnumMemberDefinition'; +import type { TSEnumNameDefinition } from './TSEnumNameDefinition'; +import type { TSModuleNameDefinition } from './TSModuleNameDefinition'; +import type { TypeDefinition } from './TypeDefinition'; +import type { VariableDefinition } from './VariableDefinition'; +export type Definition = CatchClauseDefinition | ClassNameDefinition | FunctionNameDefinition | ImplicitGlobalVariableDefinition | ImportBindingDefinition | ParameterDefinition | TSEnumMemberDefinition | TSEnumNameDefinition | TSModuleNameDefinition | TypeDefinition | VariableDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/Definition.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/Definition.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/Definition.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionBase.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionBase.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cd5ebcb9ac2020c6fe762d7fc4475c01432401f1 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionBase.d.ts @@ -0,0 +1,33 @@ +import type { NodeWithParent, TSESTree } from '@typescript-eslint/types'; +import type { DefinitionType } from './DefinitionType'; +export declare abstract class DefinitionBase { + /** + * A unique ID for this instance - primarily used to help debugging and testing + */ + readonly $id: number; + readonly type: Type; + /** + * The `Identifier` node of this definition + * @public + */ + readonly name: Name; + /** + * The enclosing node of the name. + * @public + */ + readonly node: Node; + /** + * the enclosing statement node of the identifier. + * @public + */ + readonly parent: Parent; + constructor(type: Type, name: Name, node: Node, parent: Parent); + /** + * `true` if the variable is valid in a type context, false otherwise + */ + abstract readonly isTypeDefinition: boolean; + /** + * `true` if the variable is valid in a value context, false otherwise + */ + abstract readonly isVariableDefinition: boolean; +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionBase.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionBase.js new file mode 100644 index 0000000000000000000000000000000000000000..3327b11b9cb9b9c94afd23aa6d98cb8e41194e82 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionBase.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DefinitionBase = void 0; +const ID_1 = require("../ID"); +const generator = (0, ID_1.createIdGenerator)(); +class DefinitionBase { + /** + * A unique ID for this instance - primarily used to help debugging and testing + */ + $id = generator(); + type; + /** + * The `Identifier` node of this definition + * @public + */ + name; + /** + * The enclosing node of the name. + * @public + */ + node; + /** + * the enclosing statement node of the identifier. + * @public + */ + parent; + constructor(type, name, node, parent) { + this.type = type; + this.name = name; + this.node = node; + this.parent = parent; + } +} +exports.DefinitionBase = DefinitionBase; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionType.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionType.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a4321cd42886f1c5c21c7aa790565c2325a8673 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionType.d.ts @@ -0,0 +1,13 @@ +export declare enum DefinitionType { + CatchClause = "CatchClause", + ClassName = "ClassName", + FunctionName = "FunctionName", + ImplicitGlobalVariable = "ImplicitGlobalVariable", + ImportBinding = "ImportBinding", + Parameter = "Parameter", + TSEnumName = "TSEnumName", + TSEnumMember = "TSEnumMemberName", + TSModuleName = "TSModuleName", + Type = "Type", + Variable = "Variable" +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionType.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionType.js new file mode 100644 index 0000000000000000000000000000000000000000..1ac31940882acf860c49cd19a11ce4c04d5e107d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionType.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DefinitionType = void 0; +var DefinitionType; +(function (DefinitionType) { + DefinitionType["CatchClause"] = "CatchClause"; + DefinitionType["ClassName"] = "ClassName"; + DefinitionType["FunctionName"] = "FunctionName"; + DefinitionType["ImplicitGlobalVariable"] = "ImplicitGlobalVariable"; + DefinitionType["ImportBinding"] = "ImportBinding"; + DefinitionType["Parameter"] = "Parameter"; + DefinitionType["TSEnumName"] = "TSEnumName"; + DefinitionType["TSEnumMember"] = "TSEnumMemberName"; + DefinitionType["TSModuleName"] = "TSModuleName"; + DefinitionType["Type"] = "Type"; + DefinitionType["Variable"] = "Variable"; +})(DefinitionType || (exports.DefinitionType = DefinitionType = {})); diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/FunctionNameDefinition.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/FunctionNameDefinition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..200a7c44faab06c7f0c66f90c620f75a81e11fd7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/FunctionNameDefinition.d.ts @@ -0,0 +1,8 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class FunctionNameDefinition extends DefinitionBase { + readonly isTypeDefinition = false; + readonly isVariableDefinition = true; + constructor(name: TSESTree.Identifier, node: FunctionNameDefinition['node']); +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/FunctionNameDefinition.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/FunctionNameDefinition.js new file mode 100644 index 0000000000000000000000000000000000000000..ed7998d56d4fab68328850699e5d440bf3eb3194 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/FunctionNameDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FunctionNameDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class FunctionNameDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = false; + isVariableDefinition = true; + constructor(name, node) { + super(DefinitionType_1.DefinitionType.FunctionName, name, node, null); + } +} +exports.FunctionNameDefinition = FunctionNameDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ImplicitGlobalVariableDefinition.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ImplicitGlobalVariableDefinition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fddb5b42264ee20c6413303096f1aa7f5acb4d85 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ImplicitGlobalVariableDefinition.d.ts @@ -0,0 +1,8 @@ +import type { NodeWithParent, TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class ImplicitGlobalVariableDefinition extends DefinitionBase { + readonly isTypeDefinition = false; + readonly isVariableDefinition = true; + constructor(name: TSESTree.BindingName, node: ImplicitGlobalVariableDefinition['node']); +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ImplicitGlobalVariableDefinition.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ImplicitGlobalVariableDefinition.js new file mode 100644 index 0000000000000000000000000000000000000000..f48182dbe7f8bc68f005a1106075b0a7f355657d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ImplicitGlobalVariableDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ImplicitGlobalVariableDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class ImplicitGlobalVariableDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = false; + isVariableDefinition = true; + constructor(name, node) { + super(DefinitionType_1.DefinitionType.ImplicitGlobalVariable, name, node, null); + } +} +exports.ImplicitGlobalVariableDefinition = ImplicitGlobalVariableDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ImportBindingDefinition.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ImportBindingDefinition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bdd228bc2aaba21508d8a709b3443aa788cd5fdd --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ImportBindingDefinition.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class ImportBindingDefinition extends DefinitionBase { + readonly isTypeDefinition = true; + readonly isVariableDefinition = true; + constructor(name: TSESTree.Identifier, node: TSESTree.TSImportEqualsDeclaration, decl: TSESTree.TSImportEqualsDeclaration); + constructor(name: TSESTree.Identifier, node: Exclude, decl: TSESTree.ImportDeclaration); +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ImportBindingDefinition.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ImportBindingDefinition.js new file mode 100644 index 0000000000000000000000000000000000000000..e5407f3120d82b4e84b84739730361ab504db884 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ImportBindingDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ImportBindingDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class ImportBindingDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = true; + isVariableDefinition = true; + constructor(name, node, decl) { + super(DefinitionType_1.DefinitionType.ImportBinding, name, node, decl); + } +} +exports.ImportBindingDefinition = ImportBindingDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ParameterDefinition.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ParameterDefinition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..721e03bc21486f88a6da19d202823896fc84f6ce --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ParameterDefinition.d.ts @@ -0,0 +1,12 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class ParameterDefinition extends DefinitionBase { + /** + * Whether the parameter definition is a part of a rest parameter. + */ + readonly isTypeDefinition = false; + readonly isVariableDefinition = true; + readonly rest: boolean; + constructor(name: TSESTree.BindingName, node: ParameterDefinition['node'], rest: boolean); +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ParameterDefinition.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ParameterDefinition.js new file mode 100644 index 0000000000000000000000000000000000000000..81a48951cdeaa1c0f05cd3883e4bd2b99807fea7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/ParameterDefinition.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ParameterDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class ParameterDefinition extends DefinitionBase_1.DefinitionBase { + /** + * Whether the parameter definition is a part of a rest parameter. + */ + isTypeDefinition = false; + isVariableDefinition = true; + rest; + constructor(name, node, rest) { + super(DefinitionType_1.DefinitionType.Parameter, name, node, null); + this.rest = rest; + } +} +exports.ParameterDefinition = ParameterDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumMemberDefinition.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumMemberDefinition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eeb30614de1bd7155ef22609f4e3bf3eaf741839 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumMemberDefinition.d.ts @@ -0,0 +1,8 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class TSEnumMemberDefinition extends DefinitionBase { + readonly isTypeDefinition = true; + readonly isVariableDefinition = true; + constructor(name: TSESTree.Identifier | TSESTree.StringLiteral, node: TSEnumMemberDefinition['node']); +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumMemberDefinition.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumMemberDefinition.js new file mode 100644 index 0000000000000000000000000000000000000000..c6da19044b8009d609f3be5422a3f47cc7879dcd --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumMemberDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TSEnumMemberDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class TSEnumMemberDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = true; + isVariableDefinition = true; + constructor(name, node) { + super(DefinitionType_1.DefinitionType.TSEnumMember, name, node, null); + } +} +exports.TSEnumMemberDefinition = TSEnumMemberDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumNameDefinition.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumNameDefinition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ffd577e95a03293eb07164098f58ff70bd36e05 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumNameDefinition.d.ts @@ -0,0 +1,8 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class TSEnumNameDefinition extends DefinitionBase { + readonly isTypeDefinition = true; + readonly isVariableDefinition = true; + constructor(name: TSESTree.Identifier, node: TSEnumNameDefinition['node']); +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumNameDefinition.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumNameDefinition.js new file mode 100644 index 0000000000000000000000000000000000000000..d5453d2647ec20f0cf6588fb63116a5f64a1186d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumNameDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TSEnumNameDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class TSEnumNameDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = true; + isVariableDefinition = true; + constructor(name, node) { + super(DefinitionType_1.DefinitionType.TSEnumName, name, node, null); + } +} +exports.TSEnumNameDefinition = TSEnumNameDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TSModuleNameDefinition.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TSModuleNameDefinition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5088b2bf9d4b1fc1a5e6197750daafc3f6fb961e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TSModuleNameDefinition.d.ts @@ -0,0 +1,8 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class TSModuleNameDefinition extends DefinitionBase { + readonly isTypeDefinition = true; + readonly isVariableDefinition = true; + constructor(name: TSESTree.Identifier, node: TSModuleNameDefinition['node']); +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TSModuleNameDefinition.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TSModuleNameDefinition.js new file mode 100644 index 0000000000000000000000000000000000000000..93fb8470537f3c4cf6061ba4c664f7845e231907 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TSModuleNameDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TSModuleNameDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class TSModuleNameDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = true; + isVariableDefinition = true; + constructor(name, node) { + super(DefinitionType_1.DefinitionType.TSModuleName, name, node, null); + } +} +exports.TSModuleNameDefinition = TSModuleNameDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TypeDefinition.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TypeDefinition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4740a9ce255cdabfa44a1420e4385a085a024aa9 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TypeDefinition.d.ts @@ -0,0 +1,8 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class TypeDefinition extends DefinitionBase { + readonly isTypeDefinition = true; + readonly isVariableDefinition = false; + constructor(name: TSESTree.Identifier, node: TypeDefinition['node']); +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TypeDefinition.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TypeDefinition.js new file mode 100644 index 0000000000000000000000000000000000000000..2966fde970f66d52f41dc5d9f2a510c76a7373f0 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/TypeDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TypeDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class TypeDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = true; + isVariableDefinition = false; + constructor(name, node) { + super(DefinitionType_1.DefinitionType.Type, name, node, null); + } +} +exports.TypeDefinition = TypeDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/VariableDefinition.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/VariableDefinition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5b75b2cd3a9c493aa555810ef8477115e6ad9f7c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/VariableDefinition.d.ts @@ -0,0 +1,8 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class VariableDefinition extends DefinitionBase { + readonly isTypeDefinition = false; + readonly isVariableDefinition = true; + constructor(name: TSESTree.Identifier, node: VariableDefinition['node'], decl: TSESTree.VariableDeclaration); +} diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/VariableDefinition.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/VariableDefinition.js new file mode 100644 index 0000000000000000000000000000000000000000..fc30f8385bad6c44bbbd62bbe71dbcc89b5e701d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/VariableDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.VariableDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class VariableDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = false; + isVariableDefinition = true; + constructor(name, node, decl) { + super(DefinitionType_1.DefinitionType.Variable, name, node, decl); + } +} +exports.VariableDefinition = VariableDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/index.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9bd1f0123370fd9d0f2c89ffb5f7f194e81b2870 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/index.d.ts @@ -0,0 +1,13 @@ +export * from './CatchClauseDefinition'; +export * from './ClassNameDefinition'; +export * from './Definition'; +export * from './DefinitionType'; +export * from './FunctionNameDefinition'; +export * from './ImplicitGlobalVariableDefinition'; +export * from './ImportBindingDefinition'; +export * from './ParameterDefinition'; +export * from './TSEnumMemberDefinition'; +export * from './TSEnumNameDefinition'; +export * from './TSModuleNameDefinition'; +export * from './TypeDefinition'; +export * from './VariableDefinition'; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/index.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/index.js new file mode 100644 index 0000000000000000000000000000000000000000..67fad66bf217eea248cecb40de0db1c529fc9206 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/definition/index.js @@ -0,0 +1,29 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./CatchClauseDefinition"), exports); +__exportStar(require("./ClassNameDefinition"), exports); +__exportStar(require("./Definition"), exports); +__exportStar(require("./DefinitionType"), exports); +__exportStar(require("./FunctionNameDefinition"), exports); +__exportStar(require("./ImplicitGlobalVariableDefinition"), exports); +__exportStar(require("./ImportBindingDefinition"), exports); +__exportStar(require("./ParameterDefinition"), exports); +__exportStar(require("./TSEnumMemberDefinition"), exports); +__exportStar(require("./TSEnumNameDefinition"), exports); +__exportStar(require("./TSModuleNameDefinition"), exports); +__exportStar(require("./TypeDefinition"), exports); +__exportStar(require("./VariableDefinition"), exports); diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/index.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e1feec0dca6e87c894909e84fd9e522bbed8780c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/index.d.ts @@ -0,0 +1,8 @@ +export { analyze, type AnalyzeOptions } from './analyze'; +export * from './definition'; +export { PatternVisitor, type PatternVisitorCallback, type PatternVisitorOptions, } from './referencer/PatternVisitor'; +export { Reference } from './referencer/Reference'; +export { Visitor } from './referencer/Visitor'; +export * from './scope'; +export { ScopeManager } from './ScopeManager'; +export * from './variable'; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/index.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3ecc7a33765bebb70180e3a16fd514c89f694a9c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/index.js @@ -0,0 +1,30 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ScopeManager = exports.Visitor = exports.Reference = exports.PatternVisitor = exports.analyze = void 0; +var analyze_1 = require("./analyze"); +Object.defineProperty(exports, "analyze", { enumerable: true, get: function () { return analyze_1.analyze; } }); +__exportStar(require("./definition"), exports); +var PatternVisitor_1 = require("./referencer/PatternVisitor"); +Object.defineProperty(exports, "PatternVisitor", { enumerable: true, get: function () { return PatternVisitor_1.PatternVisitor; } }); +var Reference_1 = require("./referencer/Reference"); +Object.defineProperty(exports, "Reference", { enumerable: true, get: function () { return Reference_1.Reference; } }); +var Visitor_1 = require("./referencer/Visitor"); +Object.defineProperty(exports, "Visitor", { enumerable: true, get: function () { return Visitor_1.Visitor; } }); +__exportStar(require("./scope"), exports); +var ScopeManager_1 = require("./ScopeManager"); +Object.defineProperty(exports, "ScopeManager", { enumerable: true, get: function () { return ScopeManager_1.ScopeManager; } }); +__exportStar(require("./variable"), exports); diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/base-config.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/base-config.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..de5f223e7913679063fe18e9cae8a1623d8439ec --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/base-config.d.ts @@ -0,0 +1,15 @@ +export declare const TYPE: Readonly<{ + eslintImplicitGlobalSetting: "readonly"; + isTypeVariable: true; + isValueVariable: false; +}>; +export declare const VALUE: Readonly<{ + eslintImplicitGlobalSetting: "readonly"; + isTypeVariable: false; + isValueVariable: true; +}>; +export declare const TYPE_VALUE: Readonly<{ + eslintImplicitGlobalSetting: "readonly"; + isTypeVariable: true; + isValueVariable: true; +}>; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/base-config.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/base-config.js new file mode 100644 index 0000000000000000000000000000000000000000..52febf4e0e6b79044fe72780b1cc9f3c33801da5 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/base-config.js @@ -0,0 +1,22 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TYPE_VALUE = exports.VALUE = exports.TYPE = void 0; +exports.TYPE = Object.freeze({ + eslintImplicitGlobalSetting: 'readonly', + isTypeVariable: true, + isValueVariable: false, +}); +exports.VALUE = Object.freeze({ + eslintImplicitGlobalSetting: 'readonly', + isTypeVariable: false, + isValueVariable: true, +}); +exports.TYPE_VALUE = Object.freeze({ + eslintImplicitGlobalSetting: 'readonly', + isTypeVariable: true, + isValueVariable: true, +}); diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e8fd08723ac5612313a8df7046fb484f70672838 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const decorators: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.js new file mode 100644 index 0000000000000000000000000000000000000000..4b8c452bf0e944dbe639f1759646b3dd8ade2461 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.js @@ -0,0 +1,25 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decorators = void 0; +const base_config_1 = require("./base-config"); +exports.decorators = { + libs: [], + variables: [ + ['ClassMemberDecoratorContext', base_config_1.TYPE], + ['DecoratorContext', base_config_1.TYPE], + ['DecoratorMetadataObject', base_config_1.TYPE], + ['DecoratorMetadata', base_config_1.TYPE], + ['ClassDecoratorContext', base_config_1.TYPE], + ['ClassMethodDecoratorContext', base_config_1.TYPE], + ['ClassGetterDecoratorContext', base_config_1.TYPE], + ['ClassSetterDecoratorContext', base_config_1.TYPE], + ['ClassAccessorDecoratorContext', base_config_1.TYPE], + ['ClassAccessorDecoratorTarget', base_config_1.TYPE], + ['ClassAccessorDecoratorResult', base_config_1.TYPE], + ['ClassFieldDecoratorContext', base_config_1.TYPE], + ], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.legacy.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.legacy.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e2b40a2d70d6df5510ab1514fe3da68bc6b115fa --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.legacy.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const decorators_legacy: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.legacy.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.legacy.js new file mode 100644 index 0000000000000000000000000000000000000000..c6c196d61b0123383bee4567dd9ded362b181bba --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.legacy.js @@ -0,0 +1,17 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decorators_legacy = void 0; +const base_config_1 = require("./base-config"); +exports.decorators_legacy = { + libs: [], + variables: [ + ['ClassDecorator', base_config_1.TYPE], + ['PropertyDecorator', base_config_1.TYPE], + ['MethodDecorator', base_config_1.TYPE], + ['ParameterDecorator', base_config_1.TYPE], + ], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.asynciterable.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.asynciterable.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5d4d6d20a62a2df2f86ccbb3cb5c38c97d84a4e6 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.asynciterable.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const dom_asynciterable: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.asynciterable.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.asynciterable.js new file mode 100644 index 0000000000000000000000000000000000000000..5ea1b19634ee50e018f96eb009431a28f065012f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.asynciterable.js @@ -0,0 +1,11 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.dom_asynciterable = void 0; +exports.dom_asynciterable = { + libs: [], + variables: [], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..be8282b2e0091363fa870939bbc49aeaef7a1cdd --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const dom: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.iterable.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.iterable.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..681e7a198a08350408fce134b687fab36d385d97 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.iterable.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const dom_iterable: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.iterable.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.iterable.js new file mode 100644 index 0000000000000000000000000000000000000000..39bfe68bb6fca7674b94ae82f85b424d6e78fc29 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.iterable.js @@ -0,0 +1,11 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.dom_iterable = void 0; +exports.dom_iterable = { + libs: [], + variables: [], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.js new file mode 100644 index 0000000000000000000000000000000000000000..d979279dd681fefe17cfbbf7e271c6726c106b02 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.js @@ -0,0 +1,1812 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.dom = void 0; +const base_config_1 = require("./base-config"); +const es2015_1 = require("./es2015"); +const es2018_asynciterable_1 = require("./es2018.asynciterable"); +exports.dom = { + libs: [es2015_1.es2015, es2018_asynciterable_1.es2018_asynciterable], + variables: [ + ['AacEncoderConfig', base_config_1.TYPE], + ['AddEventListenerOptions', base_config_1.TYPE], + ['AddressErrors', base_config_1.TYPE], + ['AesCbcParams', base_config_1.TYPE], + ['AesCtrParams', base_config_1.TYPE], + ['AesDerivedKeyParams', base_config_1.TYPE], + ['AesGcmParams', base_config_1.TYPE], + ['AesKeyAlgorithm', base_config_1.TYPE], + ['AesKeyGenParams', base_config_1.TYPE], + ['Algorithm', base_config_1.TYPE], + ['AllAcceptedCredentialsOptions', base_config_1.TYPE], + ['AnalyserOptions', base_config_1.TYPE], + ['AnimationEventInit', base_config_1.TYPE], + ['AnimationPlaybackEventInit', base_config_1.TYPE], + ['AssignedNodesOptions', base_config_1.TYPE], + ['AudioBufferOptions', base_config_1.TYPE], + ['AudioBufferSourceOptions', base_config_1.TYPE], + ['AudioConfiguration', base_config_1.TYPE], + ['AudioContextOptions', base_config_1.TYPE], + ['AudioDataCopyToOptions', base_config_1.TYPE], + ['AudioDataInit', base_config_1.TYPE], + ['AudioDecoderConfig', base_config_1.TYPE], + ['AudioDecoderInit', base_config_1.TYPE], + ['AudioDecoderSupport', base_config_1.TYPE], + ['AudioEncoderConfig', base_config_1.TYPE], + ['AudioEncoderInit', base_config_1.TYPE], + ['AudioEncoderSupport', base_config_1.TYPE], + ['AudioNodeOptions', base_config_1.TYPE], + ['AudioProcessingEventInit', base_config_1.TYPE], + ['AudioTimestamp', base_config_1.TYPE], + ['AudioWorkletNodeOptions', base_config_1.TYPE], + ['AuthenticationExtensionsClientInputs', base_config_1.TYPE], + ['AuthenticationExtensionsClientInputsJSON', base_config_1.TYPE], + ['AuthenticationExtensionsClientOutputs', base_config_1.TYPE], + ['AuthenticationExtensionsClientOutputsJSON', base_config_1.TYPE], + ['AuthenticationExtensionsLargeBlobInputs', base_config_1.TYPE], + ['AuthenticationExtensionsLargeBlobInputsJSON', base_config_1.TYPE], + ['AuthenticationExtensionsLargeBlobOutputs', base_config_1.TYPE], + ['AuthenticationExtensionsLargeBlobOutputsJSON', base_config_1.TYPE], + ['AuthenticationExtensionsPRFInputs', base_config_1.TYPE], + ['AuthenticationExtensionsPRFInputsJSON', base_config_1.TYPE], + ['AuthenticationExtensionsPRFOutputs', base_config_1.TYPE], + ['AuthenticationExtensionsPRFOutputsJSON', base_config_1.TYPE], + ['AuthenticationExtensionsPRFValues', base_config_1.TYPE], + ['AuthenticationExtensionsPRFValuesJSON', base_config_1.TYPE], + ['AuthenticationResponseJSON', base_config_1.TYPE], + ['AuthenticatorAssertionResponseJSON', base_config_1.TYPE], + ['AuthenticatorAttestationResponseJSON', base_config_1.TYPE], + ['AuthenticatorSelectionCriteria', base_config_1.TYPE], + ['AvcEncoderConfig', base_config_1.TYPE], + ['BiquadFilterOptions', base_config_1.TYPE], + ['BlobEventInit', base_config_1.TYPE], + ['BlobPropertyBag', base_config_1.TYPE], + ['CSSMatrixComponentOptions', base_config_1.TYPE], + ['CSSNumericType', base_config_1.TYPE], + ['CSSStyleSheetInit', base_config_1.TYPE], + ['CacheQueryOptions', base_config_1.TYPE], + ['CanvasRenderingContext2DSettings', base_config_1.TYPE], + ['CaretPositionFromPointOptions', base_config_1.TYPE], + ['ChannelMergerOptions', base_config_1.TYPE], + ['ChannelSplitterOptions', base_config_1.TYPE], + ['CheckVisibilityOptions', base_config_1.TYPE], + ['ClientQueryOptions', base_config_1.TYPE], + ['ClipboardEventInit', base_config_1.TYPE], + ['ClipboardItemOptions', base_config_1.TYPE], + ['CloseEventInit', base_config_1.TYPE], + ['CommandEventInit', base_config_1.TYPE], + ['CompositionEventInit', base_config_1.TYPE], + ['ComputedEffectTiming', base_config_1.TYPE], + ['ComputedKeyframe', base_config_1.TYPE], + ['ConstantSourceOptions', base_config_1.TYPE], + ['ConstrainBooleanOrDOMStringParameters', base_config_1.TYPE], + ['ConstrainBooleanParameters', base_config_1.TYPE], + ['ConstrainDOMStringParameters', base_config_1.TYPE], + ['ConstrainDoubleRange', base_config_1.TYPE], + ['ConstrainULongRange', base_config_1.TYPE], + ['ContentVisibilityAutoStateChangeEventInit', base_config_1.TYPE], + ['ConvolverOptions', base_config_1.TYPE], + ['CookieChangeEventInit', base_config_1.TYPE], + ['CookieInit', base_config_1.TYPE], + ['CookieListItem', base_config_1.TYPE], + ['CookieStoreDeleteOptions', base_config_1.TYPE], + ['CookieStoreGetOptions', base_config_1.TYPE], + ['CredentialCreationOptions', base_config_1.TYPE], + ['CredentialPropertiesOutput', base_config_1.TYPE], + ['CredentialRequestOptions', base_config_1.TYPE], + ['CryptoKeyPair', base_config_1.TYPE], + ['CurrentUserDetailsOptions', base_config_1.TYPE], + ['CustomEventInit', base_config_1.TYPE], + ['DOMMatrix2DInit', base_config_1.TYPE], + ['DOMMatrixInit', base_config_1.TYPE], + ['DOMPointInit', base_config_1.TYPE], + ['DOMQuadInit', base_config_1.TYPE], + ['DOMRectInit', base_config_1.TYPE], + ['DelayOptions', base_config_1.TYPE], + ['DeviceMotionEventAccelerationInit', base_config_1.TYPE], + ['DeviceMotionEventInit', base_config_1.TYPE], + ['DeviceMotionEventRotationRateInit', base_config_1.TYPE], + ['DeviceOrientationEventInit', base_config_1.TYPE], + ['DisplayMediaStreamOptions', base_config_1.TYPE], + ['DocumentTimelineOptions', base_config_1.TYPE], + ['DoubleRange', base_config_1.TYPE], + ['DragEventInit', base_config_1.TYPE], + ['DynamicsCompressorOptions', base_config_1.TYPE], + ['EcKeyAlgorithm', base_config_1.TYPE], + ['EcKeyGenParams', base_config_1.TYPE], + ['EcKeyImportParams', base_config_1.TYPE], + ['EcdhKeyDeriveParams', base_config_1.TYPE], + ['EcdsaParams', base_config_1.TYPE], + ['EffectTiming', base_config_1.TYPE], + ['ElementCreationOptions', base_config_1.TYPE], + ['ElementDefinitionOptions', base_config_1.TYPE], + ['EncodedAudioChunkInit', base_config_1.TYPE], + ['EncodedAudioChunkMetadata', base_config_1.TYPE], + ['EncodedVideoChunkInit', base_config_1.TYPE], + ['EncodedVideoChunkMetadata', base_config_1.TYPE], + ['ErrorEventInit', base_config_1.TYPE], + ['EventInit', base_config_1.TYPE], + ['EventListenerOptions', base_config_1.TYPE], + ['EventModifierInit', base_config_1.TYPE], + ['EventSourceInit', base_config_1.TYPE], + ['FilePropertyBag', base_config_1.TYPE], + ['FileSystemCreateWritableOptions', base_config_1.TYPE], + ['FileSystemFlags', base_config_1.TYPE], + ['FileSystemGetDirectoryOptions', base_config_1.TYPE], + ['FileSystemGetFileOptions', base_config_1.TYPE], + ['FileSystemRemoveOptions', base_config_1.TYPE], + ['FocusEventInit', base_config_1.TYPE], + ['FocusOptions', base_config_1.TYPE], + ['FontFaceDescriptors', base_config_1.TYPE], + ['FontFaceSetLoadEventInit', base_config_1.TYPE], + ['FormDataEventInit', base_config_1.TYPE], + ['FullscreenOptions', base_config_1.TYPE], + ['GPUBindGroupDescriptor', base_config_1.TYPE], + ['GPUBindGroupEntry', base_config_1.TYPE], + ['GPUBindGroupLayoutDescriptor', base_config_1.TYPE], + ['GPUBindGroupLayoutEntry', base_config_1.TYPE], + ['GPUBlendComponent', base_config_1.TYPE], + ['GPUBlendState', base_config_1.TYPE], + ['GPUBufferBinding', base_config_1.TYPE], + ['GPUBufferBindingLayout', base_config_1.TYPE], + ['GPUBufferDescriptor', base_config_1.TYPE], + ['GPUCanvasConfiguration', base_config_1.TYPE], + ['GPUCanvasToneMapping', base_config_1.TYPE], + ['GPUColorDict', base_config_1.TYPE], + ['GPUColorTargetState', base_config_1.TYPE], + ['GPUCommandBufferDescriptor', base_config_1.TYPE], + ['GPUCommandEncoderDescriptor', base_config_1.TYPE], + ['GPUComputePassDescriptor', base_config_1.TYPE], + ['GPUComputePassTimestampWrites', base_config_1.TYPE], + ['GPUComputePipelineDescriptor', base_config_1.TYPE], + ['GPUCopyExternalImageDestInfo', base_config_1.TYPE], + ['GPUCopyExternalImageSourceInfo', base_config_1.TYPE], + ['GPUDepthStencilState', base_config_1.TYPE], + ['GPUDeviceDescriptor', base_config_1.TYPE], + ['GPUExtent3DDict', base_config_1.TYPE], + ['GPUExternalTextureBindingLayout', base_config_1.TYPE], + ['GPUExternalTextureDescriptor', base_config_1.TYPE], + ['GPUFragmentState', base_config_1.TYPE], + ['GPUMultisampleState', base_config_1.TYPE], + ['GPUObjectDescriptorBase', base_config_1.TYPE], + ['GPUOrigin2DDict', base_config_1.TYPE], + ['GPUOrigin3DDict', base_config_1.TYPE], + ['GPUPipelineDescriptorBase', base_config_1.TYPE], + ['GPUPipelineErrorInit', base_config_1.TYPE], + ['GPUPipelineLayoutDescriptor', base_config_1.TYPE], + ['GPUPrimitiveState', base_config_1.TYPE], + ['GPUProgrammableStage', base_config_1.TYPE], + ['GPUQuerySetDescriptor', base_config_1.TYPE], + ['GPUQueueDescriptor', base_config_1.TYPE], + ['GPURenderBundleDescriptor', base_config_1.TYPE], + ['GPURenderBundleEncoderDescriptor', base_config_1.TYPE], + ['GPURenderPassColorAttachment', base_config_1.TYPE], + ['GPURenderPassDepthStencilAttachment', base_config_1.TYPE], + ['GPURenderPassDescriptor', base_config_1.TYPE], + ['GPURenderPassLayout', base_config_1.TYPE], + ['GPURenderPassTimestampWrites', base_config_1.TYPE], + ['GPURenderPipelineDescriptor', base_config_1.TYPE], + ['GPURequestAdapterOptions', base_config_1.TYPE], + ['GPUSamplerBindingLayout', base_config_1.TYPE], + ['GPUSamplerDescriptor', base_config_1.TYPE], + ['GPUShaderModuleDescriptor', base_config_1.TYPE], + ['GPUStencilFaceState', base_config_1.TYPE], + ['GPUStorageTextureBindingLayout', base_config_1.TYPE], + ['GPUTexelCopyBufferInfo', base_config_1.TYPE], + ['GPUTexelCopyBufferLayout', base_config_1.TYPE], + ['GPUTexelCopyTextureInfo', base_config_1.TYPE], + ['GPUTextureBindingLayout', base_config_1.TYPE], + ['GPUTextureDescriptor', base_config_1.TYPE], + ['GPUTextureViewDescriptor', base_config_1.TYPE], + ['GPUUncapturedErrorEventInit', base_config_1.TYPE], + ['GPUVertexAttribute', base_config_1.TYPE], + ['GPUVertexBufferLayout', base_config_1.TYPE], + ['GPUVertexState', base_config_1.TYPE], + ['GainOptions', base_config_1.TYPE], + ['GamepadEffectParameters', base_config_1.TYPE], + ['GamepadEventInit', base_config_1.TYPE], + ['GetAnimationsOptions', base_config_1.TYPE], + ['GetComposedRangesOptions', base_config_1.TYPE], + ['GetHTMLOptions', base_config_1.TYPE], + ['GetNotificationOptions', base_config_1.TYPE], + ['GetRootNodeOptions', base_config_1.TYPE], + ['HashChangeEventInit', base_config_1.TYPE], + ['HkdfParams', base_config_1.TYPE], + ['HmacImportParams', base_config_1.TYPE], + ['HmacKeyAlgorithm', base_config_1.TYPE], + ['HmacKeyGenParams', base_config_1.TYPE], + ['IDBDatabaseInfo', base_config_1.TYPE], + ['IDBIndexParameters', base_config_1.TYPE], + ['IDBObjectStoreParameters', base_config_1.TYPE], + ['IDBTransactionOptions', base_config_1.TYPE], + ['IDBVersionChangeEventInit', base_config_1.TYPE], + ['IIRFilterOptions', base_config_1.TYPE], + ['IdleRequestOptions', base_config_1.TYPE], + ['ImageBitmapOptions', base_config_1.TYPE], + ['ImageBitmapRenderingContextSettings', base_config_1.TYPE], + ['ImageDataSettings', base_config_1.TYPE], + ['ImageDecodeOptions', base_config_1.TYPE], + ['ImageDecodeResult', base_config_1.TYPE], + ['ImageDecoderInit', base_config_1.TYPE], + ['ImageEncodeOptions', base_config_1.TYPE], + ['ImportNodeOptions', base_config_1.TYPE], + ['InputEventInit', base_config_1.TYPE], + ['IntersectionObserverInit', base_config_1.TYPE], + ['JsonWebKey', base_config_1.TYPE], + ['KeyAlgorithm', base_config_1.TYPE], + ['KeySystemTrackConfiguration', base_config_1.TYPE], + ['KeyboardEventInit', base_config_1.TYPE], + ['Keyframe', base_config_1.TYPE], + ['KeyframeAnimationOptions', base_config_1.TYPE], + ['KeyframeEffectOptions', base_config_1.TYPE], + ['LockInfo', base_config_1.TYPE], + ['LockManagerSnapshot', base_config_1.TYPE], + ['LockOptions', base_config_1.TYPE], + ['MIDIConnectionEventInit', base_config_1.TYPE], + ['MIDIMessageEventInit', base_config_1.TYPE], + ['MIDIOptions', base_config_1.TYPE], + ['MediaCapabilitiesDecodingInfo', base_config_1.TYPE], + ['MediaCapabilitiesEncodingInfo', base_config_1.TYPE], + ['MediaCapabilitiesInfo', base_config_1.TYPE], + ['MediaCapabilitiesKeySystemConfiguration', base_config_1.TYPE], + ['MediaConfiguration', base_config_1.TYPE], + ['MediaDecodingConfiguration', base_config_1.TYPE], + ['MediaElementAudioSourceOptions', base_config_1.TYPE], + ['MediaEncodingConfiguration', base_config_1.TYPE], + ['MediaEncryptedEventInit', base_config_1.TYPE], + ['MediaImage', base_config_1.TYPE], + ['MediaKeyMessageEventInit', base_config_1.TYPE], + ['MediaKeySystemConfiguration', base_config_1.TYPE], + ['MediaKeySystemMediaCapability', base_config_1.TYPE], + ['MediaKeysPolicy', base_config_1.TYPE], + ['MediaMetadataInit', base_config_1.TYPE], + ['MediaPositionState', base_config_1.TYPE], + ['MediaQueryListEventInit', base_config_1.TYPE], + ['MediaRecorderOptions', base_config_1.TYPE], + ['MediaSessionActionDetails', base_config_1.TYPE], + ['MediaSettingsRange', base_config_1.TYPE], + ['MediaStreamAudioSourceOptions', base_config_1.TYPE], + ['MediaStreamConstraints', base_config_1.TYPE], + ['MediaStreamTrackEventInit', base_config_1.TYPE], + ['MediaTrackCapabilities', base_config_1.TYPE], + ['MediaTrackConstraintSet', base_config_1.TYPE], + ['MediaTrackConstraints', base_config_1.TYPE], + ['MediaTrackSettings', base_config_1.TYPE], + ['MediaTrackSupportedConstraints', base_config_1.TYPE], + ['MessageEventInit', base_config_1.TYPE], + ['MouseEventInit', base_config_1.TYPE], + ['MultiCacheQueryOptions', base_config_1.TYPE], + ['MutationObserverInit', base_config_1.TYPE], + ['NavigateEventInit', base_config_1.TYPE], + ['NavigationCurrentEntryChangeEventInit', base_config_1.TYPE], + ['NavigationInterceptOptions', base_config_1.TYPE], + ['NavigationNavigateOptions', base_config_1.TYPE], + ['NavigationOptions', base_config_1.TYPE], + ['NavigationPreloadState', base_config_1.TYPE], + ['NavigationReloadOptions', base_config_1.TYPE], + ['NavigationResult', base_config_1.TYPE], + ['NavigationUpdateCurrentEntryOptions', base_config_1.TYPE], + ['NotificationOptions', base_config_1.TYPE], + ['OfflineAudioCompletionEventInit', base_config_1.TYPE], + ['OfflineAudioContextOptions', base_config_1.TYPE], + ['OptionalEffectTiming', base_config_1.TYPE], + ['OpusEncoderConfig', base_config_1.TYPE], + ['OscillatorOptions', base_config_1.TYPE], + ['PageRevealEventInit', base_config_1.TYPE], + ['PageSwapEventInit', base_config_1.TYPE], + ['PageTransitionEventInit', base_config_1.TYPE], + ['PannerOptions', base_config_1.TYPE], + ['PayerErrors', base_config_1.TYPE], + ['PaymentCurrencyAmount', base_config_1.TYPE], + ['PaymentDetailsBase', base_config_1.TYPE], + ['PaymentDetailsInit', base_config_1.TYPE], + ['PaymentDetailsModifier', base_config_1.TYPE], + ['PaymentDetailsUpdate', base_config_1.TYPE], + ['PaymentItem', base_config_1.TYPE], + ['PaymentMethodChangeEventInit', base_config_1.TYPE], + ['PaymentMethodData', base_config_1.TYPE], + ['PaymentOptions', base_config_1.TYPE], + ['PaymentRequestUpdateEventInit', base_config_1.TYPE], + ['PaymentShippingOption', base_config_1.TYPE], + ['PaymentValidationErrors', base_config_1.TYPE], + ['Pbkdf2Params', base_config_1.TYPE], + ['PerformanceMarkOptions', base_config_1.TYPE], + ['PerformanceMeasureOptions', base_config_1.TYPE], + ['PerformanceObserverInit', base_config_1.TYPE], + ['PeriodicWaveConstraints', base_config_1.TYPE], + ['PeriodicWaveOptions', base_config_1.TYPE], + ['PermissionDescriptor', base_config_1.TYPE], + ['PhotoCapabilities', base_config_1.TYPE], + ['PhotoSettings', base_config_1.TYPE], + ['PictureInPictureEventInit', base_config_1.TYPE], + ['PlaneLayout', base_config_1.TYPE], + ['PointerEventInit', base_config_1.TYPE], + ['PointerLockOptions', base_config_1.TYPE], + ['PopStateEventInit', base_config_1.TYPE], + ['PositionOptions', base_config_1.TYPE], + ['ProgressEventInit', base_config_1.TYPE], + ['PromiseRejectionEventInit', base_config_1.TYPE], + ['PropertyDefinition', base_config_1.TYPE], + ['PropertyIndexedKeyframes', base_config_1.TYPE], + ['PublicKeyCredentialCreationOptions', base_config_1.TYPE], + ['PublicKeyCredentialCreationOptionsJSON', base_config_1.TYPE], + ['PublicKeyCredentialDescriptor', base_config_1.TYPE], + ['PublicKeyCredentialDescriptorJSON', base_config_1.TYPE], + ['PublicKeyCredentialEntity', base_config_1.TYPE], + ['PublicKeyCredentialParameters', base_config_1.TYPE], + ['PublicKeyCredentialRequestOptions', base_config_1.TYPE], + ['PublicKeyCredentialRequestOptionsJSON', base_config_1.TYPE], + ['PublicKeyCredentialRpEntity', base_config_1.TYPE], + ['PublicKeyCredentialUserEntity', base_config_1.TYPE], + ['PublicKeyCredentialUserEntityJSON', base_config_1.TYPE], + ['PushSubscriptionJSON', base_config_1.TYPE], + ['PushSubscriptionOptionsInit', base_config_1.TYPE], + ['QueuingStrategy', base_config_1.TYPE], + ['QueuingStrategyInit', base_config_1.TYPE], + ['RTCAnswerOptions', base_config_1.TYPE], + ['RTCCertificateExpiration', base_config_1.TYPE], + ['RTCConfiguration', base_config_1.TYPE], + ['RTCDTMFToneChangeEventInit', base_config_1.TYPE], + ['RTCDataChannelEventInit', base_config_1.TYPE], + ['RTCDataChannelInit', base_config_1.TYPE], + ['RTCDtlsFingerprint', base_config_1.TYPE], + ['RTCEncodedAudioFrameMetadata', base_config_1.TYPE], + ['RTCEncodedFrameMetadata', base_config_1.TYPE], + ['RTCEncodedVideoFrameMetadata', base_config_1.TYPE], + ['RTCErrorEventInit', base_config_1.TYPE], + ['RTCErrorInit', base_config_1.TYPE], + ['RTCIceCandidateInit', base_config_1.TYPE], + ['RTCIceCandidatePairStats', base_config_1.TYPE], + ['RTCIceServer', base_config_1.TYPE], + ['RTCInboundRtpStreamStats', base_config_1.TYPE], + ['RTCLocalIceCandidateInit', base_config_1.TYPE], + ['RTCLocalSessionDescriptionInit', base_config_1.TYPE], + ['RTCOfferAnswerOptions', base_config_1.TYPE], + ['RTCOfferOptions', base_config_1.TYPE], + ['RTCOutboundRtpStreamStats', base_config_1.TYPE], + ['RTCPeerConnectionIceErrorEventInit', base_config_1.TYPE], + ['RTCPeerConnectionIceEventInit', base_config_1.TYPE], + ['RTCReceivedRtpStreamStats', base_config_1.TYPE], + ['RTCRtcpParameters', base_config_1.TYPE], + ['RTCRtpCapabilities', base_config_1.TYPE], + ['RTCRtpCodec', base_config_1.TYPE], + ['RTCRtpCodecParameters', base_config_1.TYPE], + ['RTCRtpCodingParameters', base_config_1.TYPE], + ['RTCRtpContributingSource', base_config_1.TYPE], + ['RTCRtpEncodingParameters', base_config_1.TYPE], + ['RTCRtpHeaderExtensionCapability', base_config_1.TYPE], + ['RTCRtpHeaderExtensionParameters', base_config_1.TYPE], + ['RTCRtpParameters', base_config_1.TYPE], + ['RTCRtpReceiveParameters', base_config_1.TYPE], + ['RTCRtpSendParameters', base_config_1.TYPE], + ['RTCRtpStreamStats', base_config_1.TYPE], + ['RTCRtpSynchronizationSource', base_config_1.TYPE], + ['RTCRtpTransceiverInit', base_config_1.TYPE], + ['RTCSentRtpStreamStats', base_config_1.TYPE], + ['RTCSessionDescriptionInit', base_config_1.TYPE], + ['RTCSetParameterOptions', base_config_1.TYPE], + ['RTCStats', base_config_1.TYPE], + ['RTCTrackEventInit', base_config_1.TYPE], + ['RTCTransportStats', base_config_1.TYPE], + ['ReadableStreamBYOBReaderReadOptions', base_config_1.TYPE], + ['ReadableStreamGetReaderOptions', base_config_1.TYPE], + ['ReadableStreamIteratorOptions', base_config_1.TYPE], + ['ReadableStreamReadDoneResult', base_config_1.TYPE], + ['ReadableStreamReadValueResult', base_config_1.TYPE], + ['ReadableWritablePair', base_config_1.TYPE], + ['RegistrationOptions', base_config_1.TYPE], + ['RegistrationResponseJSON', base_config_1.TYPE], + ['Report', base_config_1.TYPE], + ['ReportBody', base_config_1.TYPE], + ['ReportingObserverOptions', base_config_1.TYPE], + ['RequestInit', base_config_1.TYPE], + ['ResizeObserverOptions', base_config_1.TYPE], + ['ResponseInit', base_config_1.TYPE], + ['RsaHashedImportParams', base_config_1.TYPE], + ['RsaHashedKeyAlgorithm', base_config_1.TYPE], + ['RsaHashedKeyGenParams', base_config_1.TYPE], + ['RsaKeyAlgorithm', base_config_1.TYPE], + ['RsaKeyGenParams', base_config_1.TYPE], + ['RsaOaepParams', base_config_1.TYPE], + ['RsaOtherPrimesInfo', base_config_1.TYPE], + ['RsaPssParams', base_config_1.TYPE], + ['SVGBoundingBoxOptions', base_config_1.TYPE], + ['SanitizerAttributeNamespace', base_config_1.TYPE], + ['SanitizerConfig', base_config_1.TYPE], + ['SanitizerElementNamespace', base_config_1.TYPE], + ['SanitizerElementNamespaceWithAttributes', base_config_1.TYPE], + ['SchedulerPostTaskOptions', base_config_1.TYPE], + ['ScrollIntoViewOptions', base_config_1.TYPE], + ['ScrollOptions', base_config_1.TYPE], + ['ScrollTimelineOptions', base_config_1.TYPE], + ['ScrollToOptions', base_config_1.TYPE], + ['SecurityPolicyViolationEventInit', base_config_1.TYPE], + ['ShadowRootInit', base_config_1.TYPE], + ['ShareData', base_config_1.TYPE], + ['ShowPopoverOptions', base_config_1.TYPE], + ['SpeechRecognitionErrorEventInit', base_config_1.TYPE], + ['SpeechRecognitionEventInit', base_config_1.TYPE], + ['SpeechSynthesisErrorEventInit', base_config_1.TYPE], + ['SpeechSynthesisEventInit', base_config_1.TYPE], + ['StartViewTransitionOptions', base_config_1.TYPE], + ['StaticRangeInit', base_config_1.TYPE], + ['StereoPannerOptions', base_config_1.TYPE], + ['StorageEstimate', base_config_1.TYPE], + ['StorageEventInit', base_config_1.TYPE], + ['StreamPipeOptions', base_config_1.TYPE], + ['StructuredSerializeOptions', base_config_1.TYPE], + ['SubmitEventInit', base_config_1.TYPE], + ['SvcOutputMetadata', base_config_1.TYPE], + ['TaskControllerInit', base_config_1.TYPE], + ['TaskPriorityChangeEventInit', base_config_1.TYPE], + ['TaskSignalAnyInit', base_config_1.TYPE], + ['TextDecodeOptions', base_config_1.TYPE], + ['TextDecoderOptions', base_config_1.TYPE], + ['TextEncoderEncodeIntoResult', base_config_1.TYPE], + ['TimelineRangeOffset', base_config_1.TYPE], + ['ToggleEventInit', base_config_1.TYPE], + ['TogglePopoverOptions', base_config_1.TYPE], + ['TouchEventInit', base_config_1.TYPE], + ['TouchInit', base_config_1.TYPE], + ['TrackEventInit', base_config_1.TYPE], + ['Transformer', base_config_1.TYPE], + ['TransitionEventInit', base_config_1.TYPE], + ['UIEventInit', base_config_1.TYPE], + ['ULongRange', base_config_1.TYPE], + ['URLPatternComponentResult', base_config_1.TYPE], + ['URLPatternInit', base_config_1.TYPE], + ['URLPatternOptions', base_config_1.TYPE], + ['URLPatternResult', base_config_1.TYPE], + ['UnderlyingByteSource', base_config_1.TYPE], + ['UnderlyingDefaultSource', base_config_1.TYPE], + ['UnderlyingSink', base_config_1.TYPE], + ['UnderlyingSource', base_config_1.TYPE], + ['UnknownCredentialOptions', base_config_1.TYPE], + ['ValidityStateFlags', base_config_1.TYPE], + ['VideoColorSpaceInit', base_config_1.TYPE], + ['VideoConfiguration', base_config_1.TYPE], + ['VideoDecoderConfig', base_config_1.TYPE], + ['VideoDecoderInit', base_config_1.TYPE], + ['VideoDecoderSupport', base_config_1.TYPE], + ['VideoEncoderConfig', base_config_1.TYPE], + ['VideoEncoderEncodeOptions', base_config_1.TYPE], + ['VideoEncoderEncodeOptionsForAvc', base_config_1.TYPE], + ['VideoEncoderInit', base_config_1.TYPE], + ['VideoEncoderSupport', base_config_1.TYPE], + ['VideoFrameBufferInit', base_config_1.TYPE], + ['VideoFrameCallbackMetadata', base_config_1.TYPE], + ['VideoFrameCopyToOptions', base_config_1.TYPE], + ['VideoFrameInit', base_config_1.TYPE], + ['ViewTimelineOptions', base_config_1.TYPE], + ['WaveShaperOptions', base_config_1.TYPE], + ['WebGLContextAttributes', base_config_1.TYPE], + ['WebGLContextEventInit', base_config_1.TYPE], + ['WebTransportCloseInfo', base_config_1.TYPE], + ['WebTransportErrorOptions', base_config_1.TYPE], + ['WebTransportHash', base_config_1.TYPE], + ['WebTransportOptions', base_config_1.TYPE], + ['WebTransportSendOptions', base_config_1.TYPE], + ['WebTransportSendStreamOptions', base_config_1.TYPE], + ['WheelEventInit', base_config_1.TYPE], + ['WindowPostMessageOptions', base_config_1.TYPE], + ['WorkerOptions', base_config_1.TYPE], + ['WorkletOptions', base_config_1.TYPE], + ['WriteParams', base_config_1.TYPE], + ['NodeFilter', base_config_1.TYPE_VALUE], + ['XPathNSResolver', base_config_1.TYPE], + ['ANGLE_instanced_arrays', base_config_1.TYPE], + ['ARIAMixin', base_config_1.TYPE], + ['AbortController', base_config_1.TYPE_VALUE], + ['AbortSignalEventMap', base_config_1.TYPE], + ['AbortSignal', base_config_1.TYPE_VALUE], + ['AbstractRange', base_config_1.TYPE_VALUE], + ['AbstractWorkerEventMap', base_config_1.TYPE], + ['AbstractWorker', base_config_1.TYPE], + ['AnalyserNode', base_config_1.TYPE_VALUE], + ['Animatable', base_config_1.TYPE], + ['AnimationEventMap', base_config_1.TYPE], + ['Animation', base_config_1.TYPE_VALUE], + ['AnimationEffect', base_config_1.TYPE_VALUE], + ['AnimationEvent', base_config_1.TYPE_VALUE], + ['AnimationFrameProvider', base_config_1.TYPE], + ['AnimationPlaybackEvent', base_config_1.TYPE_VALUE], + ['AnimationTimeline', base_config_1.TYPE_VALUE], + ['Attr', base_config_1.TYPE_VALUE], + ['AudioBuffer', base_config_1.TYPE_VALUE], + ['AudioBufferSourceNode', base_config_1.TYPE_VALUE], + ['AudioContext', base_config_1.TYPE_VALUE], + ['AudioData', base_config_1.TYPE_VALUE], + ['AudioDecoderEventMap', base_config_1.TYPE], + ['AudioDecoder', base_config_1.TYPE_VALUE], + ['AudioDestinationNode', base_config_1.TYPE_VALUE], + ['AudioEncoderEventMap', base_config_1.TYPE], + ['AudioEncoder', base_config_1.TYPE_VALUE], + ['AudioListener', base_config_1.TYPE_VALUE], + ['AudioNode', base_config_1.TYPE_VALUE], + ['AudioParam', base_config_1.TYPE_VALUE], + ['AudioParamMap', base_config_1.TYPE_VALUE], + ['AudioProcessingEvent', base_config_1.TYPE_VALUE], + ['AudioScheduledSourceNodeEventMap', base_config_1.TYPE], + ['AudioScheduledSourceNode', base_config_1.TYPE_VALUE], + ['AudioWorklet', base_config_1.TYPE_VALUE], + ['AudioWorkletNodeEventMap', base_config_1.TYPE], + ['AudioWorkletNode', base_config_1.TYPE_VALUE], + ['AuthenticatorAssertionResponse', base_config_1.TYPE_VALUE], + ['AuthenticatorAttestationResponse', base_config_1.TYPE_VALUE], + ['AuthenticatorResponse', base_config_1.TYPE_VALUE], + ['BarProp', base_config_1.TYPE_VALUE], + ['BaseAudioContextEventMap', base_config_1.TYPE], + ['BaseAudioContext', base_config_1.TYPE_VALUE], + ['BeforeUnloadEvent', base_config_1.TYPE_VALUE], + ['BiquadFilterNode', base_config_1.TYPE_VALUE], + ['Blob', base_config_1.TYPE_VALUE], + ['BlobEvent', base_config_1.TYPE_VALUE], + ['Body', base_config_1.TYPE], + ['BroadcastChannelEventMap', base_config_1.TYPE], + ['BroadcastChannel', base_config_1.TYPE_VALUE], + ['ByteLengthQueuingStrategy', base_config_1.TYPE_VALUE], + ['CDATASection', base_config_1.TYPE_VALUE], + ['CSSAnimation', base_config_1.TYPE_VALUE], + ['CSSConditionRule', base_config_1.TYPE_VALUE], + ['CSSContainerRule', base_config_1.TYPE_VALUE], + ['CSSCounterStyleRule', base_config_1.TYPE_VALUE], + ['CSSFontFaceRule', base_config_1.TYPE_VALUE], + ['CSSFontFeatureValuesRule', base_config_1.TYPE_VALUE], + ['CSSFontPaletteValuesRule', base_config_1.TYPE_VALUE], + ['CSSGroupingRule', base_config_1.TYPE_VALUE], + ['CSSImageValue', base_config_1.TYPE_VALUE], + ['CSSImportRule', base_config_1.TYPE_VALUE], + ['CSSKeyframeRule', base_config_1.TYPE_VALUE], + ['CSSKeyframesRule', base_config_1.TYPE_VALUE], + ['CSSKeywordValue', base_config_1.TYPE_VALUE], + ['CSSLayerBlockRule', base_config_1.TYPE_VALUE], + ['CSSLayerStatementRule', base_config_1.TYPE_VALUE], + ['CSSMathClamp', base_config_1.TYPE_VALUE], + ['CSSMathInvert', base_config_1.TYPE_VALUE], + ['CSSMathMax', base_config_1.TYPE_VALUE], + ['CSSMathMin', base_config_1.TYPE_VALUE], + ['CSSMathNegate', base_config_1.TYPE_VALUE], + ['CSSMathProduct', base_config_1.TYPE_VALUE], + ['CSSMathSum', base_config_1.TYPE_VALUE], + ['CSSMathValue', base_config_1.TYPE_VALUE], + ['CSSMatrixComponent', base_config_1.TYPE_VALUE], + ['CSSMediaRule', base_config_1.TYPE_VALUE], + ['CSSNamespaceRule', base_config_1.TYPE_VALUE], + ['CSSNestedDeclarations', base_config_1.TYPE_VALUE], + ['CSSNumericArray', base_config_1.TYPE_VALUE], + ['CSSNumericValue', base_config_1.TYPE_VALUE], + ['CSSPageDescriptors', base_config_1.TYPE_VALUE], + ['CSSPageRule', base_config_1.TYPE_VALUE], + ['CSSPerspective', base_config_1.TYPE_VALUE], + ['CSSPositionTryDescriptors', base_config_1.TYPE_VALUE], + ['CSSPositionTryRule', base_config_1.TYPE_VALUE], + ['CSSPropertyRule', base_config_1.TYPE_VALUE], + ['CSSRotate', base_config_1.TYPE_VALUE], + ['CSSRule', base_config_1.TYPE_VALUE], + ['CSSRuleList', base_config_1.TYPE_VALUE], + ['CSSScale', base_config_1.TYPE_VALUE], + ['CSSScopeRule', base_config_1.TYPE_VALUE], + ['CSSSkew', base_config_1.TYPE_VALUE], + ['CSSSkewX', base_config_1.TYPE_VALUE], + ['CSSSkewY', base_config_1.TYPE_VALUE], + ['CSSStartingStyleRule', base_config_1.TYPE_VALUE], + ['CSSStyleDeclarationBase', base_config_1.TYPE], + ['CSSStyleDeclaration', base_config_1.TYPE_VALUE], + ['CSSStyleProperties', base_config_1.TYPE_VALUE], + ['CSSStyleRule', base_config_1.TYPE_VALUE], + ['CSSStyleSheet', base_config_1.TYPE_VALUE], + ['CSSStyleValue', base_config_1.TYPE_VALUE], + ['CSSSupportsRule', base_config_1.TYPE_VALUE], + ['CSSTransformComponent', base_config_1.TYPE_VALUE], + ['CSSTransformValue', base_config_1.TYPE_VALUE], + ['CSSTransition', base_config_1.TYPE_VALUE], + ['CSSTranslate', base_config_1.TYPE_VALUE], + ['CSSUnitValue', base_config_1.TYPE_VALUE], + ['CSSUnparsedValue', base_config_1.TYPE_VALUE], + ['CSSVariableReferenceValue', base_config_1.TYPE_VALUE], + ['CSSViewTransitionRule', base_config_1.TYPE_VALUE], + ['Cache', base_config_1.TYPE_VALUE], + ['CacheStorage', base_config_1.TYPE_VALUE], + ['CanvasCaptureMediaStreamTrack', base_config_1.TYPE_VALUE], + ['CanvasCompositing', base_config_1.TYPE], + ['CanvasDrawImage', base_config_1.TYPE], + ['CanvasDrawPath', base_config_1.TYPE], + ['CanvasFillStrokeStyles', base_config_1.TYPE], + ['CanvasFilters', base_config_1.TYPE], + ['CanvasGradient', base_config_1.TYPE_VALUE], + ['CanvasImageData', base_config_1.TYPE], + ['CanvasImageSmoothing', base_config_1.TYPE], + ['CanvasPath', base_config_1.TYPE], + ['CanvasPathDrawingStyles', base_config_1.TYPE], + ['CanvasPattern', base_config_1.TYPE_VALUE], + ['CanvasRect', base_config_1.TYPE], + ['CanvasRenderingContext2D', base_config_1.TYPE_VALUE], + ['CanvasSettings', base_config_1.TYPE], + ['CanvasShadowStyles', base_config_1.TYPE], + ['CanvasState', base_config_1.TYPE], + ['CanvasText', base_config_1.TYPE], + ['CanvasTextDrawingStyles', base_config_1.TYPE], + ['CanvasTransform', base_config_1.TYPE], + ['CanvasUserInterface', base_config_1.TYPE], + ['CaretPosition', base_config_1.TYPE_VALUE], + ['ChannelMergerNode', base_config_1.TYPE_VALUE], + ['ChannelSplitterNode', base_config_1.TYPE_VALUE], + ['CharacterData', base_config_1.TYPE_VALUE], + ['ChildNode', base_config_1.TYPE], + ['ClientRect', base_config_1.TYPE], + ['Clipboard', base_config_1.TYPE_VALUE], + ['ClipboardEvent', base_config_1.TYPE_VALUE], + ['ClipboardItem', base_config_1.TYPE_VALUE], + ['CloseEvent', base_config_1.TYPE_VALUE], + ['CommandEvent', base_config_1.TYPE_VALUE], + ['Comment', base_config_1.TYPE_VALUE], + ['CompositionEvent', base_config_1.TYPE_VALUE], + ['CompressionStream', base_config_1.TYPE_VALUE], + ['ConstantSourceNode', base_config_1.TYPE_VALUE], + ['ContentVisibilityAutoStateChangeEvent', base_config_1.TYPE_VALUE], + ['ConvolverNode', base_config_1.TYPE_VALUE], + ['CookieChangeEvent', base_config_1.TYPE_VALUE], + ['CookieStoreEventMap', base_config_1.TYPE], + ['CookieStore', base_config_1.TYPE_VALUE], + ['CookieStoreManager', base_config_1.TYPE_VALUE], + ['CountQueuingStrategy', base_config_1.TYPE_VALUE], + ['Credential', base_config_1.TYPE_VALUE], + ['CredentialsContainer', base_config_1.TYPE_VALUE], + ['Crypto', base_config_1.TYPE_VALUE], + ['CryptoKey', base_config_1.TYPE_VALUE], + ['CustomElementRegistry', base_config_1.TYPE_VALUE], + ['CustomEvent', base_config_1.TYPE_VALUE], + ['CustomStateSet', base_config_1.TYPE_VALUE], + ['DOMException', base_config_1.TYPE_VALUE], + ['DOMImplementation', base_config_1.TYPE_VALUE], + ['DOMMatrix', base_config_1.TYPE_VALUE], + ['SVGMatrix', base_config_1.TYPE_VALUE], + ['WebKitCSSMatrix', base_config_1.TYPE_VALUE], + ['DOMMatrixReadOnly', base_config_1.TYPE_VALUE], + ['DOMParser', base_config_1.TYPE_VALUE], + ['DOMPoint', base_config_1.TYPE_VALUE], + ['SVGPoint', base_config_1.TYPE_VALUE], + ['DOMPointReadOnly', base_config_1.TYPE_VALUE], + ['DOMQuad', base_config_1.TYPE_VALUE], + ['DOMRect', base_config_1.TYPE_VALUE], + ['SVGRect', base_config_1.TYPE_VALUE], + ['DOMRectList', base_config_1.TYPE_VALUE], + ['DOMRectReadOnly', base_config_1.TYPE_VALUE], + ['DOMStringList', base_config_1.TYPE_VALUE], + ['DOMStringMap', base_config_1.TYPE_VALUE], + ['DOMTokenList', base_config_1.TYPE_VALUE], + ['DataTransfer', base_config_1.TYPE_VALUE], + ['DataTransferItem', base_config_1.TYPE_VALUE], + ['DataTransferItemList', base_config_1.TYPE_VALUE], + ['DecompressionStream', base_config_1.TYPE_VALUE], + ['DelayNode', base_config_1.TYPE_VALUE], + ['DeviceMotionEvent', base_config_1.TYPE_VALUE], + ['DeviceMotionEventAcceleration', base_config_1.TYPE], + ['DeviceMotionEventRotationRate', base_config_1.TYPE], + ['DeviceOrientationEvent', base_config_1.TYPE_VALUE], + ['DigitalCredential', base_config_1.TYPE_VALUE], + ['DocumentEventMap', base_config_1.TYPE], + ['Document', base_config_1.TYPE_VALUE], + ['DocumentFragment', base_config_1.TYPE_VALUE], + ['DocumentOrShadowRoot', base_config_1.TYPE], + ['DocumentTimeline', base_config_1.TYPE_VALUE], + ['DocumentType', base_config_1.TYPE_VALUE], + ['DragEvent', base_config_1.TYPE_VALUE], + ['DynamicsCompressorNode', base_config_1.TYPE_VALUE], + ['EXT_blend_minmax', base_config_1.TYPE], + ['EXT_color_buffer_float', base_config_1.TYPE], + ['EXT_color_buffer_half_float', base_config_1.TYPE], + ['EXT_float_blend', base_config_1.TYPE], + ['EXT_frag_depth', base_config_1.TYPE], + ['EXT_sRGB', base_config_1.TYPE], + ['EXT_shader_texture_lod', base_config_1.TYPE], + ['EXT_texture_compression_bptc', base_config_1.TYPE], + ['EXT_texture_compression_rgtc', base_config_1.TYPE], + ['EXT_texture_filter_anisotropic', base_config_1.TYPE], + ['EXT_texture_norm16', base_config_1.TYPE], + ['ElementEventMap', base_config_1.TYPE], + ['Element', base_config_1.TYPE_VALUE], + ['ElementCSSInlineStyle', base_config_1.TYPE], + ['ElementContentEditable', base_config_1.TYPE], + ['ElementInternals', base_config_1.TYPE_VALUE], + ['EncodedAudioChunk', base_config_1.TYPE_VALUE], + ['EncodedVideoChunk', base_config_1.TYPE_VALUE], + ['ErrorEvent', base_config_1.TYPE_VALUE], + ['Event', base_config_1.TYPE_VALUE], + ['EventCounts', base_config_1.TYPE_VALUE], + ['EventListener', base_config_1.TYPE], + ['EventListenerObject', base_config_1.TYPE], + ['EventSourceEventMap', base_config_1.TYPE], + ['EventSource', base_config_1.TYPE_VALUE], + ['EventTarget', base_config_1.TYPE_VALUE], + ['External', base_config_1.TYPE_VALUE], + ['File', base_config_1.TYPE_VALUE], + ['FileList', base_config_1.TYPE_VALUE], + ['FileReaderEventMap', base_config_1.TYPE], + ['FileReader', base_config_1.TYPE_VALUE], + ['FileSystem', base_config_1.TYPE_VALUE], + ['FileSystemDirectoryEntry', base_config_1.TYPE_VALUE], + ['FileSystemDirectoryHandle', base_config_1.TYPE_VALUE], + ['FileSystemDirectoryReader', base_config_1.TYPE_VALUE], + ['FileSystemEntry', base_config_1.TYPE_VALUE], + ['FileSystemFileEntry', base_config_1.TYPE_VALUE], + ['FileSystemFileHandle', base_config_1.TYPE_VALUE], + ['FileSystemHandle', base_config_1.TYPE_VALUE], + ['FileSystemWritableFileStream', base_config_1.TYPE_VALUE], + ['FocusEvent', base_config_1.TYPE_VALUE], + ['FontFace', base_config_1.TYPE_VALUE], + ['FontFaceSetEventMap', base_config_1.TYPE], + ['FontFaceSet', base_config_1.TYPE_VALUE], + ['FontFaceSetLoadEvent', base_config_1.TYPE_VALUE], + ['FontFaceSource', base_config_1.TYPE], + ['FormData', base_config_1.TYPE_VALUE], + ['FormDataEvent', base_config_1.TYPE_VALUE], + ['FragmentDirective', base_config_1.TYPE_VALUE], + ['GPU', base_config_1.TYPE_VALUE], + ['GPUAdapter', base_config_1.TYPE_VALUE], + ['GPUAdapterInfo', base_config_1.TYPE_VALUE], + ['GPUBindGroup', base_config_1.TYPE_VALUE], + ['GPUBindGroupLayout', base_config_1.TYPE_VALUE], + ['GPUBindingCommandsMixin', base_config_1.TYPE], + ['GPUBuffer', base_config_1.TYPE_VALUE], + ['GPUCanvasContext', base_config_1.TYPE_VALUE], + ['GPUCommandBuffer', base_config_1.TYPE_VALUE], + ['GPUCommandEncoder', base_config_1.TYPE_VALUE], + ['GPUCompilationInfo', base_config_1.TYPE_VALUE], + ['GPUCompilationMessage', base_config_1.TYPE_VALUE], + ['GPUComputePassEncoder', base_config_1.TYPE_VALUE], + ['GPUComputePipeline', base_config_1.TYPE_VALUE], + ['GPUDebugCommandsMixin', base_config_1.TYPE], + ['GPUDeviceEventMap', base_config_1.TYPE], + ['GPUDevice', base_config_1.TYPE_VALUE], + ['GPUDeviceLostInfo', base_config_1.TYPE_VALUE], + ['GPUError', base_config_1.TYPE_VALUE], + ['GPUExternalTexture', base_config_1.TYPE_VALUE], + ['GPUInternalError', base_config_1.TYPE_VALUE], + ['GPUObjectBase', base_config_1.TYPE], + ['GPUOutOfMemoryError', base_config_1.TYPE_VALUE], + ['GPUPipelineBase', base_config_1.TYPE], + ['GPUPipelineError', base_config_1.TYPE_VALUE], + ['GPUPipelineLayout', base_config_1.TYPE_VALUE], + ['GPUQuerySet', base_config_1.TYPE_VALUE], + ['GPUQueue', base_config_1.TYPE_VALUE], + ['GPURenderBundle', base_config_1.TYPE_VALUE], + ['GPURenderBundleEncoder', base_config_1.TYPE_VALUE], + ['GPURenderCommandsMixin', base_config_1.TYPE], + ['GPURenderPassEncoder', base_config_1.TYPE_VALUE], + ['GPURenderPipeline', base_config_1.TYPE_VALUE], + ['GPUSampler', base_config_1.TYPE_VALUE], + ['GPUShaderModule', base_config_1.TYPE_VALUE], + ['GPUSupportedFeatures', base_config_1.TYPE_VALUE], + ['GPUSupportedLimits', base_config_1.TYPE_VALUE], + ['GPUTexture', base_config_1.TYPE_VALUE], + ['GPUTextureView', base_config_1.TYPE_VALUE], + ['GPUUncapturedErrorEvent', base_config_1.TYPE_VALUE], + ['GPUValidationError', base_config_1.TYPE_VALUE], + ['GainNode', base_config_1.TYPE_VALUE], + ['Gamepad', base_config_1.TYPE_VALUE], + ['GamepadButton', base_config_1.TYPE_VALUE], + ['GamepadEvent', base_config_1.TYPE_VALUE], + ['GamepadHapticActuator', base_config_1.TYPE_VALUE], + ['GenericTransformStream', base_config_1.TYPE], + ['Geolocation', base_config_1.TYPE_VALUE], + ['GeolocationCoordinates', base_config_1.TYPE_VALUE], + ['GeolocationPosition', base_config_1.TYPE_VALUE], + ['GeolocationPositionError', base_config_1.TYPE_VALUE], + ['GlobalEventHandlersEventMap', base_config_1.TYPE], + ['GlobalEventHandlers', base_config_1.TYPE], + ['HTMLAllCollection', base_config_1.TYPE_VALUE], + ['HTMLAnchorElement', base_config_1.TYPE_VALUE], + ['HTMLAreaElement', base_config_1.TYPE_VALUE], + ['HTMLAudioElement', base_config_1.TYPE_VALUE], + ['HTMLBRElement', base_config_1.TYPE_VALUE], + ['HTMLBaseElement', base_config_1.TYPE_VALUE], + ['HTMLBodyElementEventMap', base_config_1.TYPE], + ['HTMLBodyElement', base_config_1.TYPE_VALUE], + ['HTMLButtonElement', base_config_1.TYPE_VALUE], + ['HTMLCanvasElement', base_config_1.TYPE_VALUE], + ['HTMLCollectionBase', base_config_1.TYPE], + ['HTMLCollection', base_config_1.TYPE_VALUE], + ['HTMLCollectionOf', base_config_1.TYPE], + ['HTMLDListElement', base_config_1.TYPE_VALUE], + ['HTMLDataElement', base_config_1.TYPE_VALUE], + ['HTMLDataListElement', base_config_1.TYPE_VALUE], + ['HTMLDetailsElement', base_config_1.TYPE_VALUE], + ['HTMLDialogElement', base_config_1.TYPE_VALUE], + ['HTMLDirectoryElement', base_config_1.TYPE_VALUE], + ['HTMLDivElement', base_config_1.TYPE_VALUE], + ['HTMLDocument', base_config_1.TYPE_VALUE], + ['HTMLElementEventMap', base_config_1.TYPE], + ['HTMLElement', base_config_1.TYPE_VALUE], + ['HTMLEmbedElement', base_config_1.TYPE_VALUE], + ['HTMLFieldSetElement', base_config_1.TYPE_VALUE], + ['HTMLFontElement', base_config_1.TYPE_VALUE], + ['HTMLFormControlsCollection', base_config_1.TYPE_VALUE], + ['HTMLFormElement', base_config_1.TYPE_VALUE], + ['HTMLFrameElement', base_config_1.TYPE_VALUE], + ['HTMLFrameSetElementEventMap', base_config_1.TYPE], + ['HTMLFrameSetElement', base_config_1.TYPE_VALUE], + ['HTMLHRElement', base_config_1.TYPE_VALUE], + ['HTMLHeadElement', base_config_1.TYPE_VALUE], + ['HTMLHeadingElement', base_config_1.TYPE_VALUE], + ['HTMLHtmlElement', base_config_1.TYPE_VALUE], + ['HTMLHyperlinkElementUtils', base_config_1.TYPE], + ['HTMLIFrameElement', base_config_1.TYPE_VALUE], + ['HTMLImageElement', base_config_1.TYPE_VALUE], + ['HTMLInputElement', base_config_1.TYPE_VALUE], + ['HTMLLIElement', base_config_1.TYPE_VALUE], + ['HTMLLabelElement', base_config_1.TYPE_VALUE], + ['HTMLLegendElement', base_config_1.TYPE_VALUE], + ['HTMLLinkElement', base_config_1.TYPE_VALUE], + ['HTMLMapElement', base_config_1.TYPE_VALUE], + ['HTMLMarqueeElement', base_config_1.TYPE_VALUE], + ['HTMLMediaElementEventMap', base_config_1.TYPE], + ['HTMLMediaElement', base_config_1.TYPE_VALUE], + ['HTMLMenuElement', base_config_1.TYPE_VALUE], + ['HTMLMetaElement', base_config_1.TYPE_VALUE], + ['HTMLMeterElement', base_config_1.TYPE_VALUE], + ['HTMLModElement', base_config_1.TYPE_VALUE], + ['HTMLOListElement', base_config_1.TYPE_VALUE], + ['HTMLObjectElement', base_config_1.TYPE_VALUE], + ['HTMLOptGroupElement', base_config_1.TYPE_VALUE], + ['HTMLOptionElement', base_config_1.TYPE_VALUE], + ['HTMLOptionsCollection', base_config_1.TYPE_VALUE], + ['HTMLOrSVGElement', base_config_1.TYPE], + ['HTMLOutputElement', base_config_1.TYPE_VALUE], + ['HTMLParagraphElement', base_config_1.TYPE_VALUE], + ['HTMLParamElement', base_config_1.TYPE_VALUE], + ['HTMLPictureElement', base_config_1.TYPE_VALUE], + ['HTMLPreElement', base_config_1.TYPE_VALUE], + ['HTMLProgressElement', base_config_1.TYPE_VALUE], + ['HTMLQuoteElement', base_config_1.TYPE_VALUE], + ['HTMLScriptElement', base_config_1.TYPE_VALUE], + ['HTMLSelectElement', base_config_1.TYPE_VALUE], + ['HTMLSlotElement', base_config_1.TYPE_VALUE], + ['HTMLSourceElement', base_config_1.TYPE_VALUE], + ['HTMLSpanElement', base_config_1.TYPE_VALUE], + ['HTMLStyleElement', base_config_1.TYPE_VALUE], + ['HTMLTableCaptionElement', base_config_1.TYPE_VALUE], + ['HTMLTableCellElement', base_config_1.TYPE_VALUE], + ['HTMLTableColElement', base_config_1.TYPE_VALUE], + ['HTMLTableDataCellElement', base_config_1.TYPE], + ['HTMLTableElement', base_config_1.TYPE_VALUE], + ['HTMLTableHeaderCellElement', base_config_1.TYPE], + ['HTMLTableRowElement', base_config_1.TYPE_VALUE], + ['HTMLTableSectionElement', base_config_1.TYPE_VALUE], + ['HTMLTemplateElement', base_config_1.TYPE_VALUE], + ['HTMLTextAreaElement', base_config_1.TYPE_VALUE], + ['HTMLTimeElement', base_config_1.TYPE_VALUE], + ['HTMLTitleElement', base_config_1.TYPE_VALUE], + ['HTMLTrackElement', base_config_1.TYPE_VALUE], + ['HTMLUListElement', base_config_1.TYPE_VALUE], + ['HTMLUnknownElement', base_config_1.TYPE_VALUE], + ['HTMLVideoElementEventMap', base_config_1.TYPE], + ['HTMLVideoElement', base_config_1.TYPE_VALUE], + ['HashChangeEvent', base_config_1.TYPE_VALUE], + ['Headers', base_config_1.TYPE_VALUE], + ['Highlight', base_config_1.TYPE_VALUE], + ['HighlightRegistry', base_config_1.TYPE_VALUE], + ['History', base_config_1.TYPE_VALUE], + ['IDBCursor', base_config_1.TYPE_VALUE], + ['IDBCursorWithValue', base_config_1.TYPE_VALUE], + ['IDBDatabaseEventMap', base_config_1.TYPE], + ['IDBDatabase', base_config_1.TYPE_VALUE], + ['IDBFactory', base_config_1.TYPE_VALUE], + ['IDBIndex', base_config_1.TYPE_VALUE], + ['IDBKeyRange', base_config_1.TYPE_VALUE], + ['IDBObjectStore', base_config_1.TYPE_VALUE], + ['IDBOpenDBRequestEventMap', base_config_1.TYPE], + ['IDBOpenDBRequest', base_config_1.TYPE_VALUE], + ['IDBRequestEventMap', base_config_1.TYPE], + ['IDBRequest', base_config_1.TYPE_VALUE], + ['IDBTransactionEventMap', base_config_1.TYPE], + ['IDBTransaction', base_config_1.TYPE_VALUE], + ['IDBVersionChangeEvent', base_config_1.TYPE_VALUE], + ['IIRFilterNode', base_config_1.TYPE_VALUE], + ['IdleDeadline', base_config_1.TYPE_VALUE], + ['ImageBitmap', base_config_1.TYPE_VALUE], + ['ImageBitmapRenderingContext', base_config_1.TYPE_VALUE], + ['ImageCapture', base_config_1.TYPE_VALUE], + ['ImageData', base_config_1.TYPE_VALUE], + ['ImageDecoder', base_config_1.TYPE_VALUE], + ['ImageTrack', base_config_1.TYPE_VALUE], + ['ImageTrackList', base_config_1.TYPE_VALUE], + ['ImportMeta', base_config_1.TYPE], + ['InputDeviceInfo', base_config_1.TYPE_VALUE], + ['InputEvent', base_config_1.TYPE_VALUE], + ['IntersectionObserver', base_config_1.TYPE_VALUE], + ['IntersectionObserverEntry', base_config_1.TYPE_VALUE], + ['KHR_parallel_shader_compile', base_config_1.TYPE], + ['KeyboardEvent', base_config_1.TYPE_VALUE], + ['KeyframeEffect', base_config_1.TYPE_VALUE], + ['LargestContentfulPaint', base_config_1.TYPE_VALUE], + ['LinkStyle', base_config_1.TYPE], + ['Location', base_config_1.TYPE_VALUE], + ['Lock', base_config_1.TYPE_VALUE], + ['LockManager', base_config_1.TYPE_VALUE], + ['MIDIAccessEventMap', base_config_1.TYPE], + ['MIDIAccess', base_config_1.TYPE_VALUE], + ['MIDIConnectionEvent', base_config_1.TYPE_VALUE], + ['MIDIInputEventMap', base_config_1.TYPE], + ['MIDIInput', base_config_1.TYPE_VALUE], + ['MIDIInputMap', base_config_1.TYPE_VALUE], + ['MIDIMessageEvent', base_config_1.TYPE_VALUE], + ['MIDIOutput', base_config_1.TYPE_VALUE], + ['MIDIOutputMap', base_config_1.TYPE_VALUE], + ['MIDIPortEventMap', base_config_1.TYPE], + ['MIDIPort', base_config_1.TYPE_VALUE], + ['MathMLElementEventMap', base_config_1.TYPE], + ['MathMLElement', base_config_1.TYPE_VALUE], + ['MediaCapabilities', base_config_1.TYPE_VALUE], + ['MediaDeviceInfo', base_config_1.TYPE_VALUE], + ['MediaDevicesEventMap', base_config_1.TYPE], + ['MediaDevices', base_config_1.TYPE_VALUE], + ['MediaElementAudioSourceNode', base_config_1.TYPE_VALUE], + ['MediaEncryptedEvent', base_config_1.TYPE_VALUE], + ['MediaError', base_config_1.TYPE_VALUE], + ['MediaKeyMessageEvent', base_config_1.TYPE_VALUE], + ['MediaKeySessionEventMap', base_config_1.TYPE], + ['MediaKeySession', base_config_1.TYPE_VALUE], + ['MediaKeyStatusMap', base_config_1.TYPE_VALUE], + ['MediaKeySystemAccess', base_config_1.TYPE_VALUE], + ['MediaKeys', base_config_1.TYPE_VALUE], + ['MediaList', base_config_1.TYPE_VALUE], + ['MediaMetadata', base_config_1.TYPE_VALUE], + ['MediaQueryListEventMap', base_config_1.TYPE], + ['MediaQueryList', base_config_1.TYPE_VALUE], + ['MediaQueryListEvent', base_config_1.TYPE_VALUE], + ['MediaRecorderEventMap', base_config_1.TYPE], + ['MediaRecorder', base_config_1.TYPE_VALUE], + ['MediaSession', base_config_1.TYPE_VALUE], + ['MediaSourceEventMap', base_config_1.TYPE], + ['MediaSource', base_config_1.TYPE_VALUE], + ['MediaSourceHandle', base_config_1.TYPE_VALUE], + ['MediaStreamEventMap', base_config_1.TYPE], + ['MediaStream', base_config_1.TYPE_VALUE], + ['MediaStreamAudioDestinationNode', base_config_1.TYPE_VALUE], + ['MediaStreamAudioSourceNode', base_config_1.TYPE_VALUE], + ['MediaStreamTrackEventMap', base_config_1.TYPE], + ['MediaStreamTrack', base_config_1.TYPE_VALUE], + ['MediaStreamTrackEvent', base_config_1.TYPE_VALUE], + ['MessageChannel', base_config_1.TYPE_VALUE], + ['MessageEvent', base_config_1.TYPE_VALUE], + ['MessageEventTargetEventMap', base_config_1.TYPE], + ['MessageEventTarget', base_config_1.TYPE], + ['MessagePortEventMap', base_config_1.TYPE], + ['MessagePort', base_config_1.TYPE_VALUE], + ['MimeType', base_config_1.TYPE_VALUE], + ['MimeTypeArray', base_config_1.TYPE_VALUE], + ['MouseEvent', base_config_1.TYPE_VALUE], + ['MutationObserver', base_config_1.TYPE_VALUE], + ['MutationRecord', base_config_1.TYPE_VALUE], + ['NamedNodeMap', base_config_1.TYPE_VALUE], + ['NavigateEvent', base_config_1.TYPE_VALUE], + ['NavigationEventMap', base_config_1.TYPE], + ['Navigation', base_config_1.TYPE_VALUE], + ['NavigationActivation', base_config_1.TYPE_VALUE], + ['NavigationCurrentEntryChangeEvent', base_config_1.TYPE_VALUE], + ['NavigationDestination', base_config_1.TYPE_VALUE], + ['NavigationHistoryEntryEventMap', base_config_1.TYPE], + ['NavigationHistoryEntry', base_config_1.TYPE_VALUE], + ['NavigationPrecommitController', base_config_1.TYPE_VALUE], + ['NavigationPreloadManager', base_config_1.TYPE_VALUE], + ['NavigationTransition', base_config_1.TYPE_VALUE], + ['Navigator', base_config_1.TYPE_VALUE], + ['NavigatorAutomationInformation', base_config_1.TYPE], + ['NavigatorBadge', base_config_1.TYPE], + ['NavigatorConcurrentHardware', base_config_1.TYPE], + ['NavigatorContentUtils', base_config_1.TYPE], + ['NavigatorCookies', base_config_1.TYPE], + ['NavigatorGPU', base_config_1.TYPE], + ['NavigatorID', base_config_1.TYPE], + ['NavigatorLanguage', base_config_1.TYPE], + ['NavigatorLocks', base_config_1.TYPE], + ['NavigatorLogin', base_config_1.TYPE_VALUE], + ['NavigatorOnLine', base_config_1.TYPE], + ['NavigatorPlugins', base_config_1.TYPE], + ['NavigatorStorage', base_config_1.TYPE], + ['Node', base_config_1.TYPE_VALUE], + ['NodeIterator', base_config_1.TYPE_VALUE], + ['NodeList', base_config_1.TYPE_VALUE], + ['NodeListOf', base_config_1.TYPE], + ['NonDocumentTypeChildNode', base_config_1.TYPE], + ['NonElementParentNode', base_config_1.TYPE], + ['NotificationEventMap', base_config_1.TYPE], + ['Notification', base_config_1.TYPE_VALUE], + ['OES_draw_buffers_indexed', base_config_1.TYPE], + ['OES_element_index_uint', base_config_1.TYPE], + ['OES_fbo_render_mipmap', base_config_1.TYPE], + ['OES_standard_derivatives', base_config_1.TYPE], + ['OES_texture_float', base_config_1.TYPE], + ['OES_texture_float_linear', base_config_1.TYPE], + ['OES_texture_half_float', base_config_1.TYPE], + ['OES_texture_half_float_linear', base_config_1.TYPE], + ['OES_vertex_array_object', base_config_1.TYPE], + ['OVR_multiview2', base_config_1.TYPE], + ['OfflineAudioCompletionEvent', base_config_1.TYPE_VALUE], + ['OfflineAudioContextEventMap', base_config_1.TYPE], + ['OfflineAudioContext', base_config_1.TYPE_VALUE], + ['OffscreenCanvasEventMap', base_config_1.TYPE], + ['OffscreenCanvas', base_config_1.TYPE_VALUE], + ['OffscreenCanvasRenderingContext2D', base_config_1.TYPE_VALUE], + ['OscillatorNode', base_config_1.TYPE_VALUE], + ['OverconstrainedError', base_config_1.TYPE_VALUE], + ['PageRevealEvent', base_config_1.TYPE_VALUE], + ['PageSwapEvent', base_config_1.TYPE_VALUE], + ['PageTransitionEvent', base_config_1.TYPE_VALUE], + ['PaintTimingMixin', base_config_1.TYPE], + ['PannerNode', base_config_1.TYPE_VALUE], + ['ParentNode', base_config_1.TYPE], + ['Path2D', base_config_1.TYPE_VALUE], + ['PaymentAddress', base_config_1.TYPE_VALUE], + ['PaymentMethodChangeEvent', base_config_1.TYPE_VALUE], + ['PaymentRequestEventMap', base_config_1.TYPE], + ['PaymentRequest', base_config_1.TYPE_VALUE], + ['PaymentRequestUpdateEvent', base_config_1.TYPE_VALUE], + ['PaymentResponseEventMap', base_config_1.TYPE], + ['PaymentResponse', base_config_1.TYPE_VALUE], + ['PerformanceEventMap', base_config_1.TYPE], + ['Performance', base_config_1.TYPE_VALUE], + ['PerformanceEntry', base_config_1.TYPE_VALUE], + ['PerformanceEventTiming', base_config_1.TYPE_VALUE], + ['PerformanceMark', base_config_1.TYPE_VALUE], + ['PerformanceMeasure', base_config_1.TYPE_VALUE], + ['PerformanceNavigation', base_config_1.TYPE_VALUE], + ['PerformanceNavigationTiming', base_config_1.TYPE_VALUE], + ['PerformanceObserver', base_config_1.TYPE_VALUE], + ['PerformanceObserverEntryList', base_config_1.TYPE_VALUE], + ['PerformancePaintTiming', base_config_1.TYPE_VALUE], + ['PerformanceResourceTiming', base_config_1.TYPE_VALUE], + ['PerformanceServerTiming', base_config_1.TYPE_VALUE], + ['PerformanceTiming', base_config_1.TYPE_VALUE], + ['PeriodicWave', base_config_1.TYPE_VALUE], + ['PermissionStatusEventMap', base_config_1.TYPE], + ['PermissionStatus', base_config_1.TYPE_VALUE], + ['Permissions', base_config_1.TYPE_VALUE], + ['PictureInPictureEvent', base_config_1.TYPE_VALUE], + ['PictureInPictureWindowEventMap', base_config_1.TYPE], + ['PictureInPictureWindow', base_config_1.TYPE_VALUE], + ['Plugin', base_config_1.TYPE_VALUE], + ['PluginArray', base_config_1.TYPE_VALUE], + ['PointerEvent', base_config_1.TYPE_VALUE], + ['PopStateEvent', base_config_1.TYPE_VALUE], + ['PopoverTargetAttributes', base_config_1.TYPE], + ['ProcessingInstruction', base_config_1.TYPE_VALUE], + ['ProgressEvent', base_config_1.TYPE_VALUE], + ['PromiseRejectionEvent', base_config_1.TYPE_VALUE], + ['PublicKeyCredential', base_config_1.TYPE_VALUE], + ['PushManager', base_config_1.TYPE_VALUE], + ['PushManagerAttribute', base_config_1.TYPE], + ['PushSubscription', base_config_1.TYPE_VALUE], + ['PushSubscriptionOptions', base_config_1.TYPE_VALUE], + ['RTCCertificate', base_config_1.TYPE_VALUE], + ['RTCDTMFSenderEventMap', base_config_1.TYPE], + ['RTCDTMFSender', base_config_1.TYPE_VALUE], + ['RTCDTMFToneChangeEvent', base_config_1.TYPE_VALUE], + ['RTCDataChannelEventMap', base_config_1.TYPE], + ['RTCDataChannel', base_config_1.TYPE_VALUE], + ['RTCDataChannelEvent', base_config_1.TYPE_VALUE], + ['RTCDtlsTransportEventMap', base_config_1.TYPE], + ['RTCDtlsTransport', base_config_1.TYPE_VALUE], + ['RTCEncodedAudioFrame', base_config_1.TYPE_VALUE], + ['RTCEncodedVideoFrame', base_config_1.TYPE_VALUE], + ['RTCError', base_config_1.TYPE_VALUE], + ['RTCErrorEvent', base_config_1.TYPE_VALUE], + ['RTCIceCandidate', base_config_1.TYPE_VALUE], + ['RTCIceCandidatePair', base_config_1.TYPE], + ['RTCIceTransportEventMap', base_config_1.TYPE], + ['RTCIceTransport', base_config_1.TYPE_VALUE], + ['RTCPeerConnectionEventMap', base_config_1.TYPE], + ['RTCPeerConnection', base_config_1.TYPE_VALUE], + ['RTCPeerConnectionIceErrorEvent', base_config_1.TYPE_VALUE], + ['RTCPeerConnectionIceEvent', base_config_1.TYPE_VALUE], + ['RTCRtpReceiver', base_config_1.TYPE_VALUE], + ['RTCRtpScriptTransform', base_config_1.TYPE_VALUE], + ['RTCRtpSender', base_config_1.TYPE_VALUE], + ['RTCRtpTransceiver', base_config_1.TYPE_VALUE], + ['RTCSctpTransportEventMap', base_config_1.TYPE], + ['RTCSctpTransport', base_config_1.TYPE_VALUE], + ['RTCSessionDescription', base_config_1.TYPE_VALUE], + ['RTCStatsReport', base_config_1.TYPE_VALUE], + ['RTCTrackEvent', base_config_1.TYPE_VALUE], + ['RadioNodeList', base_config_1.TYPE_VALUE], + ['Range', base_config_1.TYPE_VALUE], + ['ReadableByteStreamController', base_config_1.TYPE_VALUE], + ['ReadableStream', base_config_1.TYPE_VALUE], + ['ReadableStreamBYOBReader', base_config_1.TYPE_VALUE], + ['ReadableStreamBYOBRequest', base_config_1.TYPE_VALUE], + ['ReadableStreamDefaultController', base_config_1.TYPE_VALUE], + ['ReadableStreamDefaultReader', base_config_1.TYPE_VALUE], + ['ReadableStreamGenericReader', base_config_1.TYPE], + ['RemotePlaybackEventMap', base_config_1.TYPE], + ['RemotePlayback', base_config_1.TYPE_VALUE], + ['ReportingObserver', base_config_1.TYPE_VALUE], + ['Request', base_config_1.TYPE_VALUE], + ['ResizeObserver', base_config_1.TYPE_VALUE], + ['ResizeObserverEntry', base_config_1.TYPE_VALUE], + ['ResizeObserverSize', base_config_1.TYPE_VALUE], + ['Response', base_config_1.TYPE_VALUE], + ['SVGAElement', base_config_1.TYPE_VALUE], + ['SVGAngle', base_config_1.TYPE_VALUE], + ['SVGAnimateElement', base_config_1.TYPE_VALUE], + ['SVGAnimateMotionElement', base_config_1.TYPE_VALUE], + ['SVGAnimateTransformElement', base_config_1.TYPE_VALUE], + ['SVGAnimatedAngle', base_config_1.TYPE_VALUE], + ['SVGAnimatedBoolean', base_config_1.TYPE_VALUE], + ['SVGAnimatedEnumeration', base_config_1.TYPE_VALUE], + ['SVGAnimatedInteger', base_config_1.TYPE_VALUE], + ['SVGAnimatedLength', base_config_1.TYPE_VALUE], + ['SVGAnimatedLengthList', base_config_1.TYPE_VALUE], + ['SVGAnimatedNumber', base_config_1.TYPE_VALUE], + ['SVGAnimatedNumberList', base_config_1.TYPE_VALUE], + ['SVGAnimatedPoints', base_config_1.TYPE], + ['SVGAnimatedPreserveAspectRatio', base_config_1.TYPE_VALUE], + ['SVGAnimatedRect', base_config_1.TYPE_VALUE], + ['SVGAnimatedString', base_config_1.TYPE_VALUE], + ['SVGAnimatedTransformList', base_config_1.TYPE_VALUE], + ['SVGAnimationElement', base_config_1.TYPE_VALUE], + ['SVGCircleElement', base_config_1.TYPE_VALUE], + ['SVGClipPathElement', base_config_1.TYPE_VALUE], + ['SVGComponentTransferFunctionElement', base_config_1.TYPE_VALUE], + ['SVGDefsElement', base_config_1.TYPE_VALUE], + ['SVGDescElement', base_config_1.TYPE_VALUE], + ['SVGElementEventMap', base_config_1.TYPE], + ['SVGElement', base_config_1.TYPE_VALUE], + ['SVGEllipseElement', base_config_1.TYPE_VALUE], + ['SVGFEBlendElement', base_config_1.TYPE_VALUE], + ['SVGFEColorMatrixElement', base_config_1.TYPE_VALUE], + ['SVGFEComponentTransferElement', base_config_1.TYPE_VALUE], + ['SVGFECompositeElement', base_config_1.TYPE_VALUE], + ['SVGFEConvolveMatrixElement', base_config_1.TYPE_VALUE], + ['SVGFEDiffuseLightingElement', base_config_1.TYPE_VALUE], + ['SVGFEDisplacementMapElement', base_config_1.TYPE_VALUE], + ['SVGFEDistantLightElement', base_config_1.TYPE_VALUE], + ['SVGFEDropShadowElement', base_config_1.TYPE_VALUE], + ['SVGFEFloodElement', base_config_1.TYPE_VALUE], + ['SVGFEFuncAElement', base_config_1.TYPE_VALUE], + ['SVGFEFuncBElement', base_config_1.TYPE_VALUE], + ['SVGFEFuncGElement', base_config_1.TYPE_VALUE], + ['SVGFEFuncRElement', base_config_1.TYPE_VALUE], + ['SVGFEGaussianBlurElement', base_config_1.TYPE_VALUE], + ['SVGFEImageElement', base_config_1.TYPE_VALUE], + ['SVGFEMergeElement', base_config_1.TYPE_VALUE], + ['SVGFEMergeNodeElement', base_config_1.TYPE_VALUE], + ['SVGFEMorphologyElement', base_config_1.TYPE_VALUE], + ['SVGFEOffsetElement', base_config_1.TYPE_VALUE], + ['SVGFEPointLightElement', base_config_1.TYPE_VALUE], + ['SVGFESpecularLightingElement', base_config_1.TYPE_VALUE], + ['SVGFESpotLightElement', base_config_1.TYPE_VALUE], + ['SVGFETileElement', base_config_1.TYPE_VALUE], + ['SVGFETurbulenceElement', base_config_1.TYPE_VALUE], + ['SVGFilterElement', base_config_1.TYPE_VALUE], + ['SVGFilterPrimitiveStandardAttributes', base_config_1.TYPE], + ['SVGFitToViewBox', base_config_1.TYPE], + ['SVGForeignObjectElement', base_config_1.TYPE_VALUE], + ['SVGGElement', base_config_1.TYPE_VALUE], + ['SVGGeometryElement', base_config_1.TYPE_VALUE], + ['SVGGradientElement', base_config_1.TYPE_VALUE], + ['SVGGraphicsElement', base_config_1.TYPE_VALUE], + ['SVGImageElement', base_config_1.TYPE_VALUE], + ['SVGLength', base_config_1.TYPE_VALUE], + ['SVGLengthList', base_config_1.TYPE_VALUE], + ['SVGLineElement', base_config_1.TYPE_VALUE], + ['SVGLinearGradientElement', base_config_1.TYPE_VALUE], + ['SVGMPathElement', base_config_1.TYPE_VALUE], + ['SVGMarkerElement', base_config_1.TYPE_VALUE], + ['SVGMaskElement', base_config_1.TYPE_VALUE], + ['SVGMetadataElement', base_config_1.TYPE_VALUE], + ['SVGNumber', base_config_1.TYPE_VALUE], + ['SVGNumberList', base_config_1.TYPE_VALUE], + ['SVGPathElement', base_config_1.TYPE_VALUE], + ['SVGPatternElement', base_config_1.TYPE_VALUE], + ['SVGPointList', base_config_1.TYPE_VALUE], + ['SVGPolygonElement', base_config_1.TYPE_VALUE], + ['SVGPolylineElement', base_config_1.TYPE_VALUE], + ['SVGPreserveAspectRatio', base_config_1.TYPE_VALUE], + ['SVGRadialGradientElement', base_config_1.TYPE_VALUE], + ['SVGRectElement', base_config_1.TYPE_VALUE], + ['SVGSVGElementEventMap', base_config_1.TYPE], + ['SVGSVGElement', base_config_1.TYPE_VALUE], + ['SVGScriptElement', base_config_1.TYPE_VALUE], + ['SVGSetElement', base_config_1.TYPE_VALUE], + ['SVGStopElement', base_config_1.TYPE_VALUE], + ['SVGStringList', base_config_1.TYPE_VALUE], + ['SVGStyleElement', base_config_1.TYPE_VALUE], + ['SVGSwitchElement', base_config_1.TYPE_VALUE], + ['SVGSymbolElement', base_config_1.TYPE_VALUE], + ['SVGTSpanElement', base_config_1.TYPE_VALUE], + ['SVGTests', base_config_1.TYPE], + ['SVGTextContentElement', base_config_1.TYPE_VALUE], + ['SVGTextElement', base_config_1.TYPE_VALUE], + ['SVGTextPathElement', base_config_1.TYPE_VALUE], + ['SVGTextPositioningElement', base_config_1.TYPE_VALUE], + ['SVGTitleElement', base_config_1.TYPE_VALUE], + ['SVGTransform', base_config_1.TYPE_VALUE], + ['SVGTransformList', base_config_1.TYPE_VALUE], + ['SVGURIReference', base_config_1.TYPE], + ['SVGUnitTypes', base_config_1.TYPE_VALUE], + ['SVGUseElement', base_config_1.TYPE_VALUE], + ['SVGViewElement', base_config_1.TYPE_VALUE], + ['Sanitizer', base_config_1.TYPE_VALUE], + ['Scheduler', base_config_1.TYPE_VALUE], + ['Screen', base_config_1.TYPE_VALUE], + ['ScreenOrientationEventMap', base_config_1.TYPE], + ['ScreenOrientation', base_config_1.TYPE_VALUE], + ['ScriptProcessorNodeEventMap', base_config_1.TYPE], + ['ScriptProcessorNode', base_config_1.TYPE_VALUE], + ['ScrollTimeline', base_config_1.TYPE_VALUE], + ['SecurityPolicyViolationEvent', base_config_1.TYPE_VALUE], + ['Selection', base_config_1.TYPE_VALUE], + ['ServiceWorkerEventMap', base_config_1.TYPE], + ['ServiceWorker', base_config_1.TYPE_VALUE], + ['ServiceWorkerContainerEventMap', base_config_1.TYPE], + ['ServiceWorkerContainer', base_config_1.TYPE_VALUE], + ['ServiceWorkerRegistrationEventMap', base_config_1.TYPE], + ['ServiceWorkerRegistration', base_config_1.TYPE_VALUE], + ['ShadowRootEventMap', base_config_1.TYPE], + ['ShadowRoot', base_config_1.TYPE_VALUE], + ['SharedWorker', base_config_1.TYPE_VALUE], + ['Slottable', base_config_1.TYPE], + ['SourceBufferEventMap', base_config_1.TYPE], + ['SourceBuffer', base_config_1.TYPE_VALUE], + ['SourceBufferListEventMap', base_config_1.TYPE], + ['SourceBufferList', base_config_1.TYPE_VALUE], + ['SpeechRecognitionAlternative', base_config_1.TYPE_VALUE], + ['SpeechRecognitionErrorEvent', base_config_1.TYPE_VALUE], + ['SpeechRecognitionEvent', base_config_1.TYPE_VALUE], + ['SpeechRecognitionResult', base_config_1.TYPE_VALUE], + ['SpeechRecognitionResultList', base_config_1.TYPE_VALUE], + ['SpeechSynthesisEventMap', base_config_1.TYPE], + ['SpeechSynthesis', base_config_1.TYPE_VALUE], + ['SpeechSynthesisErrorEvent', base_config_1.TYPE_VALUE], + ['SpeechSynthesisEvent', base_config_1.TYPE_VALUE], + ['SpeechSynthesisUtteranceEventMap', base_config_1.TYPE], + ['SpeechSynthesisUtterance', base_config_1.TYPE_VALUE], + ['SpeechSynthesisVoice', base_config_1.TYPE_VALUE], + ['StaticRange', base_config_1.TYPE_VALUE], + ['StereoPannerNode', base_config_1.TYPE_VALUE], + ['Storage', base_config_1.TYPE_VALUE], + ['StorageEvent', base_config_1.TYPE_VALUE], + ['StorageManager', base_config_1.TYPE_VALUE], + ['StylePropertyMap', base_config_1.TYPE_VALUE], + ['StylePropertyMapReadOnly', base_config_1.TYPE_VALUE], + ['StyleSheet', base_config_1.TYPE_VALUE], + ['StyleSheetList', base_config_1.TYPE_VALUE], + ['SubmitEvent', base_config_1.TYPE_VALUE], + ['SubtleCrypto', base_config_1.TYPE_VALUE], + ['TaskController', base_config_1.TYPE_VALUE], + ['TaskPriorityChangeEvent', base_config_1.TYPE_VALUE], + ['TaskSignalEventMap', base_config_1.TYPE], + ['TaskSignal', base_config_1.TYPE_VALUE], + ['Text', base_config_1.TYPE_VALUE], + ['TextDecoder', base_config_1.TYPE_VALUE], + ['TextDecoderCommon', base_config_1.TYPE], + ['TextDecoderStream', base_config_1.TYPE_VALUE], + ['TextEncoder', base_config_1.TYPE_VALUE], + ['TextEncoderCommon', base_config_1.TYPE], + ['TextEncoderStream', base_config_1.TYPE_VALUE], + ['TextEvent', base_config_1.TYPE_VALUE], + ['TextMetrics', base_config_1.TYPE_VALUE], + ['TextTrackEventMap', base_config_1.TYPE], + ['TextTrack', base_config_1.TYPE_VALUE], + ['TextTrackCueEventMap', base_config_1.TYPE], + ['TextTrackCue', base_config_1.TYPE_VALUE], + ['TextTrackCueList', base_config_1.TYPE_VALUE], + ['TextTrackListEventMap', base_config_1.TYPE], + ['TextTrackList', base_config_1.TYPE_VALUE], + ['TimeRanges', base_config_1.TYPE_VALUE], + ['ToggleEvent', base_config_1.TYPE_VALUE], + ['Touch', base_config_1.TYPE_VALUE], + ['TouchEvent', base_config_1.TYPE_VALUE], + ['TouchList', base_config_1.TYPE_VALUE], + ['TrackEvent', base_config_1.TYPE_VALUE], + ['TransformStream', base_config_1.TYPE_VALUE], + ['TransformStreamDefaultController', base_config_1.TYPE_VALUE], + ['TransitionEvent', base_config_1.TYPE_VALUE], + ['TreeWalker', base_config_1.TYPE_VALUE], + ['UIEvent', base_config_1.TYPE_VALUE], + ['URL', base_config_1.TYPE_VALUE], + ['webkitURL', base_config_1.TYPE_VALUE], + ['URLPattern', base_config_1.TYPE_VALUE], + ['URLSearchParams', base_config_1.TYPE_VALUE], + ['UserActivation', base_config_1.TYPE_VALUE], + ['VTTCue', base_config_1.TYPE_VALUE], + ['VTTRegion', base_config_1.TYPE_VALUE], + ['ValidityState', base_config_1.TYPE_VALUE], + ['VideoColorSpace', base_config_1.TYPE_VALUE], + ['VideoDecoderEventMap', base_config_1.TYPE], + ['VideoDecoder', base_config_1.TYPE_VALUE], + ['VideoEncoderEventMap', base_config_1.TYPE], + ['VideoEncoder', base_config_1.TYPE_VALUE], + ['VideoFrame', base_config_1.TYPE_VALUE], + ['VideoPlaybackQuality', base_config_1.TYPE_VALUE], + ['ViewTimeline', base_config_1.TYPE_VALUE], + ['ViewTransition', base_config_1.TYPE_VALUE], + ['ViewTransitionTypeSet', base_config_1.TYPE_VALUE], + ['VisualViewportEventMap', base_config_1.TYPE], + ['VisualViewport', base_config_1.TYPE_VALUE], + ['WEBGL_color_buffer_float', base_config_1.TYPE], + ['WEBGL_compressed_texture_astc', base_config_1.TYPE], + ['WEBGL_compressed_texture_etc', base_config_1.TYPE], + ['WEBGL_compressed_texture_etc1', base_config_1.TYPE], + ['WEBGL_compressed_texture_pvrtc', base_config_1.TYPE], + ['WEBGL_compressed_texture_s3tc', base_config_1.TYPE], + ['WEBGL_compressed_texture_s3tc_srgb', base_config_1.TYPE], + ['WEBGL_debug_renderer_info', base_config_1.TYPE], + ['WEBGL_debug_shaders', base_config_1.TYPE], + ['WEBGL_depth_texture', base_config_1.TYPE], + ['WEBGL_draw_buffers', base_config_1.TYPE], + ['WEBGL_lose_context', base_config_1.TYPE], + ['WEBGL_multi_draw', base_config_1.TYPE], + ['WGSLLanguageFeatures', base_config_1.TYPE_VALUE], + ['WakeLock', base_config_1.TYPE_VALUE], + ['WakeLockSentinelEventMap', base_config_1.TYPE], + ['WakeLockSentinel', base_config_1.TYPE_VALUE], + ['WaveShaperNode', base_config_1.TYPE_VALUE], + ['WebGL2RenderingContext', base_config_1.TYPE_VALUE], + ['WebGL2RenderingContextBase', base_config_1.TYPE], + ['WebGL2RenderingContextOverloads', base_config_1.TYPE], + ['WebGLActiveInfo', base_config_1.TYPE_VALUE], + ['WebGLBuffer', base_config_1.TYPE_VALUE], + ['WebGLContextEvent', base_config_1.TYPE_VALUE], + ['WebGLFramebuffer', base_config_1.TYPE_VALUE], + ['WebGLProgram', base_config_1.TYPE_VALUE], + ['WebGLQuery', base_config_1.TYPE_VALUE], + ['WebGLRenderbuffer', base_config_1.TYPE_VALUE], + ['WebGLRenderingContext', base_config_1.TYPE_VALUE], + ['WebGLRenderingContextBase', base_config_1.TYPE], + ['WebGLRenderingContextOverloads', base_config_1.TYPE], + ['WebGLSampler', base_config_1.TYPE_VALUE], + ['WebGLShader', base_config_1.TYPE_VALUE], + ['WebGLShaderPrecisionFormat', base_config_1.TYPE_VALUE], + ['WebGLSync', base_config_1.TYPE_VALUE], + ['WebGLTexture', base_config_1.TYPE_VALUE], + ['WebGLTransformFeedback', base_config_1.TYPE_VALUE], + ['WebGLUniformLocation', base_config_1.TYPE_VALUE], + ['WebGLVertexArrayObject', base_config_1.TYPE_VALUE], + ['WebGLVertexArrayObjectOES', base_config_1.TYPE], + ['WebSocketEventMap', base_config_1.TYPE], + ['WebSocket', base_config_1.TYPE_VALUE], + ['WebTransport', base_config_1.TYPE_VALUE], + ['WebTransportBidirectionalStream', base_config_1.TYPE_VALUE], + ['WebTransportDatagramDuplexStream', base_config_1.TYPE_VALUE], + ['WebTransportError', base_config_1.TYPE_VALUE], + ['WheelEvent', base_config_1.TYPE_VALUE], + ['WindowEventMap', base_config_1.TYPE], + ['Window', base_config_1.TYPE_VALUE], + ['WindowEventHandlersEventMap', base_config_1.TYPE], + ['WindowEventHandlers', base_config_1.TYPE], + ['WindowLocalStorage', base_config_1.TYPE], + ['WindowOrWorkerGlobalScope', base_config_1.TYPE], + ['WindowSessionStorage', base_config_1.TYPE], + ['WorkerEventMap', base_config_1.TYPE], + ['Worker', base_config_1.TYPE_VALUE], + ['Worklet', base_config_1.TYPE_VALUE], + ['WritableStream', base_config_1.TYPE_VALUE], + ['WritableStreamDefaultController', base_config_1.TYPE_VALUE], + ['WritableStreamDefaultWriter', base_config_1.TYPE_VALUE], + ['XMLDocument', base_config_1.TYPE_VALUE], + ['XMLHttpRequestEventMap', base_config_1.TYPE], + ['XMLHttpRequest', base_config_1.TYPE_VALUE], + ['XMLHttpRequestEventTargetEventMap', base_config_1.TYPE], + ['XMLHttpRequestEventTarget', base_config_1.TYPE_VALUE], + ['XMLHttpRequestUpload', base_config_1.TYPE_VALUE], + ['XMLSerializer', base_config_1.TYPE_VALUE], + ['XPathEvaluator', base_config_1.TYPE_VALUE], + ['XPathEvaluatorBase', base_config_1.TYPE], + ['XPathExpression', base_config_1.TYPE_VALUE], + ['XPathResult', base_config_1.TYPE_VALUE], + ['XSLTProcessor', base_config_1.TYPE_VALUE], + ['CSS', base_config_1.TYPE_VALUE], + ['WebAssembly', base_config_1.TYPE_VALUE], + ['Console', base_config_1.TYPE], + ['AudioDataOutputCallback', base_config_1.TYPE], + ['BlobCallback', base_config_1.TYPE], + ['CustomElementConstructor', base_config_1.TYPE], + ['DecodeErrorCallback', base_config_1.TYPE], + ['DecodeSuccessCallback', base_config_1.TYPE], + ['EncodedAudioChunkOutputCallback', base_config_1.TYPE], + ['EncodedVideoChunkOutputCallback', base_config_1.TYPE], + ['ErrorCallback', base_config_1.TYPE], + ['FileCallback', base_config_1.TYPE], + ['FileSystemEntriesCallback', base_config_1.TYPE], + ['FileSystemEntryCallback', base_config_1.TYPE], + ['FrameRequestCallback', base_config_1.TYPE], + ['FunctionStringCallback', base_config_1.TYPE], + ['IdleRequestCallback', base_config_1.TYPE], + ['IntersectionObserverCallback', base_config_1.TYPE], + ['LockGrantedCallback', base_config_1.TYPE], + ['MediaSessionActionHandler', base_config_1.TYPE], + ['MutationCallback', base_config_1.TYPE], + ['NavigationInterceptHandler', base_config_1.TYPE], + ['NavigationPrecommitHandler', base_config_1.TYPE], + ['NotificationPermissionCallback', base_config_1.TYPE], + ['OnBeforeUnloadEventHandlerNonNull', base_config_1.TYPE], + ['OnErrorEventHandlerNonNull', base_config_1.TYPE], + ['PerformanceObserverCallback', base_config_1.TYPE], + ['PositionCallback', base_config_1.TYPE], + ['PositionErrorCallback', base_config_1.TYPE], + ['QueuingStrategySize', base_config_1.TYPE], + ['RTCPeerConnectionErrorCallback', base_config_1.TYPE], + ['RTCSessionDescriptionCallback', base_config_1.TYPE], + ['RemotePlaybackAvailabilityCallback', base_config_1.TYPE], + ['ReportingObserverCallback', base_config_1.TYPE], + ['ResizeObserverCallback', base_config_1.TYPE], + ['SchedulerPostTaskCallback', base_config_1.TYPE], + ['TransformerFlushCallback', base_config_1.TYPE], + ['TransformerStartCallback', base_config_1.TYPE], + ['TransformerTransformCallback', base_config_1.TYPE], + ['UnderlyingSinkAbortCallback', base_config_1.TYPE], + ['UnderlyingSinkCloseCallback', base_config_1.TYPE], + ['UnderlyingSinkStartCallback', base_config_1.TYPE], + ['UnderlyingSinkWriteCallback', base_config_1.TYPE], + ['UnderlyingSourceCancelCallback', base_config_1.TYPE], + ['UnderlyingSourcePullCallback', base_config_1.TYPE], + ['UnderlyingSourceStartCallback', base_config_1.TYPE], + ['VideoFrameOutputCallback', base_config_1.TYPE], + ['VideoFrameRequestCallback', base_config_1.TYPE], + ['ViewTransitionUpdateCallback', base_config_1.TYPE], + ['VoidFunction', base_config_1.TYPE], + ['WebCodecsErrorCallback', base_config_1.TYPE], + ['HTMLElementTagNameMap', base_config_1.TYPE], + ['HTMLElementDeprecatedTagNameMap', base_config_1.TYPE], + ['SVGElementTagNameMap', base_config_1.TYPE], + ['MathMLElementTagNameMap', base_config_1.TYPE], + ['ElementTagNameMap', base_config_1.TYPE], + ['AlgorithmIdentifier', base_config_1.TYPE], + ['AllowSharedBufferSource', base_config_1.TYPE], + ['AutoFill', base_config_1.TYPE], + ['AutoFillField', base_config_1.TYPE], + ['AutoFillSection', base_config_1.TYPE], + ['Base64URLString', base_config_1.TYPE], + ['BigInteger', base_config_1.TYPE], + ['BlobPart', base_config_1.TYPE], + ['BodyInit', base_config_1.TYPE], + ['BufferSource', base_config_1.TYPE], + ['COSEAlgorithmIdentifier', base_config_1.TYPE], + ['CSSKeywordish', base_config_1.TYPE], + ['CSSNumberish', base_config_1.TYPE], + ['CSSPerspectiveValue', base_config_1.TYPE], + ['CSSUnparsedSegment', base_config_1.TYPE], + ['CanvasImageSource', base_config_1.TYPE], + ['ClipboardItemData', base_config_1.TYPE], + ['ClipboardItems', base_config_1.TYPE], + ['ConstrainBoolean', base_config_1.TYPE], + ['ConstrainBooleanOrDOMString', base_config_1.TYPE], + ['ConstrainDOMString', base_config_1.TYPE], + ['ConstrainDouble', base_config_1.TYPE], + ['ConstrainULong', base_config_1.TYPE], + ['CookieList', base_config_1.TYPE], + ['DOMHighResTimeStamp', base_config_1.TYPE], + ['EpochTimeStamp', base_config_1.TYPE], + ['EventListenerOrEventListenerObject', base_config_1.TYPE], + ['FileSystemWriteChunkType', base_config_1.TYPE], + ['Float32List', base_config_1.TYPE], + ['FormDataEntryValue', base_config_1.TYPE], + ['GLbitfield', base_config_1.TYPE], + ['GLboolean', base_config_1.TYPE], + ['GLclampf', base_config_1.TYPE], + ['GLenum', base_config_1.TYPE], + ['GLfloat', base_config_1.TYPE], + ['GLint', base_config_1.TYPE], + ['GLint64', base_config_1.TYPE], + ['GLintptr', base_config_1.TYPE], + ['GLsizei', base_config_1.TYPE], + ['GLsizeiptr', base_config_1.TYPE], + ['GLuint', base_config_1.TYPE], + ['GLuint64', base_config_1.TYPE], + ['GPUBindingResource', base_config_1.TYPE], + ['GPUBufferDynamicOffset', base_config_1.TYPE], + ['GPUBufferUsageFlags', base_config_1.TYPE], + ['GPUColor', base_config_1.TYPE], + ['GPUColorWriteFlags', base_config_1.TYPE], + ['GPUCopyExternalImageSource', base_config_1.TYPE], + ['GPUDepthBias', base_config_1.TYPE], + ['GPUExtent3D', base_config_1.TYPE], + ['GPUFlagsConstant', base_config_1.TYPE], + ['GPUIndex32', base_config_1.TYPE], + ['GPUIntegerCoordinate', base_config_1.TYPE], + ['GPUIntegerCoordinateOut', base_config_1.TYPE], + ['GPUMapModeFlags', base_config_1.TYPE], + ['GPUOrigin2D', base_config_1.TYPE], + ['GPUOrigin3D', base_config_1.TYPE], + ['GPUPipelineConstantValue', base_config_1.TYPE], + ['GPUSampleMask', base_config_1.TYPE], + ['GPUShaderStageFlags', base_config_1.TYPE], + ['GPUSignedOffset32', base_config_1.TYPE], + ['GPUSize32', base_config_1.TYPE], + ['GPUSize32Out', base_config_1.TYPE], + ['GPUSize64', base_config_1.TYPE], + ['GPUSize64Out', base_config_1.TYPE], + ['GPUStencilValue', base_config_1.TYPE], + ['GPUTextureUsageFlags', base_config_1.TYPE], + ['HTMLOrSVGImageElement', base_config_1.TYPE], + ['HTMLOrSVGScriptElement', base_config_1.TYPE], + ['HashAlgorithmIdentifier', base_config_1.TYPE], + ['HeadersInit', base_config_1.TYPE], + ['IDBValidKey', base_config_1.TYPE], + ['ImageBitmapSource', base_config_1.TYPE], + ['ImageBufferSource', base_config_1.TYPE], + ['ImageDataArray', base_config_1.TYPE], + ['Int32List', base_config_1.TYPE], + ['LineAndPositionSetting', base_config_1.TYPE], + ['MediaProvider', base_config_1.TYPE], + ['MessageEventSource', base_config_1.TYPE], + ['MutationRecordType', base_config_1.TYPE], + ['NamedCurve', base_config_1.TYPE], + ['OffscreenRenderingContext', base_config_1.TYPE], + ['OnBeforeUnloadEventHandler', base_config_1.TYPE], + ['OnErrorEventHandler', base_config_1.TYPE], + ['OptionalPostfixToken', base_config_1.TYPE], + ['OptionalPrefixToken', base_config_1.TYPE], + ['PerformanceEntryList', base_config_1.TYPE], + ['PublicKeyCredentialClientCapabilities', base_config_1.TYPE], + ['RTCRtpReceiverTransform', base_config_1.TYPE], + ['RTCRtpSenderTransform', base_config_1.TYPE], + ['ReadableStreamController', base_config_1.TYPE], + ['ReadableStreamReadResult', base_config_1.TYPE], + ['ReadableStreamReader', base_config_1.TYPE], + ['RenderingContext', base_config_1.TYPE], + ['ReportList', base_config_1.TYPE], + ['RequestInfo', base_config_1.TYPE], + ['SanitizerAttribute', base_config_1.TYPE], + ['SanitizerElement', base_config_1.TYPE], + ['SanitizerElementWithAttributes', base_config_1.TYPE], + ['SelectionDirection', base_config_1.TYPE], + ['TexImageSource', base_config_1.TYPE], + ['TimerHandler', base_config_1.TYPE], + ['Transferable', base_config_1.TYPE], + ['URLPatternInput', base_config_1.TYPE], + ['Uint32List', base_config_1.TYPE], + ['VibratePattern', base_config_1.TYPE], + ['WindowProxy', base_config_1.TYPE], + ['XMLHttpRequestBodyInit', base_config_1.TYPE], + ['AacBitstreamFormat', base_config_1.TYPE], + ['AlignSetting', base_config_1.TYPE], + ['AlphaOption', base_config_1.TYPE], + ['AnimationPlayState', base_config_1.TYPE], + ['AnimationReplaceState', base_config_1.TYPE], + ['AppendMode', base_config_1.TYPE], + ['AttestationConveyancePreference', base_config_1.TYPE], + ['AudioContextLatencyCategory', base_config_1.TYPE], + ['AudioContextState', base_config_1.TYPE], + ['AudioSampleFormat', base_config_1.TYPE], + ['AuthenticatorAttachment', base_config_1.TYPE], + ['AuthenticatorTransport', base_config_1.TYPE], + ['AutoFillAddressKind', base_config_1.TYPE], + ['AutoFillBase', base_config_1.TYPE], + ['AutoFillContactField', base_config_1.TYPE], + ['AutoFillContactKind', base_config_1.TYPE], + ['AutoFillCredentialField', base_config_1.TYPE], + ['AutoFillNormalField', base_config_1.TYPE], + ['AutoKeyword', base_config_1.TYPE], + ['AutomationRate', base_config_1.TYPE], + ['AvcBitstreamFormat', base_config_1.TYPE], + ['BinaryType', base_config_1.TYPE], + ['BiquadFilterType', base_config_1.TYPE], + ['BitrateMode', base_config_1.TYPE], + ['CSSMathOperator', base_config_1.TYPE], + ['CSSNumericBaseType', base_config_1.TYPE], + ['CanPlayTypeResult', base_config_1.TYPE], + ['CanvasDirection', base_config_1.TYPE], + ['CanvasFillRule', base_config_1.TYPE], + ['CanvasFontKerning', base_config_1.TYPE], + ['CanvasFontStretch', base_config_1.TYPE], + ['CanvasFontVariantCaps', base_config_1.TYPE], + ['CanvasLineCap', base_config_1.TYPE], + ['CanvasLineJoin', base_config_1.TYPE], + ['CanvasTextAlign', base_config_1.TYPE], + ['CanvasTextBaseline', base_config_1.TYPE], + ['CanvasTextRendering', base_config_1.TYPE], + ['ChannelCountMode', base_config_1.TYPE], + ['ChannelInterpretation', base_config_1.TYPE], + ['ClientTypes', base_config_1.TYPE], + ['CodecState', base_config_1.TYPE], + ['ColorGamut', base_config_1.TYPE], + ['ColorSpaceConversion', base_config_1.TYPE], + ['CompositeOperation', base_config_1.TYPE], + ['CompositeOperationOrAuto', base_config_1.TYPE], + ['CompressionFormat', base_config_1.TYPE], + ['CookieSameSite', base_config_1.TYPE], + ['CredentialMediationRequirement', base_config_1.TYPE], + ['DOMParserSupportedType', base_config_1.TYPE], + ['DirectionSetting', base_config_1.TYPE], + ['DisplayCaptureSurfaceType', base_config_1.TYPE], + ['DistanceModelType', base_config_1.TYPE], + ['DocumentReadyState', base_config_1.TYPE], + ['DocumentVisibilityState', base_config_1.TYPE], + ['EncodedAudioChunkType', base_config_1.TYPE], + ['EncodedVideoChunkType', base_config_1.TYPE], + ['EndOfStreamError', base_config_1.TYPE], + ['EndingType', base_config_1.TYPE], + ['FileSystemHandleKind', base_config_1.TYPE], + ['FillLightMode', base_config_1.TYPE], + ['FillMode', base_config_1.TYPE], + ['FontDisplay', base_config_1.TYPE], + ['FontFaceLoadStatus', base_config_1.TYPE], + ['FontFaceSetLoadStatus', base_config_1.TYPE], + ['FullscreenNavigationUI', base_config_1.TYPE], + ['GPUAddressMode', base_config_1.TYPE], + ['GPUAutoLayoutMode', base_config_1.TYPE], + ['GPUBlendFactor', base_config_1.TYPE], + ['GPUBlendOperation', base_config_1.TYPE], + ['GPUBufferBindingType', base_config_1.TYPE], + ['GPUBufferMapState', base_config_1.TYPE], + ['GPUCanvasAlphaMode', base_config_1.TYPE], + ['GPUCanvasToneMappingMode', base_config_1.TYPE], + ['GPUCompareFunction', base_config_1.TYPE], + ['GPUCompilationMessageType', base_config_1.TYPE], + ['GPUCullMode', base_config_1.TYPE], + ['GPUDeviceLostReason', base_config_1.TYPE], + ['GPUErrorFilter', base_config_1.TYPE], + ['GPUFeatureName', base_config_1.TYPE], + ['GPUFilterMode', base_config_1.TYPE], + ['GPUFrontFace', base_config_1.TYPE], + ['GPUIndexFormat', base_config_1.TYPE], + ['GPULoadOp', base_config_1.TYPE], + ['GPUMipmapFilterMode', base_config_1.TYPE], + ['GPUPipelineErrorReason', base_config_1.TYPE], + ['GPUPowerPreference', base_config_1.TYPE], + ['GPUPrimitiveTopology', base_config_1.TYPE], + ['GPUQueryType', base_config_1.TYPE], + ['GPUSamplerBindingType', base_config_1.TYPE], + ['GPUStencilOperation', base_config_1.TYPE], + ['GPUStorageTextureAccess', base_config_1.TYPE], + ['GPUStoreOp', base_config_1.TYPE], + ['GPUTextureAspect', base_config_1.TYPE], + ['GPUTextureDimension', base_config_1.TYPE], + ['GPUTextureFormat', base_config_1.TYPE], + ['GPUTextureSampleType', base_config_1.TYPE], + ['GPUTextureViewDimension', base_config_1.TYPE], + ['GPUVertexFormat', base_config_1.TYPE], + ['GPUVertexStepMode', base_config_1.TYPE], + ['GamepadHapticEffectType', base_config_1.TYPE], + ['GamepadHapticsResult', base_config_1.TYPE], + ['GamepadMappingType', base_config_1.TYPE], + ['GlobalCompositeOperation', base_config_1.TYPE], + ['HardwareAcceleration', base_config_1.TYPE], + ['HdrMetadataType', base_config_1.TYPE], + ['HighlightType', base_config_1.TYPE], + ['IDBCursorDirection', base_config_1.TYPE], + ['IDBRequestReadyState', base_config_1.TYPE], + ['IDBTransactionDurability', base_config_1.TYPE], + ['IDBTransactionMode', base_config_1.TYPE], + ['ImageDataPixelFormat', base_config_1.TYPE], + ['ImageOrientation', base_config_1.TYPE], + ['ImageSmoothingQuality', base_config_1.TYPE], + ['InsertPosition', base_config_1.TYPE], + ['IterationCompositeOperation', base_config_1.TYPE], + ['KeyFormat', base_config_1.TYPE], + ['KeyType', base_config_1.TYPE], + ['KeyUsage', base_config_1.TYPE], + ['LatencyMode', base_config_1.TYPE], + ['LineAlignSetting', base_config_1.TYPE], + ['LockMode', base_config_1.TYPE], + ['LoginStatus', base_config_1.TYPE], + ['MIDIPortConnectionState', base_config_1.TYPE], + ['MIDIPortDeviceState', base_config_1.TYPE], + ['MIDIPortType', base_config_1.TYPE], + ['MediaDecodingType', base_config_1.TYPE], + ['MediaDeviceKind', base_config_1.TYPE], + ['MediaEncodingType', base_config_1.TYPE], + ['MediaKeyMessageType', base_config_1.TYPE], + ['MediaKeySessionClosedReason', base_config_1.TYPE], + ['MediaKeySessionType', base_config_1.TYPE], + ['MediaKeyStatus', base_config_1.TYPE], + ['MediaKeysRequirement', base_config_1.TYPE], + ['MediaSessionAction', base_config_1.TYPE], + ['MediaSessionPlaybackState', base_config_1.TYPE], + ['MediaStreamTrackState', base_config_1.TYPE], + ['NavigationFocusReset', base_config_1.TYPE], + ['NavigationHistoryBehavior', base_config_1.TYPE], + ['NavigationScrollBehavior', base_config_1.TYPE], + ['NavigationTimingType', base_config_1.TYPE], + ['NavigationType', base_config_1.TYPE], + ['NotificationDirection', base_config_1.TYPE], + ['NotificationPermission', base_config_1.TYPE], + ['OffscreenRenderingContextId', base_config_1.TYPE], + ['OpusBitstreamFormat', base_config_1.TYPE], + ['OrientationLockType', base_config_1.TYPE], + ['OrientationType', base_config_1.TYPE], + ['OscillatorType', base_config_1.TYPE], + ['OverSampleType', base_config_1.TYPE], + ['PanningModelType', base_config_1.TYPE], + ['PaymentComplete', base_config_1.TYPE], + ['PaymentShippingType', base_config_1.TYPE], + ['PermissionName', base_config_1.TYPE], + ['PermissionState', base_config_1.TYPE], + ['PlaybackDirection', base_config_1.TYPE], + ['PositionAlignSetting', base_config_1.TYPE], + ['PredefinedColorSpace', base_config_1.TYPE], + ['PremultiplyAlpha', base_config_1.TYPE], + ['PresentationStyle', base_config_1.TYPE], + ['PublicKeyCredentialType', base_config_1.TYPE], + ['PushEncryptionKeyName', base_config_1.TYPE], + ['RTCBundlePolicy', base_config_1.TYPE], + ['RTCDataChannelState', base_config_1.TYPE], + ['RTCDegradationPreference', base_config_1.TYPE], + ['RTCDtlsRole', base_config_1.TYPE], + ['RTCDtlsTransportState', base_config_1.TYPE], + ['RTCErrorDetailType', base_config_1.TYPE], + ['RTCIceCandidateType', base_config_1.TYPE], + ['RTCIceComponent', base_config_1.TYPE], + ['RTCIceConnectionState', base_config_1.TYPE], + ['RTCIceGathererState', base_config_1.TYPE], + ['RTCIceGatheringState', base_config_1.TYPE], + ['RTCIceProtocol', base_config_1.TYPE], + ['RTCIceRole', base_config_1.TYPE], + ['RTCIceTcpCandidateType', base_config_1.TYPE], + ['RTCIceTransportPolicy', base_config_1.TYPE], + ['RTCIceTransportState', base_config_1.TYPE], + ['RTCPeerConnectionState', base_config_1.TYPE], + ['RTCPriorityType', base_config_1.TYPE], + ['RTCQualityLimitationReason', base_config_1.TYPE], + ['RTCRtcpMuxPolicy', base_config_1.TYPE], + ['RTCRtpTransceiverDirection', base_config_1.TYPE], + ['RTCSctpTransportState', base_config_1.TYPE], + ['RTCSdpType', base_config_1.TYPE], + ['RTCSignalingState', base_config_1.TYPE], + ['RTCStatsIceCandidatePairState', base_config_1.TYPE], + ['RTCStatsType', base_config_1.TYPE], + ['ReadableStreamReaderMode', base_config_1.TYPE], + ['ReadableStreamType', base_config_1.TYPE], + ['ReadyState', base_config_1.TYPE], + ['RecordingState', base_config_1.TYPE], + ['RedEyeReduction', base_config_1.TYPE], + ['ReferrerPolicy', base_config_1.TYPE], + ['RemotePlaybackState', base_config_1.TYPE], + ['RequestCache', base_config_1.TYPE], + ['RequestCredentials', base_config_1.TYPE], + ['RequestDestination', base_config_1.TYPE], + ['RequestMode', base_config_1.TYPE], + ['RequestPriority', base_config_1.TYPE], + ['RequestRedirect', base_config_1.TYPE], + ['ResidentKeyRequirement', base_config_1.TYPE], + ['ResizeObserverBoxOptions', base_config_1.TYPE], + ['ResizeQuality', base_config_1.TYPE], + ['ResponseType', base_config_1.TYPE], + ['SanitizerPresets', base_config_1.TYPE], + ['ScrollAxis', base_config_1.TYPE], + ['ScrollBehavior', base_config_1.TYPE], + ['ScrollLogicalPosition', base_config_1.TYPE], + ['ScrollRestoration', base_config_1.TYPE], + ['ScrollSetting', base_config_1.TYPE], + ['SecurityPolicyViolationEventDisposition', base_config_1.TYPE], + ['SelectionMode', base_config_1.TYPE], + ['ServiceWorkerState', base_config_1.TYPE], + ['ServiceWorkerUpdateViaCache', base_config_1.TYPE], + ['ShadowRootMode', base_config_1.TYPE], + ['SlotAssignmentMode', base_config_1.TYPE], + ['SpeechRecognitionErrorCode', base_config_1.TYPE], + ['SpeechSynthesisErrorCode', base_config_1.TYPE], + ['TaskPriority', base_config_1.TYPE], + ['TextTrackKind', base_config_1.TYPE], + ['TextTrackMode', base_config_1.TYPE], + ['TouchType', base_config_1.TYPE], + ['TransferFunction', base_config_1.TYPE], + ['UserVerificationRequirement', base_config_1.TYPE], + ['VideoColorPrimaries', base_config_1.TYPE], + ['VideoEncoderBitrateMode', base_config_1.TYPE], + ['VideoFacingModeEnum', base_config_1.TYPE], + ['VideoMatrixCoefficients', base_config_1.TYPE], + ['VideoPixelFormat', base_config_1.TYPE], + ['VideoTransferCharacteristics', base_config_1.TYPE], + ['WakeLockType', base_config_1.TYPE], + ['WebGLPowerPreference', base_config_1.TYPE], + ['WebTransportCongestionControl', base_config_1.TYPE], + ['WebTransportErrorSource', base_config_1.TYPE], + ['WorkerType', base_config_1.TYPE], + ['WriteCommandType', base_config_1.TYPE], + ['XMLHttpRequestResponseType', base_config_1.TYPE], + ['FormDataIterator', base_config_1.TYPE], + ['HeadersIterator', base_config_1.TYPE], + ['MediaKeyStatusMapIterator', base_config_1.TYPE], + ['StylePropertyMapReadOnlyIterator', base_config_1.TYPE], + ['URLSearchParamsIterator', base_config_1.TYPE], + ['FileSystemDirectoryHandleAsyncIterator', base_config_1.TYPE], + ['ReadableStreamAsyncIterator', base_config_1.TYPE], + ], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.collection.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.collection.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3aee50975cc0de593b96682f933425df6eee93e1 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.collection.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015_collection: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.collection.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.collection.js new file mode 100644 index 0000000000000000000000000000000000000000..30f3035b3a90be0a7b5c48faf60eb4ae6831bb23 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.collection.js @@ -0,0 +1,23 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015_collection = void 0; +const base_config_1 = require("./base-config"); +exports.es2015_collection = { + libs: [], + variables: [ + ['Map', base_config_1.TYPE_VALUE], + ['MapConstructor', base_config_1.TYPE], + ['ReadonlyMap', base_config_1.TYPE], + ['WeakMap', base_config_1.TYPE_VALUE], + ['WeakMapConstructor', base_config_1.TYPE], + ['Set', base_config_1.TYPE_VALUE], + ['SetConstructor', base_config_1.TYPE], + ['ReadonlySet', base_config_1.TYPE], + ['WeakSet', base_config_1.TYPE_VALUE], + ['WeakSetConstructor', base_config_1.TYPE], + ], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.core.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.core.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..86fbc58c3f59a846604c6cd8752ea7f5c9939471 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.core.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015_core: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.core.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.core.js new file mode 100644 index 0000000000000000000000000000000000000000..f8c2a08ad1e4fb1fb042c859d4c9246e6e1777aa --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.core.js @@ -0,0 +1,34 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015_core = void 0; +const base_config_1 = require("./base-config"); +exports.es2015_core = { + libs: [], + variables: [ + ['Array', base_config_1.TYPE], + ['ArrayConstructor', base_config_1.TYPE], + ['DateConstructor', base_config_1.TYPE], + ['Function', base_config_1.TYPE], + ['Math', base_config_1.TYPE], + ['NumberConstructor', base_config_1.TYPE], + ['ObjectConstructor', base_config_1.TYPE], + ['ReadonlyArray', base_config_1.TYPE], + ['RegExp', base_config_1.TYPE], + ['RegExpConstructor', base_config_1.TYPE], + ['String', base_config_1.TYPE], + ['StringConstructor', base_config_1.TYPE], + ['Int8Array', base_config_1.TYPE], + ['Uint8Array', base_config_1.TYPE], + ['Uint8ClampedArray', base_config_1.TYPE], + ['Int16Array', base_config_1.TYPE], + ['Uint16Array', base_config_1.TYPE], + ['Int32Array', base_config_1.TYPE], + ['Uint32Array', base_config_1.TYPE], + ['Float32Array', base_config_1.TYPE], + ['Float64Array', base_config_1.TYPE], + ], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5e1c3ed5d625635266f12e59775e76d4c67b1d3c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.generator.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.generator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eec0b1fbef48cde40d2aec49e609683404c5b1b8 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.generator.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015_generator: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.generator.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.generator.js new file mode 100644 index 0000000000000000000000000000000000000000..0b51a8561c4b7d1e974399618e60b700bc032f32 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.generator.js @@ -0,0 +1,17 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015_generator = void 0; +const base_config_1 = require("./base-config"); +const es2015_iterable_1 = require("./es2015.iterable"); +exports.es2015_generator = { + libs: [es2015_iterable_1.es2015_iterable], + variables: [ + ['Generator', base_config_1.TYPE], + ['GeneratorFunction', base_config_1.TYPE], + ['GeneratorFunctionConstructor', base_config_1.TYPE], + ], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.iterable.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.iterable.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..39ad182e70e1b28a2a8f8d5a105859dfff7d5fc3 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.iterable.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015_iterable: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.iterable.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.iterable.js new file mode 100644 index 0000000000000000000000000000000000000000..d91a0a7d8e00372280ccc95eff683894e17a1f79 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.iterable.js @@ -0,0 +1,62 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015_iterable = void 0; +const base_config_1 = require("./base-config"); +const es2015_symbol_1 = require("./es2015.symbol"); +exports.es2015_iterable = { + libs: [es2015_symbol_1.es2015_symbol], + variables: [ + ['SymbolConstructor', base_config_1.TYPE], + ['IteratorYieldResult', base_config_1.TYPE], + ['IteratorReturnResult', base_config_1.TYPE], + ['IteratorResult', base_config_1.TYPE], + ['Iterator', base_config_1.TYPE], + ['Iterable', base_config_1.TYPE], + ['IterableIterator', base_config_1.TYPE], + ['IteratorObject', base_config_1.TYPE], + ['BuiltinIteratorReturn', base_config_1.TYPE], + ['ArrayIterator', base_config_1.TYPE], + ['Array', base_config_1.TYPE], + ['ArrayConstructor', base_config_1.TYPE], + ['ReadonlyArray', base_config_1.TYPE], + ['IArguments', base_config_1.TYPE], + ['MapIterator', base_config_1.TYPE], + ['Map', base_config_1.TYPE], + ['ReadonlyMap', base_config_1.TYPE], + ['MapConstructor', base_config_1.TYPE], + ['WeakMap', base_config_1.TYPE], + ['WeakMapConstructor', base_config_1.TYPE], + ['SetIterator', base_config_1.TYPE], + ['Set', base_config_1.TYPE], + ['ReadonlySet', base_config_1.TYPE], + ['SetConstructor', base_config_1.TYPE], + ['WeakSet', base_config_1.TYPE], + ['WeakSetConstructor', base_config_1.TYPE], + ['Promise', base_config_1.TYPE], + ['PromiseConstructor', base_config_1.TYPE], + ['StringIterator', base_config_1.TYPE], + ['String', base_config_1.TYPE], + ['Int8Array', base_config_1.TYPE], + ['Int8ArrayConstructor', base_config_1.TYPE], + ['Uint8Array', base_config_1.TYPE], + ['Uint8ArrayConstructor', base_config_1.TYPE], + ['Uint8ClampedArray', base_config_1.TYPE], + ['Uint8ClampedArrayConstructor', base_config_1.TYPE], + ['Int16Array', base_config_1.TYPE], + ['Int16ArrayConstructor', base_config_1.TYPE], + ['Uint16Array', base_config_1.TYPE], + ['Uint16ArrayConstructor', base_config_1.TYPE], + ['Int32Array', base_config_1.TYPE], + ['Int32ArrayConstructor', base_config_1.TYPE], + ['Uint32Array', base_config_1.TYPE], + ['Uint32ArrayConstructor', base_config_1.TYPE], + ['Float32Array', base_config_1.TYPE], + ['Float32ArrayConstructor', base_config_1.TYPE], + ['Float64Array', base_config_1.TYPE], + ['Float64ArrayConstructor', base_config_1.TYPE], + ], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.js new file mode 100644 index 0000000000000000000000000000000000000000..44ab404a1a3a59d8593afe55030f3df1ca0f0c12 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.js @@ -0,0 +1,32 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015 = void 0; +const es5_1 = require("./es5"); +const es2015_collection_1 = require("./es2015.collection"); +const es2015_core_1 = require("./es2015.core"); +const es2015_generator_1 = require("./es2015.generator"); +const es2015_iterable_1 = require("./es2015.iterable"); +const es2015_promise_1 = require("./es2015.promise"); +const es2015_proxy_1 = require("./es2015.proxy"); +const es2015_reflect_1 = require("./es2015.reflect"); +const es2015_symbol_1 = require("./es2015.symbol"); +const es2015_symbol_wellknown_1 = require("./es2015.symbol.wellknown"); +exports.es2015 = { + libs: [ + es5_1.es5, + es2015_core_1.es2015_core, + es2015_collection_1.es2015_collection, + es2015_iterable_1.es2015_iterable, + es2015_generator_1.es2015_generator, + es2015_promise_1.es2015_promise, + es2015_proxy_1.es2015_proxy, + es2015_reflect_1.es2015_reflect, + es2015_symbol_1.es2015_symbol, + es2015_symbol_wellknown_1.es2015_symbol_wellknown, + ], + variables: [], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.promise.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.promise.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4bb3cbb8bccecc170d7b8a27e46de1a600349fa7 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.promise.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015_promise: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.promise.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.promise.js new file mode 100644 index 0000000000000000000000000000000000000000..aca59619443181fb11208085a6c218fb3027509d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.promise.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015_promise = void 0; +const base_config_1 = require("./base-config"); +exports.es2015_promise = { + libs: [], + variables: [['PromiseConstructor', base_config_1.TYPE]], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.proxy.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.proxy.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d0ef95c092d030dd2f8c0e21869fb794d020dc39 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.proxy.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015_proxy: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.proxy.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.proxy.js new file mode 100644 index 0000000000000000000000000000000000000000..2ce5022e4cbb564a077fd31cdfd67c773d8c1ad4 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.proxy.js @@ -0,0 +1,15 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015_proxy = void 0; +const base_config_1 = require("./base-config"); +exports.es2015_proxy = { + libs: [], + variables: [ + ['ProxyHandler', base_config_1.TYPE], + ['ProxyConstructor', base_config_1.TYPE], + ], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.reflect.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.reflect.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..263b2c051246e6f63d526ac3cf4284a55c3bcd39 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.reflect.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015_reflect: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.reflect.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.reflect.js new file mode 100644 index 0000000000000000000000000000000000000000..0e29c2e40df008fe365cea0e51f731278502789c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.reflect.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015_reflect = void 0; +const base_config_1 = require("./base-config"); +exports.es2015_reflect = { + libs: [], + variables: [['Reflect', base_config_1.TYPE_VALUE]], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e1a8346d4455f07913d51546d7219c2f1a6c3dfc --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015_symbol: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.js new file mode 100644 index 0000000000000000000000000000000000000000..2baaf5ab0ef9023a6678e43cfa98f6141bd640b3 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015_symbol = void 0; +const base_config_1 = require("./base-config"); +exports.es2015_symbol = { + libs: [], + variables: [['SymbolConstructor', base_config_1.TYPE]], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.wellknown.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.wellknown.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bedc85017a5c1a6a25d89b97a45c20b58c87ed39 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.wellknown.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015_symbol_wellknown: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.wellknown.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.wellknown.js new file mode 100644 index 0000000000000000000000000000000000000000..fc5dadd71e57df1fb0557a31b2b86b3686d38b36 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.wellknown.js @@ -0,0 +1,47 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015_symbol_wellknown = void 0; +const base_config_1 = require("./base-config"); +const es2015_symbol_1 = require("./es2015.symbol"); +exports.es2015_symbol_wellknown = { + libs: [es2015_symbol_1.es2015_symbol], + variables: [ + ['SymbolConstructor', base_config_1.TYPE], + ['Symbol', base_config_1.TYPE], + ['Array', base_config_1.TYPE], + ['ReadonlyArray', base_config_1.TYPE], + ['Date', base_config_1.TYPE], + ['Map', base_config_1.TYPE], + ['WeakMap', base_config_1.TYPE], + ['Set', base_config_1.TYPE], + ['WeakSet', base_config_1.TYPE], + ['JSON', base_config_1.TYPE], + ['Function', base_config_1.TYPE], + ['GeneratorFunction', base_config_1.TYPE], + ['Math', base_config_1.TYPE], + ['Promise', base_config_1.TYPE], + ['PromiseConstructor', base_config_1.TYPE], + ['RegExp', base_config_1.TYPE], + ['RegExpConstructor', base_config_1.TYPE], + ['String', base_config_1.TYPE], + ['ArrayBuffer', base_config_1.TYPE], + ['DataView', base_config_1.TYPE], + ['Int8Array', base_config_1.TYPE], + ['Uint8Array', base_config_1.TYPE], + ['Uint8ClampedArray', base_config_1.TYPE], + ['Int16Array', base_config_1.TYPE], + ['Uint16Array', base_config_1.TYPE], + ['Int32Array', base_config_1.TYPE], + ['Uint32Array', base_config_1.TYPE], + ['Float32Array', base_config_1.TYPE], + ['Float64Array', base_config_1.TYPE], + ['ArrayConstructor', base_config_1.TYPE], + ['MapConstructor', base_config_1.TYPE], + ['SetConstructor', base_config_1.TYPE], + ['ArrayBufferConstructor', base_config_1.TYPE], + ], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.array.include.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.array.include.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e4ff90e2475014933916633fe9dafe8f98372b19 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.array.include.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2016_array_include: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.array.include.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.array.include.js new file mode 100644 index 0000000000000000000000000000000000000000..baab2d1bcf83c5b9a823f19164c65c325cdad771 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.array.include.js @@ -0,0 +1,24 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2016_array_include = void 0; +const base_config_1 = require("./base-config"); +exports.es2016_array_include = { + libs: [], + variables: [ + ['Array', base_config_1.TYPE], + ['ReadonlyArray', base_config_1.TYPE], + ['Int8Array', base_config_1.TYPE], + ['Uint8Array', base_config_1.TYPE], + ['Uint8ClampedArray', base_config_1.TYPE], + ['Int16Array', base_config_1.TYPE], + ['Uint16Array', base_config_1.TYPE], + ['Int32Array', base_config_1.TYPE], + ['Uint32Array', base_config_1.TYPE], + ['Float32Array', base_config_1.TYPE], + ['Float64Array', base_config_1.TYPE], + ], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f943687d95e710074292b97a7f091f9cc4394375 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2016: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.full.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.full.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ac847f617ab3b3afe78a1763f018b3590330c7a --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.full.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2016_full: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.full.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.full.js new file mode 100644 index 0000000000000000000000000000000000000000..029ae1c3db1af3a3b9b3db086bf232c2276a111b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.full.js @@ -0,0 +1,16 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2016_full = void 0; +const dom_1 = require("./dom"); +const dom_iterable_1 = require("./dom.iterable"); +const es2016_1 = require("./es2016"); +const scripthost_1 = require("./scripthost"); +const webworker_importscripts_1 = require("./webworker.importscripts"); +exports.es2016_full = { + libs: [es2016_1.es2016, dom_1.dom, webworker_importscripts_1.webworker_importscripts, scripthost_1.scripthost, dom_iterable_1.dom_iterable], + variables: [], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.intl.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.intl.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..68cc6af7f349e635967799f2ba65871841d8a292 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.intl.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2016_intl: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.intl.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.intl.js new file mode 100644 index 0000000000000000000000000000000000000000..e32da505103ce7bd6736a8858d1e1021e9a7d661 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.intl.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2016_intl = void 0; +const base_config_1 = require("./base-config"); +exports.es2016_intl = { + libs: [], + variables: [['Intl', base_config_1.TYPE_VALUE]], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.js new file mode 100644 index 0000000000000000000000000000000000000000..b98f66db72c7d61eca3ea86d4bfe61f15c12d177 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.js @@ -0,0 +1,14 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2016 = void 0; +const es2015_1 = require("./es2015"); +const es2016_array_include_1 = require("./es2016.array.include"); +const es2016_intl_1 = require("./es2016.intl"); +exports.es2016 = { + libs: [es2015_1.es2015, es2016_array_include_1.es2016_array_include, es2016_intl_1.es2016_intl], + variables: [], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.arraybuffer.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.arraybuffer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d335f9c4e7ff7f20581567899a94f468983d674f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.arraybuffer.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2017_arraybuffer: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.arraybuffer.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.arraybuffer.js new file mode 100644 index 0000000000000000000000000000000000000000..8f96439adff9cef9eac4fcc81e2a6a7333fbdaef --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.arraybuffer.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2017_arraybuffer = void 0; +const base_config_1 = require("./base-config"); +exports.es2017_arraybuffer = { + libs: [], + variables: [['ArrayBufferConstructor', base_config_1.TYPE]], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..21e17901581373572e2a5cf1a0a73c3884e11637 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2017: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.date.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.date.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..41ed58a2836d67932a83df39d8431f275ff4c142 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.date.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2017_date: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.date.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.date.js new file mode 100644 index 0000000000000000000000000000000000000000..5e54f22fea574d3717d98e82e05a674849beae7d --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.date.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2017_date = void 0; +const base_config_1 = require("./base-config"); +exports.es2017_date = { + libs: [], + variables: [['DateConstructor', base_config_1.TYPE]], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.full.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.full.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..03bbade450b17a0a44c74ef7b7f655a334575723 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.full.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2017_full: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.full.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.full.js new file mode 100644 index 0000000000000000000000000000000000000000..12a1568ef6d53f55e26d6343091e0465945ab095 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.full.js @@ -0,0 +1,16 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2017_full = void 0; +const dom_1 = require("./dom"); +const dom_iterable_1 = require("./dom.iterable"); +const es2017_1 = require("./es2017"); +const scripthost_1 = require("./scripthost"); +const webworker_importscripts_1 = require("./webworker.importscripts"); +exports.es2017_full = { + libs: [es2017_1.es2017, dom_1.dom, webworker_importscripts_1.webworker_importscripts, scripthost_1.scripthost, dom_iterable_1.dom_iterable], + variables: [], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.intl.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.intl.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..862858cc51c854a9d06ec6e1bc2c07ee4127f0f8 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.intl.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2017_intl: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.intl.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.intl.js new file mode 100644 index 0000000000000000000000000000000000000000..4b9ba6a7e031431a8de8604c116fb2c71cad1a09 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.intl.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2017_intl = void 0; +const base_config_1 = require("./base-config"); +exports.es2017_intl = { + libs: [], + variables: [['Intl', base_config_1.TYPE_VALUE]], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.js new file mode 100644 index 0000000000000000000000000000000000000000..bef7d0c71e6bc36f27505735156daafe053f3d03 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.js @@ -0,0 +1,28 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2017 = void 0; +const es2016_1 = require("./es2016"); +const es2017_arraybuffer_1 = require("./es2017.arraybuffer"); +const es2017_date_1 = require("./es2017.date"); +const es2017_intl_1 = require("./es2017.intl"); +const es2017_object_1 = require("./es2017.object"); +const es2017_sharedmemory_1 = require("./es2017.sharedmemory"); +const es2017_string_1 = require("./es2017.string"); +const es2017_typedarrays_1 = require("./es2017.typedarrays"); +exports.es2017 = { + libs: [ + es2016_1.es2016, + es2017_arraybuffer_1.es2017_arraybuffer, + es2017_date_1.es2017_date, + es2017_intl_1.es2017_intl, + es2017_object_1.es2017_object, + es2017_sharedmemory_1.es2017_sharedmemory, + es2017_string_1.es2017_string, + es2017_typedarrays_1.es2017_typedarrays, + ], + variables: [], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.object.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.object.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0b7d7c6681fe0c75b0e3bb16bc1c78950754f657 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.object.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2017_object: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.object.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.object.js new file mode 100644 index 0000000000000000000000000000000000000000..85c7b95b723b3039de904d54f2526fa543847f09 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.object.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2017_object = void 0; +const base_config_1 = require("./base-config"); +exports.es2017_object = { + libs: [], + variables: [['ObjectConstructor', base_config_1.TYPE]], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.sharedmemory.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.sharedmemory.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8e6ad9b8b4e5a3966dfddcef4eb9f5e2a8e4f623 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.sharedmemory.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2017_sharedmemory: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.sharedmemory.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.sharedmemory.js new file mode 100644 index 0000000000000000000000000000000000000000..66d08440d8ea43c5936eee369b27a2e0ec8d7808 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.sharedmemory.js @@ -0,0 +1,19 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2017_sharedmemory = void 0; +const base_config_1 = require("./base-config"); +const es2015_symbol_1 = require("./es2015.symbol"); +const es2015_symbol_wellknown_1 = require("./es2015.symbol.wellknown"); +exports.es2017_sharedmemory = { + libs: [es2015_symbol_1.es2015_symbol, es2015_symbol_wellknown_1.es2015_symbol_wellknown], + variables: [ + ['SharedArrayBuffer', base_config_1.TYPE_VALUE], + ['SharedArrayBufferConstructor', base_config_1.TYPE], + ['ArrayBufferTypes', base_config_1.TYPE], + ['Atomics', base_config_1.TYPE_VALUE], + ], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.string.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.string.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..72cba8a84491957871052ce0c02c8698a0f70ffe --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.string.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2017_string: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.string.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.string.js new file mode 100644 index 0000000000000000000000000000000000000000..30939851add96b7072c47332ac8f120bb8bdae0c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.string.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2017_string = void 0; +const base_config_1 = require("./base-config"); +exports.es2017_string = { + libs: [], + variables: [['String', base_config_1.TYPE]], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.typedarrays.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.typedarrays.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3c757aa0fe6a0be3e773073c607ad4fbbd35fb0e --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.typedarrays.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2017_typedarrays: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.typedarrays.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.typedarrays.js new file mode 100644 index 0000000000000000000000000000000000000000..986aed96f5e40d8629e7cb3fba6e7f250ed77c8b --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.typedarrays.js @@ -0,0 +1,22 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2017_typedarrays = void 0; +const base_config_1 = require("./base-config"); +exports.es2017_typedarrays = { + libs: [], + variables: [ + ['Int8ArrayConstructor', base_config_1.TYPE], + ['Uint8ArrayConstructor', base_config_1.TYPE], + ['Uint8ClampedArrayConstructor', base_config_1.TYPE], + ['Int16ArrayConstructor', base_config_1.TYPE], + ['Uint16ArrayConstructor', base_config_1.TYPE], + ['Int32ArrayConstructor', base_config_1.TYPE], + ['Uint32ArrayConstructor', base_config_1.TYPE], + ['Float32ArrayConstructor', base_config_1.TYPE], + ['Float64ArrayConstructor', base_config_1.TYPE], + ], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asyncgenerator.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asyncgenerator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..036ee0b8ba7eeca99be92d8ea085520679bdb3cf --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asyncgenerator.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2018_asyncgenerator: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asyncgenerator.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asyncgenerator.js new file mode 100644 index 0000000000000000000000000000000000000000..653f3733bee1bef6a8bf19b408e412c0dd0b063a --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asyncgenerator.js @@ -0,0 +1,17 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2018_asyncgenerator = void 0; +const base_config_1 = require("./base-config"); +const es2018_asynciterable_1 = require("./es2018.asynciterable"); +exports.es2018_asyncgenerator = { + libs: [es2018_asynciterable_1.es2018_asynciterable], + variables: [ + ['AsyncGenerator', base_config_1.TYPE], + ['AsyncGeneratorFunction', base_config_1.TYPE], + ['AsyncGeneratorFunctionConstructor', base_config_1.TYPE], + ], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asynciterable.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asynciterable.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a90dd11438e59a6c86a0c613c62fc091655cc2f --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asynciterable.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2018_asynciterable: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asynciterable.js b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asynciterable.js new file mode 100644 index 0000000000000000000000000000000000000000..028f65ca04e6002cc5deef64d007829ccee12d87 --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asynciterable.js @@ -0,0 +1,20 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2018_asynciterable = void 0; +const base_config_1 = require("./base-config"); +const es2015_iterable_1 = require("./es2015.iterable"); +const es2015_symbol_1 = require("./es2015.symbol"); +exports.es2018_asynciterable = { + libs: [es2015_symbol_1.es2015_symbol, es2015_iterable_1.es2015_iterable], + variables: [ + ['SymbolConstructor', base_config_1.TYPE], + ['AsyncIterator', base_config_1.TYPE], + ['AsyncIterable', base_config_1.TYPE], + ['AsyncIterableIterator', base_config_1.TYPE], + ['AsyncIteratorObject', base_config_1.TYPE], + ], +}; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..580776de9bb42a92c674a5064c5ba684bf00d81c --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2018: LibDefinition; diff --git a/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.full.d.ts b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.full.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cfc1d231eb571ee9b9248a9569181520d612c4ae --- /dev/null +++ b/tools/ui/node_modules/eslint-plugin-perfectionist/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.full.d.ts @@ -0,0 +1,2 @@ +import type { LibDefinition } from '../variable'; +export declare const es2018_full: LibDefinition; diff --git a/tools/ui/node_modules/eslint/lib/rules/lines-between-class-members.js b/tools/ui/node_modules/eslint/lib/rules/lines-between-class-members.js new file mode 100644 index 0000000000000000000000000000000000000000..896169985c957fdc50347649f943c4d82c7ae88e --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/lines-between-class-members.js @@ -0,0 +1,358 @@ +/** + * @fileoverview Rule to check empty newline between class members + * @author 薛定谔的猫 + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Types of class members. + * Those have `test` method to check it matches to the given class member. + * @private + */ +const ClassMemberTypes = { + "*": { test: () => true }, + field: { test: node => node.type === "PropertyDefinition" }, + method: { test: node => node.type === "MethodDefinition" }, +}; + +//------------------------------------------------------------------------------ +// 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: "lines-between-class-members", + url: "https://eslint.style/rules/lines-between-class-members", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Require or disallow an empty line between class members", + recommended: false, + url: "https://eslint.org/docs/latest/rules/lines-between-class-members", + }, + + fixable: "whitespace", + + schema: [ + { + anyOf: [ + { + type: "object", + properties: { + enforce: { + type: "array", + items: { + type: "object", + properties: { + blankLine: { + enum: ["always", "never"], + }, + prev: { + enum: ["method", "field", "*"], + }, + next: { + enum: ["method", "field", "*"], + }, + }, + additionalProperties: false, + required: ["blankLine", "prev", "next"], + }, + minItems: 1, + }, + }, + additionalProperties: false, + required: ["enforce"], + }, + { + enum: ["always", "never"], + }, + ], + }, + { + type: "object", + properties: { + exceptAfterSingleLine: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + messages: { + never: "Unexpected blank line between class members.", + always: "Expected blank line between class members.", + }, + }, + + create(context) { + const options = []; + + options[0] = context.options[0] || "always"; + options[1] = context.options[1] || { exceptAfterSingleLine: false }; + + const configureList = + typeof options[0] === "object" + ? options[0].enforce + : [{ blankLine: options[0], prev: "*", next: "*" }]; + const sourceCode = context.sourceCode; + + /** + * Gets a pair of tokens that should be used to check lines between two class member nodes. + * + * In most cases, this returns the very last token of the current node and + * the very first token of the next node. + * For example: + * + * class C { + * x = 1; // curLast: `;` nextFirst: `in` + * in = 2 + * } + * + * There is only one exception. If the given node ends with a semicolon, and it looks like + * a semicolon-less style's semicolon - one that is not on the same line as the preceding + * token, but is on the line where the next class member starts - this returns the preceding + * token and the semicolon as boundary tokens. + * For example: + * + * class C { + * x = 1 // curLast: `1` nextFirst: `;` + * ;in = 2 + * } + * When determining the desired layout of the code, we should treat this semicolon as + * a part of the next class member node instead of the one it technically belongs to. + * @param {ASTNode} curNode Current class member node. + * @param {ASTNode} nextNode Next class member node. + * @returns {Token} The actual last token of `node`. + * @private + */ + function getBoundaryTokens(curNode, nextNode) { + const lastToken = sourceCode.getLastToken(curNode); + const prevToken = sourceCode.getTokenBefore(lastToken); + const nextToken = sourceCode.getFirstToken(nextNode); // skip possible lone `;` between nodes + + const isSemicolonLessStyle = + astUtils.isSemicolonToken(lastToken) && + !astUtils.isTokenOnSameLine(prevToken, lastToken) && + astUtils.isTokenOnSameLine(lastToken, nextToken); + + return isSemicolonLessStyle + ? { curLast: prevToken, nextFirst: lastToken } + : { curLast: lastToken, nextFirst: nextToken }; + } + + /** + * Return the last token among the consecutive tokens that have no exceed max line difference in between, before the first token in the next member. + * @param {Token} prevLastToken The last token in the previous member node. + * @param {Token} nextFirstToken The first token in the next member node. + * @param {number} maxLine The maximum number of allowed line difference between consecutive tokens. + * @returns {Token} The last token among the consecutive tokens. + */ + function findLastConsecutiveTokenAfter( + prevLastToken, + nextFirstToken, + maxLine, + ) { + const after = sourceCode.getTokenAfter(prevLastToken, { + includeComments: true, + }); + + if ( + after !== nextFirstToken && + after.loc.start.line - prevLastToken.loc.end.line <= maxLine + ) { + return findLastConsecutiveTokenAfter( + after, + nextFirstToken, + maxLine, + ); + } + return prevLastToken; + } + + /** + * Return the first token among the consecutive tokens that have no exceed max line difference in between, after the last token in the previous member. + * @param {Token} nextFirstToken The first token in the next member node. + * @param {Token} prevLastToken The last token in the previous member node. + * @param {number} maxLine The maximum number of allowed line difference between consecutive tokens. + * @returns {Token} The first token among the consecutive tokens. + */ + function findFirstConsecutiveTokenBefore( + nextFirstToken, + prevLastToken, + maxLine, + ) { + const before = sourceCode.getTokenBefore(nextFirstToken, { + includeComments: true, + }); + + if ( + before !== prevLastToken && + nextFirstToken.loc.start.line - before.loc.end.line <= maxLine + ) { + return findFirstConsecutiveTokenBefore( + before, + prevLastToken, + maxLine, + ); + } + return nextFirstToken; + } + + /** + * Checks if there is a token or comment between two tokens. + * @param {Token} before The token before. + * @param {Token} after The token after. + * @returns {boolean} True if there is a token or comment between two tokens. + */ + function hasTokenOrCommentBetween(before, after) { + return ( + sourceCode.getTokensBetween(before, after, { + includeComments: true, + }).length !== 0 + ); + } + + /** + * Checks whether the given node matches the given type. + * @param {ASTNode} node The class member node to check. + * @param {string} type The class member type to check. + * @returns {boolean} `true` if the class member node matched the type. + * @private + */ + function match(node, type) { + return ClassMemberTypes[type].test(node); + } + + /** + * Finds the last matched configuration from the configureList. + * @param {ASTNode} prevNode The previous node to match. + * @param {ASTNode} nextNode The current node to match. + * @returns {string|null} Padding type or `null` if no matches were found. + * @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 configure.blankLine; + } + } + return null; + } + + return { + ClassBody(node) { + const body = node.body; + + for (let i = 0; i < body.length - 1; i++) { + const curFirst = sourceCode.getFirstToken(body[i]); + const { curLast, nextFirst } = getBoundaryTokens( + body[i], + body[i + 1], + ); + const isMulti = !astUtils.isTokenOnSameLine( + curFirst, + curLast, + ); + const skip = !isMulti && options[1].exceptAfterSingleLine; + const beforePadding = findLastConsecutiveTokenAfter( + curLast, + nextFirst, + 1, + ); + const afterPadding = findFirstConsecutiveTokenBefore( + nextFirst, + curLast, + 1, + ); + const isPadded = + afterPadding.loc.start.line - + beforePadding.loc.end.line > + 1; + const hasTokenInPadding = hasTokenOrCommentBetween( + beforePadding, + afterPadding, + ); + const curLineLastToken = findLastConsecutiveTokenAfter( + curLast, + nextFirst, + 0, + ); + const paddingType = getPaddingType(body[i], body[i + 1]); + + if (paddingType === "never" && isPadded) { + context.report({ + node: body[i + 1], + messageId: "never", + + fix(fixer) { + if (hasTokenInPadding) { + return null; + } + return fixer.replaceTextRange( + [ + beforePadding.range[1], + afterPadding.range[0], + ], + "\n", + ); + }, + }); + } else if (paddingType === "always" && !skip && !isPadded) { + context.report({ + node: body[i + 1], + messageId: "always", + + fix(fixer) { + if (hasTokenInPadding) { + return null; + } + return fixer.insertTextAfter( + curLineLastToken, + "\n", + ); + }, + }); + } + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/logical-assignment-operators.js b/tools/ui/node_modules/eslint/lib/rules/logical-assignment-operators.js new file mode 100644 index 0000000000000000000000000000000000000000..38103f16c5b52da90a88dc83c595ffe114c7575d --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/logical-assignment-operators.js @@ -0,0 +1,688 @@ +/** + * @fileoverview Rule to replace assignment expressions with logical operator assignment + * @author Daniel Martens + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ +const astUtils = require("./utils/ast-utils.js"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const baseTypes = new Set(["Identifier", "Super", "ThisExpression"]); + +/** + * Returns true iff either "undefined" or a void expression (eg. "void 0") + * @param {ASTNode} expression Expression to check + * @param {import('eslint-scope').Scope} scope Scope of the expression + * @returns {boolean} True iff "undefined" or "void ..." + */ +function isUndefined(expression, scope) { + if (expression.type === "Identifier" && expression.name === "undefined") { + return astUtils.isReferenceToGlobalVariable(scope, expression); + } + + return ( + expression.type === "UnaryExpression" && + expression.operator === "void" && + expression.argument.type === "Literal" && + expression.argument.value === 0 + ); +} + +/** + * Returns true iff the reference is either an identifier or member expression + * @param {ASTNode} expression Expression to check + * @returns {boolean} True for identifiers and member expressions + */ +function isReference(expression) { + return ( + (expression.type === "Identifier" && expression.name !== "undefined") || + expression.type === "MemberExpression" + ); +} + +/** + * Returns true iff the expression checks for nullish with loose equals. + * Examples: value == null, value == void 0 + * @param {ASTNode} expression Test condition + * @param {import('eslint-scope').Scope} scope Scope of the expression + * @returns {boolean} True iff implicit nullish comparison + */ +function isImplicitNullishComparison(expression, scope) { + if ( + expression.type !== "BinaryExpression" || + expression.operator !== "==" + ) { + return false; + } + + const reference = isReference(expression.left) ? "left" : "right"; + const nullish = reference === "left" ? "right" : "left"; + + return ( + isReference(expression[reference]) && + (astUtils.isNullLiteral(expression[nullish]) || + isUndefined(expression[nullish], scope)) + ); +} + +/** + * Condition with two equal comparisons. + * @param {ASTNode} expression Condition + * @returns {boolean} True iff matches ? === ? || ? === ? + */ +function isDoubleComparison(expression) { + return ( + expression.type === "LogicalExpression" && + expression.operator === "||" && + expression.left.type === "BinaryExpression" && + expression.left.operator === "===" && + expression.right.type === "BinaryExpression" && + expression.right.operator === "===" + ); +} + +/** + * Returns true iff the expression checks for undefined and null. + * Example: value === null || value === undefined + * @param {ASTNode} expression Test condition + * @param {import('eslint-scope').Scope} scope Scope of the expression + * @returns {boolean} True iff explicit nullish comparison + */ +function isExplicitNullishComparison(expression, scope) { + if (!isDoubleComparison(expression)) { + return false; + } + const leftReference = isReference(expression.left.left) ? "left" : "right"; + const leftNullish = leftReference === "left" ? "right" : "left"; + const rightReference = isReference(expression.right.left) + ? "left" + : "right"; + const rightNullish = rightReference === "left" ? "right" : "left"; + + return ( + astUtils.isSameReference( + expression.left[leftReference], + expression.right[rightReference], + ) && + ((astUtils.isNullLiteral(expression.left[leftNullish]) && + isUndefined(expression.right[rightNullish], scope)) || + (isUndefined(expression.left[leftNullish], scope) && + astUtils.isNullLiteral(expression.right[rightNullish]))) + ); +} + +/** + * Returns true for Boolean(arg) calls + * @param {ASTNode} expression Test condition + * @param {import('eslint-scope').Scope} scope Scope of the expression + * @returns {boolean} Whether the expression is a boolean cast + */ +function isBooleanCast(expression, scope) { + return ( + expression.type === "CallExpression" && + expression.callee.name === "Boolean" && + expression.arguments.length === 1 && + astUtils.isReferenceToGlobalVariable(scope, expression.callee) + ); +} + +/** + * Returns true for: + * truthiness checks: value, Boolean(value), !!value + * falsiness checks: !value, !Boolean(value) + * nullish checks: value == null, value === undefined || value === null + * @param {ASTNode} expression Test condition + * @param {import('eslint-scope').Scope} scope Scope of the expression + * @returns {?{ reference: ASTNode, operator: '??'|'||'|'&&'}} Null if not a known existence + */ +function getExistence(expression, scope) { + const isNegated = + expression.type === "UnaryExpression" && expression.operator === "!"; + const base = isNegated ? expression.argument : expression; + + switch (true) { + case isReference(base): + return { reference: base, operator: isNegated ? "||" : "&&" }; + case base.type === "UnaryExpression" && + base.operator === "!" && + isReference(base.argument): + return { reference: base.argument, operator: "&&" }; + case isBooleanCast(base, scope) && isReference(base.arguments[0]): + return { + reference: base.arguments[0], + operator: isNegated ? "||" : "&&", + }; + case isImplicitNullishComparison(expression, scope): + return { + reference: isReference(expression.left) + ? expression.left + : expression.right, + operator: "??", + }; + case isExplicitNullishComparison(expression, scope): + return { + reference: isReference(expression.left.left) + ? expression.left.left + : expression.left.right, + operator: "??", + }; + default: + return null; + } +} + +/** + * Returns true iff the node is inside a with block + * @param {ASTNode} node Node to check + * @returns {boolean} True iff passed node is inside a with block + */ +function isInsideWithBlock(node) { + if (node.type === "Program") { + return false; + } + + return node.parent.type === "WithStatement" && node.parent.body === node + ? true + : isInsideWithBlock(node.parent); +} + +/** + * Gets the leftmost operand of a consecutive logical expression. + * @param {SourceCode} sourceCode The ESLint source code object + * @param {LogicalExpression} node LogicalExpression + * @returns {Expression} Leftmost operand + */ +function getLeftmostOperand(sourceCode, node) { + let left = node.left; + + while ( + left.type === "LogicalExpression" && + left.operator === node.operator + ) { + if (astUtils.isParenthesised(sourceCode, left)) { + /* + * It should have associativity, + * but ignore it if use parentheses to make the evaluation order clear. + */ + return left; + } + left = left.left; + } + return left; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Require or disallow logical assignment operator shorthand", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/logical-assignment-operators", + }, + + schema: { + type: "array", + oneOf: [ + { + items: [ + { const: "always" }, + { + type: "object", + properties: { + enforceForIfStatements: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + minItems: 0, // 0 for allowing passing no options + maxItems: 2, + }, + { + items: [{ const: "never" }], + minItems: 1, + maxItems: 1, + }, + ], + }, + fixable: "code", + hasSuggestions: true, + messages: { + assignment: + "Assignment (=) can be replaced with operator assignment ({{operator}}).", + useLogicalOperator: + "Convert this assignment to use the operator {{ operator }}.", + logical: + "Logical expression can be replaced with an assignment ({{ operator }}).", + convertLogical: + "Replace this logical expression with an assignment with the operator {{ operator }}.", + if: "'if' statement can be replaced with a logical operator assignment with operator {{ operator }}.", + convertIf: + "Replace this 'if' statement with a logical assignment with operator {{ operator }}.", + unexpected: + "Unexpected logical operator assignment ({{operator}}) shorthand.", + separate: + "Separate the logical assignment into an assignment with a logical operator.", + }, + }, + + create(context) { + const mode = context.options[0] === "never" ? "never" : "always"; + const checkIf = + mode === "always" && + context.options.length > 1 && + context.options[1].enforceForIfStatements; + const sourceCode = context.sourceCode; + const isStrict = sourceCode.getScope(sourceCode.ast).isStrict; + + /** + * Returns false if the access could be a getter + * @param {ASTNode} node Assignment expression + * @returns {boolean} True iff the fix is safe + */ + function cannotBeGetter(node) { + return ( + node.type === "Identifier" && + (isStrict || !isInsideWithBlock(node)) + ); + } + + /** + * Check whether only a single property is accessed + * @param {ASTNode} node reference + * @returns {boolean} True iff a single property is accessed + */ + function accessesSingleProperty(node) { + if (!isStrict && isInsideWithBlock(node)) { + return node.type === "Identifier"; + } + + return ( + node.type === "MemberExpression" && + baseTypes.has(node.object.type) && + (!node.computed || + (node.property.type !== "MemberExpression" && + node.property.type !== "ChainExpression")) + ); + } + + /** + * Adds a fixer or suggestion whether on the fix is safe. + * @param {{ messageId: string, node: ASTNode }} descriptor Report descriptor without fix or suggest + * @param {{ messageId: string, fix: Function }} suggestion Adds the fix or the whole suggestion as only element in "suggest" to suggestion + * @param {boolean} shouldBeFixed Fix iff the condition is true + * @returns {Object} Descriptor with either an added fix or suggestion + */ + function createConditionalFixer(descriptor, suggestion, shouldBeFixed) { + if (shouldBeFixed) { + return { + ...descriptor, + fix: suggestion.fix, + }; + } + + return { + ...descriptor, + suggest: [suggestion], + }; + } + + /** + * Returns the operator token for assignments and binary expressions + * @param {ASTNode} node AssignmentExpression or BinaryExpression + * @returns {import('eslint').AST.Token} Operator token between the left and right expression + */ + function getOperatorToken(node) { + return sourceCode.getFirstTokenBetween( + node.left, + node.right, + token => token.value === node.operator, + ); + } + + if (mode === "never") { + return { + // foo ||= bar + AssignmentExpression(assignment) { + if ( + !astUtils.isLogicalAssignmentOperator( + assignment.operator, + ) + ) { + return; + } + + const descriptor = { + messageId: "unexpected", + node: assignment, + data: { operator: assignment.operator }, + }; + const suggestion = { + messageId: "separate", + *fix(ruleFixer) { + if ( + sourceCode.getCommentsInside(assignment) + .length > 0 + ) { + return; + } + + const operatorToken = getOperatorToken(assignment); + + // -> foo = bar + yield ruleFixer.replaceText(operatorToken, "="); + + const assignmentText = sourceCode.getText( + assignment.left, + ); + const operator = assignment.operator.slice(0, -1); + + // -> foo = foo || bar + yield ruleFixer.insertTextAfter( + operatorToken, + ` ${assignmentText} ${operator}`, + ); + + const precedence = + astUtils.getPrecedence(assignment.right) <= + astUtils.getPrecedence({ + type: "LogicalExpression", + operator, + }); + + // ?? and || / && cannot be mixed but have same precedence + const mixed = + assignment.operator === "??=" && + astUtils.isLogicalExpression(assignment.right); + + if ( + !astUtils.isParenthesised( + sourceCode, + assignment.right, + ) && + (precedence || mixed) + ) { + // -> foo = foo || (bar) + yield ruleFixer.insertTextBefore( + assignment.right, + "(", + ); + yield ruleFixer.insertTextAfter( + assignment.right, + ")", + ); + } + }, + }; + + context.report( + createConditionalFixer( + descriptor, + suggestion, + cannotBeGetter(assignment.left), + ), + ); + }, + }; + } + + return { + // foo = foo || bar + "AssignmentExpression[operator='='][right.type='LogicalExpression']"( + assignment, + ) { + const leftOperand = getLeftmostOperand( + sourceCode, + assignment.right, + ); + + if (!astUtils.isSameReference(assignment.left, leftOperand)) { + return; + } + + const descriptor = { + messageId: "assignment", + node: assignment, + data: { operator: `${assignment.right.operator}=` }, + }; + const suggestion = { + messageId: "useLogicalOperator", + data: { operator: `${assignment.right.operator}=` }, + *fix(ruleFixer) { + if ( + sourceCode.getCommentsInside(assignment).length > 0 + ) { + return; + } + + // No need for parenthesis around the assignment based on precedence as the precedence stays the same even with changed operator + const assignmentOperatorToken = + getOperatorToken(assignment); + + // -> foo ||= foo || bar + yield ruleFixer.insertTextBefore( + assignmentOperatorToken, + assignment.right.operator, + ); + + // -> foo ||= bar + const logicalOperatorToken = getOperatorToken( + leftOperand.parent, + ); + const firstRightOperandToken = + sourceCode.getTokenAfter(logicalOperatorToken); + + yield ruleFixer.removeRange([ + leftOperand.parent.range[0], + firstRightOperandToken.range[0], + ]); + }, + }; + + context.report( + createConditionalFixer( + descriptor, + suggestion, + cannotBeGetter(assignment.left), + ), + ); + }, + + // foo || (foo = bar) + 'LogicalExpression[right.type="AssignmentExpression"][right.operator="="]'( + logical, + ) { + // Right side has to be parenthesized, otherwise would be parsed as (foo || foo) = bar which is illegal + if ( + isReference(logical.left) && + astUtils.isSameReference(logical.left, logical.right.left) + ) { + const descriptor = { + messageId: "logical", + node: logical, + data: { operator: `${logical.operator}=` }, + }; + const suggestion = { + messageId: "convertLogical", + data: { operator: `${logical.operator}=` }, + *fix(ruleFixer) { + if ( + sourceCode.getCommentsInside(logical).length > 0 + ) { + return; + } + + const parentPrecedence = astUtils.getPrecedence( + logical.parent, + ); + const requiresOuterParenthesis = + logical.parent.type !== "ExpressionStatement" && + (parentPrecedence === -1 || + astUtils.getPrecedence({ + type: "AssignmentExpression", + }) < parentPrecedence); + + if ( + !astUtils.isParenthesised( + sourceCode, + logical, + ) && + requiresOuterParenthesis + ) { + yield ruleFixer.insertTextBefore(logical, "("); + yield ruleFixer.insertTextAfter(logical, ")"); + } + + // Also removes all opening parenthesis + yield ruleFixer.removeRange([ + logical.range[0], + logical.right.range[0], + ]); // -> foo = bar) + + // Also removes all ending parenthesis + yield ruleFixer.removeRange([ + logical.right.range[1], + logical.range[1], + ]); // -> foo = bar + + const operatorToken = getOperatorToken( + logical.right, + ); + + yield ruleFixer.insertTextBefore( + operatorToken, + logical.operator, + ); // -> foo ||= bar + }, + }; + const fix = + cannotBeGetter(logical.left) || + accessesSingleProperty(logical.left); + + context.report( + createConditionalFixer(descriptor, suggestion, fix), + ); + } + }, + + // if (foo) foo = bar + "IfStatement[alternate=null]"(ifNode) { + if (!checkIf) { + return; + } + + const hasBody = ifNode.consequent.type === "BlockStatement"; + + if (hasBody && ifNode.consequent.body.length !== 1) { + return; + } + + const body = hasBody + ? ifNode.consequent.body[0] + : ifNode.consequent; + const scope = sourceCode.getScope(ifNode); + const existence = getExistence(ifNode.test, scope); + + if ( + body.type === "ExpressionStatement" && + body.expression.type === "AssignmentExpression" && + body.expression.operator === "=" && + existence !== null && + astUtils.isSameReference( + existence.reference, + body.expression.left, + ) + ) { + const descriptor = { + messageId: "if", + node: ifNode, + data: { operator: `${existence.operator}=` }, + }; + const suggestion = { + messageId: "convertIf", + data: { operator: `${existence.operator}=` }, + *fix(ruleFixer) { + if ( + sourceCode.getCommentsInside(ifNode).length > 0 + ) { + return; + } + + const firstBodyToken = + sourceCode.getFirstToken(body); + const prevToken = sourceCode.getTokenBefore(ifNode); + + if ( + prevToken !== null && + prevToken.value !== ";" && + prevToken.value !== "{" && + firstBodyToken.type !== "Identifier" && + firstBodyToken.type !== "Keyword" + ) { + // Do not fix if the fixed statement could be part of the previous statement (eg. fn() if (a == null) (a) = b --> fn()(a) ??= b) + return; + } + + const operatorToken = getOperatorToken( + body.expression, + ); + + yield ruleFixer.insertTextBefore( + operatorToken, + existence.operator, + ); // -> if (foo) foo ||= bar + + yield ruleFixer.removeRange([ + ifNode.range[0], + body.range[0], + ]); // -> foo ||= bar + + yield ruleFixer.removeRange([ + body.range[1], + ifNode.range[1], + ]); // -> foo ||= bar, only present if "if" had a body + + const nextToken = sourceCode.getTokenAfter( + body.expression, + ); + + if ( + hasBody && + nextToken !== null && + nextToken.value !== ";" + ) { + yield ruleFixer.insertTextAfter(ifNode, ";"); + } + }, + }; + const shouldBeFixed = + cannotBeGetter(existence.reference) || + (ifNode.test.type !== "LogicalExpression" && + accessesSingleProperty(existence.reference)); + + context.report( + createConditionalFixer( + descriptor, + suggestion, + shouldBeFixed, + ), + ); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/max-classes-per-file.js b/tools/ui/node_modules/eslint/lib/rules/max-classes-per-file.js new file mode 100644 index 0000000000000000000000000000000000000000..3ede9edf2edd28684255fce73a4d97f96567b47b --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/max-classes-per-file.js @@ -0,0 +1,90 @@ +/** + * @fileoverview Enforce a maximum number of classes per file + * @author James Garbutt + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce a maximum number of classes per file", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-classes-per-file", + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 1, + }, + { + type: "object", + properties: { + ignoreExpressions: { + type: "boolean", + }, + max: { + type: "integer", + minimum: 1, + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + maximumExceeded: + "File has too many classes ({{ classCount }}). Maximum allowed is {{ max }}.", + }, + }, + create(context) { + const [option = {}] = context.options; + const [ignoreExpressions, max] = + typeof option === "number" + ? [false, option || 1] + : [option.ignoreExpressions, option.max || 1]; + + let classCount = 0; + + return { + Program() { + classCount = 0; + }, + "Program:exit"(node) { + if (classCount > max) { + context.report({ + node, + messageId: "maximumExceeded", + data: { + classCount, + max, + }, + }); + } + }, + ClassDeclaration() { + classCount++; + }, + ClassExpression() { + if (!ignoreExpressions) { + classCount++; + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/max-depth.js b/tools/ui/node_modules/eslint/lib/rules/max-depth.js new file mode 100644 index 0000000000000000000000000000000000000000..f3c66b7aecd2b6bdeaacd73fd25dfb115ecf51dc --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/max-depth.js @@ -0,0 +1,159 @@ +/** + * @fileoverview A rule to set the maximum depth block can be nested in a function. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce a maximum depth that blocks can be nested", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-depth", + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + type: "object", + properties: { + maximum: { + type: "integer", + minimum: 0, + }, + max: { + type: "integer", + minimum: 0, + }, + }, + additionalProperties: false, + }, + ], + }, + ], + messages: { + tooDeeply: + "Blocks are nested too deeply ({{depth}}). Maximum allowed is {{maxDepth}}.", + }, + }, + + create(context) { + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const functionStack = [], + option = context.options[0]; + let maxDepth = 4; + + if ( + typeof option === "object" && + (Object.hasOwn(option, "maximum") || Object.hasOwn(option, "max")) + ) { + maxDepth = option.maximum || option.max; + } + if (typeof option === "number") { + maxDepth = option; + } + + /** + * When parsing a new function, store it in our function stack + * @returns {void} + * @private + */ + function startFunction() { + functionStack.push(0); + } + + /** + * When parsing is done then pop out the reference + * @returns {void} + * @private + */ + function endFunction() { + functionStack.pop(); + } + + /** + * Save the block and Evaluate the node + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function pushBlock(node) { + const len = ++functionStack[functionStack.length - 1]; + + if (len > maxDepth) { + context.report({ + node, + messageId: "tooDeeply", + data: { depth: len, maxDepth }, + }); + } + } + + /** + * Pop the saved block + * @returns {void} + * @private + */ + function popBlock() { + functionStack[functionStack.length - 1]--; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + Program: startFunction, + FunctionDeclaration: startFunction, + FunctionExpression: startFunction, + ArrowFunctionExpression: startFunction, + StaticBlock: startFunction, + + IfStatement(node) { + if (node.parent.type !== "IfStatement") { + pushBlock(node); + } + }, + SwitchStatement: pushBlock, + TryStatement: pushBlock, + DoWhileStatement: pushBlock, + WhileStatement: pushBlock, + WithStatement: pushBlock, + ForStatement: pushBlock, + ForInStatement: pushBlock, + ForOfStatement: pushBlock, + + "IfStatement:exit": popBlock, + "SwitchStatement:exit": popBlock, + "TryStatement:exit": popBlock, + "DoWhileStatement:exit": popBlock, + "WhileStatement:exit": popBlock, + "WithStatement:exit": popBlock, + "ForStatement:exit": popBlock, + "ForInStatement:exit": popBlock, + "ForOfStatement:exit": popBlock, + + "FunctionDeclaration:exit": endFunction, + "FunctionExpression:exit": endFunction, + "ArrowFunctionExpression:exit": endFunction, + "StaticBlock:exit": endFunction, + "Program:exit": endFunction, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/max-len.js b/tools/ui/node_modules/eslint/lib/rules/max-len.js new file mode 100644 index 0000000000000000000000000000000000000000..108918f88cb77d9ca076cbc0f56962ea665324d9 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/max-len.js @@ -0,0 +1,497 @@ +/** + * @fileoverview Rule to check for max length on a line. + * @author Matt DuVall + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +const OPTIONS_SCHEMA = { + type: "object", + properties: { + code: { + type: "integer", + minimum: 0, + }, + comments: { + type: "integer", + minimum: 0, + }, + tabWidth: { + type: "integer", + minimum: 0, + }, + ignorePattern: { + type: "string", + }, + ignoreComments: { + type: "boolean", + }, + ignoreStrings: { + type: "boolean", + }, + ignoreUrls: { + type: "boolean", + }, + ignoreTemplateLiterals: { + type: "boolean", + }, + ignoreRegExpLiterals: { + type: "boolean", + }, + ignoreTrailingComments: { + type: "boolean", + }, + }, + additionalProperties: false, +}; + +const OPTIONS_OR_INTEGER_SCHEMA = { + anyOf: [ + OPTIONS_SCHEMA, + { + type: "integer", + minimum: 0, + }, + ], +}; + +//------------------------------------------------------------------------------ +// 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: "max-len", + url: "https://eslint.style/rules/max-len", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce a maximum line length", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-len", + }, + + schema: [ + OPTIONS_OR_INTEGER_SCHEMA, + OPTIONS_OR_INTEGER_SCHEMA, + OPTIONS_SCHEMA, + ], + messages: { + max: "This line has a length of {{lineLength}}. Maximum allowed is {{maxLength}}.", + maxComment: + "This line has a comment length of {{lineLength}}. Maximum allowed is {{maxCommentLength}}.", + }, + }, + + create(context) { + /* + * Inspired by http://tools.ietf.org/html/rfc3986#appendix-B, however: + * - They're matching an entire string that we know is a URI + * - We're matching part of a string where we think there *might* be a URL + * - We're only concerned about URLs, as picking out any URI would cause + * too many false positives + * - We don't care about matching the entire URL, any small segment is fine + */ + const URL_REGEXP = /[^:/?#]:\/\/[^?#]/u; + + const sourceCode = context.sourceCode; + + /** + * Computes the length of a line that may contain tabs. The width of each + * tab will be the number of spaces to the next tab stop. + * @param {string} line The line. + * @param {number} tabWidth The width of each tab stop in spaces. + * @returns {number} The computed line length. + * @private + */ + function computeLineLength(line, tabWidth) { + let extraCharacterCount = 0; + + line.replace(/\t/gu, (match, offset) => { + const totalOffset = offset + extraCharacterCount, + previousTabStopOffset = tabWidth + ? totalOffset % tabWidth + : 0, + spaceCount = tabWidth - previousTabStopOffset; + + extraCharacterCount += spaceCount - 1; // -1 for the replaced tab + }); + return Array.from(line).length + extraCharacterCount; + } + + // The options object must be the last option specified… + const options = Object.assign({}, context.options.at(-1)); + + // …but max code length… + if (typeof context.options[0] === "number") { + options.code = context.options[0]; + } + + // …and tabWidth can be optionally specified directly as integers. + if (typeof context.options[1] === "number") { + options.tabWidth = context.options[1]; + } + + const maxLength = typeof options.code === "number" ? options.code : 80, + tabWidth = + typeof options.tabWidth === "number" ? options.tabWidth : 4, + ignoreComments = !!options.ignoreComments, + ignoreStrings = !!options.ignoreStrings, + ignoreTemplateLiterals = !!options.ignoreTemplateLiterals, + ignoreRegExpLiterals = !!options.ignoreRegExpLiterals, + ignoreTrailingComments = + !!options.ignoreTrailingComments || !!options.ignoreComments, + ignoreUrls = !!options.ignoreUrls, + maxCommentLength = options.comments; + let ignorePattern = options.ignorePattern || null; + + if (ignorePattern) { + ignorePattern = new RegExp(ignorePattern, "u"); + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Tells if a given comment is trailing: it starts on the current line and + * extends to or past the end of the current line. + * @param {string} line The source line we want to check for a trailing comment on + * @param {number} lineNumber The one-indexed line number for line + * @param {ASTNode} comment The comment to inspect + * @returns {boolean} If the comment is trailing on the given line + */ + function isTrailingComment(line, lineNumber, comment) { + return ( + comment && + comment.loc.start.line === lineNumber && + lineNumber <= comment.loc.end.line && + (comment.loc.end.line > lineNumber || + comment.loc.end.column === line.length) + ); + } + + /** + * Tells if a comment encompasses the entire line. + * @param {string} line The source line with a trailing comment + * @param {number} lineNumber The one-indexed line number this is on + * @param {ASTNode} comment The comment to remove + * @returns {boolean} If the comment covers the entire line + */ + function isFullLineComment(line, lineNumber, comment) { + const start = comment.loc.start, + end = comment.loc.end, + isFirstTokenOnLine = !line + .slice(0, comment.loc.start.column) + .trim(); + + return ( + comment && + (start.line < lineNumber || + (start.line === lineNumber && isFirstTokenOnLine)) && + (end.line > lineNumber || + (end.line === lineNumber && end.column === line.length)) + ); + } + + /** + * Check if a node is a JSXEmptyExpression contained in a single line JSXExpressionContainer. + * @param {ASTNode} node A node to check. + * @returns {boolean} True if the node is a JSXEmptyExpression contained in a single line JSXExpressionContainer. + */ + function isJSXEmptyExpressionInSingleLineContainer(node) { + if ( + !node || + !node.parent || + node.type !== "JSXEmptyExpression" || + node.parent.type !== "JSXExpressionContainer" + ) { + return false; + } + + const parent = node.parent; + + return parent.loc.start.line === parent.loc.end.line; + } + + /** + * Gets the line after the comment and any remaining trailing whitespace is + * stripped. + * @param {string} line The source line with a trailing comment + * @param {ASTNode} comment The comment to remove + * @returns {string} Line without comment and trailing whitespace + */ + function stripTrailingComment(line, comment) { + // loc.column is zero-indexed + return line.slice(0, comment.loc.start.column).replace(/\s+$/u, ""); + } + + /** + * Ensure that an array exists at [key] on `object`, and add `value` to it. + * @param {Object} object the object to mutate + * @param {string} key the object's key + * @param {any} value the value to add + * @returns {void} + * @private + */ + function ensureArrayAndPush(object, key, value) { + if (!Array.isArray(object[key])) { + object[key] = []; + } + object[key].push(value); + } + + /** + * Retrieves an array containing all strings (" or ') in the source code. + * @returns {ASTNode[]} An array of string nodes. + */ + function getAllStrings() { + return sourceCode.ast.tokens.filter( + token => + token.type === "String" || + (token.type === "JSXText" && + sourceCode.getNodeByRangeIndex(token.range[0] - 1) + .type === "JSXAttribute"), + ); + } + + /** + * Retrieves an array containing all template literals in the source code. + * @returns {ASTNode[]} An array of template literal nodes. + */ + function getAllTemplateLiterals() { + return sourceCode.ast.tokens.filter( + token => token.type === "Template", + ); + } + + /** + * Retrieves an array containing all RegExp literals in the source code. + * @returns {ASTNode[]} An array of RegExp literal nodes. + */ + function getAllRegExpLiterals() { + return sourceCode.ast.tokens.filter( + token => token.type === "RegularExpression", + ); + } + + /** + * + * reduce an array of AST nodes by line number, both start and end. + * @param {ASTNode[]} arr array of AST nodes + * @returns {Object} accululated AST nodes + */ + function groupArrayByLineNumber(arr) { + const obj = {}; + + for (let i = 0; i < arr.length; i++) { + const node = arr[i]; + + for (let j = node.loc.start.line; j <= node.loc.end.line; ++j) { + ensureArrayAndPush(obj, j, node); + } + } + return obj; + } + + /** + * Returns an array of all comments in the source code. + * If the element in the array is a JSXEmptyExpression contained with a single line JSXExpressionContainer, + * the element is changed with JSXExpressionContainer node. + * @returns {ASTNode[]} An array of comment nodes + */ + function getAllComments() { + const comments = []; + + sourceCode.getAllComments().forEach(commentNode => { + const containingNode = sourceCode.getNodeByRangeIndex( + commentNode.range[0], + ); + + if (isJSXEmptyExpressionInSingleLineContainer(containingNode)) { + // push a unique node only + if (comments.at(-1) !== containingNode.parent) { + comments.push(containingNode.parent); + } + } else { + comments.push(commentNode); + } + }); + + return comments; + } + + /** + * Check the program for max length + * @param {ASTNode} node Node to examine + * @returns {void} + * @private + */ + function checkProgramForMaxLength(node) { + // split (honors line-ending) + const lines = sourceCode.lines, + // list of comments to ignore + comments = + ignoreComments || maxCommentLength || ignoreTrailingComments + ? getAllComments() + : []; + + // we iterate over comments in parallel with the lines + let commentsIndex = 0; + + const strings = getAllStrings(); + const stringsByLine = groupArrayByLineNumber(strings); + + const templateLiterals = getAllTemplateLiterals(); + const templateLiteralsByLine = + groupArrayByLineNumber(templateLiterals); + + const regExpLiterals = getAllRegExpLiterals(); + const regExpLiteralsByLine = groupArrayByLineNumber(regExpLiterals); + + lines.forEach((line, i) => { + // i is zero-indexed, line numbers are one-indexed + const lineNumber = i + 1; + + /* + * if we're checking comment length; we need to know whether this + * line is a comment + */ + let lineIsComment = false; + let textToMeasure; + + /* + * We can short-circuit the comment checks if we're already out of + * comments to check. + */ + if (commentsIndex < comments.length) { + let comment; + + // iterate over comments until we find one past the current line + do { + comment = comments[++commentsIndex]; + } while (comment && comment.loc.start.line <= lineNumber); + + // and step back by one + comment = comments[--commentsIndex]; + + if (isFullLineComment(line, lineNumber, comment)) { + lineIsComment = true; + textToMeasure = line; + } else if ( + ignoreTrailingComments && + isTrailingComment(line, lineNumber, comment) + ) { + textToMeasure = stripTrailingComment(line, comment); + + // ignore multiple trailing comments in the same line + let lastIndex = commentsIndex; + + while ( + isTrailingComment( + textToMeasure, + lineNumber, + comments[--lastIndex], + ) + ) { + textToMeasure = stripTrailingComment( + textToMeasure, + comments[lastIndex], + ); + } + } else { + textToMeasure = line; + } + } else { + textToMeasure = line; + } + if ( + (ignorePattern && ignorePattern.test(textToMeasure)) || + (ignoreUrls && URL_REGEXP.test(textToMeasure)) || + (ignoreStrings && stringsByLine[lineNumber]) || + (ignoreTemplateLiterals && + templateLiteralsByLine[lineNumber]) || + (ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber]) + ) { + // ignore this line + return; + } + + const lineLength = computeLineLength(textToMeasure, tabWidth); + const commentLengthApplies = lineIsComment && maxCommentLength; + + if (lineIsComment && ignoreComments) { + return; + } + + const loc = { + start: { + line: lineNumber, + column: 0, + }, + end: { + line: lineNumber, + column: textToMeasure.length, + }, + }; + + if (commentLengthApplies) { + if (lineLength > maxCommentLength) { + context.report({ + node, + loc, + messageId: "maxComment", + data: { + lineLength, + maxCommentLength, + }, + }); + } + } else if (lineLength > maxLength) { + context.report({ + node, + loc, + messageId: "max", + data: { + lineLength, + maxLength, + }, + }); + } + }); + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + Program: checkProgramForMaxLength, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/max-lines-per-function.js b/tools/ui/node_modules/eslint/lib/rules/max-lines-per-function.js new file mode 100644 index 0000000000000000000000000000000000000000..fd9a783f4f25b5d65f029557ecc71155fe1aa907 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/max-lines-per-function.js @@ -0,0 +1,238 @@ +/** + * @fileoverview A rule to set the maximum number of line of code in a function. + * @author Pete Ward + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { upperCaseFirst } = require("../shared/string-utils"); + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +const OPTIONS_SCHEMA = { + type: "object", + properties: { + max: { + type: "integer", + minimum: 0, + }, + skipComments: { + type: "boolean", + }, + skipBlankLines: { + type: "boolean", + }, + IIFEs: { + type: "boolean", + }, + }, + additionalProperties: false, +}; + +const OPTIONS_OR_INTEGER_SCHEMA = { + oneOf: [ + OPTIONS_SCHEMA, + { + type: "integer", + minimum: 1, + }, + ], +}; + +/** + * Given a list of comment nodes, return a map with numeric keys (source code line numbers) and comment token values. + * @param {Array} comments An array of comment nodes. + * @returns {Map} A map with numeric keys (source code line numbers) and comment token values. + */ +function getCommentLineNumbers(comments) { + const map = new Map(); + + comments.forEach(comment => { + for (let i = comment.loc.start.line; i <= comment.loc.end.line; i++) { + map.set(i, comment); + } + }); + return map; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce a maximum number of lines of code in a function", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-lines-per-function", + }, + + schema: [OPTIONS_OR_INTEGER_SCHEMA], + messages: { + exceed: "{{name}} has too many lines ({{lineCount}}). Maximum allowed is {{maxLines}}.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const lines = sourceCode.lines; + + const option = context.options[0]; + let maxLines = 50; + let skipComments = false; + let skipBlankLines = false; + let IIFEs = false; + + if (typeof option === "object") { + maxLines = typeof option.max === "number" ? option.max : 50; + skipComments = !!option.skipComments; + skipBlankLines = !!option.skipBlankLines; + IIFEs = !!option.IIFEs; + } else if (typeof option === "number") { + maxLines = option; + } + + const commentLineNumbers = getCommentLineNumbers( + sourceCode.getAllComments(), + ); + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Tells if a comment encompasses the entire line. + * @param {string} line The source line with a trailing comment + * @param {number} lineNumber The one-indexed line number this is on + * @param {ASTNode} comment The comment to remove + * @returns {boolean} If the comment covers the entire line + */ + function isFullLineComment(line, lineNumber, comment) { + const start = comment.loc.start, + end = comment.loc.end, + isFirstTokenOnLine = + start.line === lineNumber && + !line.slice(0, start.column).trim(), + isLastTokenOnLine = + end.line === lineNumber && !line.slice(end.column).trim(); + + return ( + comment && + (start.line < lineNumber || isFirstTokenOnLine) && + (end.line > lineNumber || isLastTokenOnLine) + ); + } + + /** + * 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 + ); + } + + /** + * Identifies is a node is a FunctionExpression which is embedded within a MethodDefinition or Property + * @param {ASTNode} node Node to test + * @returns {boolean} True if it's a FunctionExpression embedded within a MethodDefinition or Property + */ + function isEmbedded(node) { + if (!node.parent) { + return false; + } + if (node !== node.parent.value) { + return false; + } + if (node.parent.type === "MethodDefinition") { + return true; + } + if (node.parent.type === "Property") { + return ( + node.parent.method === true || + node.parent.kind === "get" || + node.parent.kind === "set" + ); + } + return false; + } + + /** + * Count the lines in the function + * @param {ASTNode} funcNode Function AST node + * @returns {void} + * @private + */ + function processFunction(funcNode) { + const node = isEmbedded(funcNode) ? funcNode.parent : funcNode; + + if (!IIFEs && isIIFE(node)) { + return; + } + let lineCount = 0; + + for (let i = node.loc.start.line - 1; i < node.loc.end.line; ++i) { + const line = lines[i]; + + if (skipComments) { + if ( + commentLineNumbers.has(i + 1) && + isFullLineComment( + line, + i + 1, + commentLineNumbers.get(i + 1), + ) + ) { + continue; + } + } + + if (skipBlankLines) { + if (line.match(/^\s*$/u)) { + continue; + } + } + + lineCount++; + } + + if (lineCount > maxLines) { + const name = upperCaseFirst( + astUtils.getFunctionNameWithKind(funcNode), + ); + + context.report({ + node, + messageId: "exceed", + data: { name, lineCount, maxLines }, + }); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + FunctionDeclaration: processFunction, + FunctionExpression: processFunction, + ArrowFunctionExpression: processFunction, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/max-lines.js b/tools/ui/node_modules/eslint/lib/rules/max-lines.js new file mode 100644 index 0000000000000000000000000000000000000000..eb8aeb1a7e2618a95dddef1b23d72bea524e057c --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/max-lines.js @@ -0,0 +1,189 @@ +/** + * @fileoverview enforce a maximum file length + * @author Alberto Rodríguez + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Creates an array of numbers from `start` up to, but not including, `end` + * @param {number} start The start of the range + * @param {number} end The end of the range + * @returns {number[]} The range of numbers + */ +function range(start, end) { + return [...Array(end - start).keys()].map(x => x + start); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce a maximum number of lines per file", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-lines", + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + type: "object", + properties: { + max: { + type: "integer", + minimum: 0, + }, + skipComments: { + type: "boolean", + }, + skipBlankLines: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + ], + messages: { + exceed: "File has too many lines ({{actual}}). Maximum allowed is {{max}}.", + }, + }, + + create(context) { + const option = context.options[0]; + let max = 300; + + if (typeof option === "object" && Object.hasOwn(option, "max")) { + max = option.max; + } else if (typeof option === "number") { + max = option; + } + + const skipComments = option && option.skipComments; + const skipBlankLines = option && option.skipBlankLines; + + const sourceCode = context.sourceCode; + + /** + * Returns whether or not a token is a comment node type + * @param {Token} token The token to check + * @returns {boolean} True if the token is a comment node + */ + function isCommentNodeType(token) { + return token && (token.type === "Block" || token.type === "Line"); + } + + /** + * Returns the line numbers of a comment that don't have any code on the same line + * @param {Node} comment The comment node to check + * @returns {number[]} The line numbers + */ + function getLinesWithoutCode(comment) { + let start = comment.loc.start.line; + let end = comment.loc.end.line; + + let token; + + token = comment; + do { + token = sourceCode.getTokenBefore(token, { + includeComments: true, + }); + } while (isCommentNodeType(token)); + + if (token && astUtils.isTokenOnSameLine(token, comment)) { + start += 1; + } + + token = comment; + do { + token = sourceCode.getTokenAfter(token, { + includeComments: true, + }); + } while (isCommentNodeType(token)); + + if (token && astUtils.isTokenOnSameLine(comment, token)) { + end -= 1; + } + + if (start <= end) { + return range(start, end + 1); + } + return []; + } + + return { + "Program:exit"() { + let lines = sourceCode.lines.map((text, i) => ({ + lineNumber: i + 1, + text, + })); + + /* + * If file ends with a linebreak, `sourceCode.lines` will have one extra empty line at the end. + * That isn't a real line, so we shouldn't count it. + */ + if (lines.length > 1 && lines.at(-1).text === "") { + lines.pop(); + } + + if (skipBlankLines) { + lines = lines.filter(l => l.text.trim() !== ""); + } + + if (skipComments) { + const comments = sourceCode.getAllComments(); + + const commentLines = new Set( + comments.flatMap(getLinesWithoutCode), + ); + + lines = lines.filter(l => !commentLines.has(l.lineNumber)); + } + + if (lines.length > max) { + const loc = { + start: { + line: lines[max].lineNumber, + column: 0, + }, + end: { + line: sourceCode.lines.length, + column: sourceCode.lines.at(-1).length, + }, + }; + + context.report({ + loc, + messageId: "exceed", + data: { + max, + actual: lines.length, + }, + }); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/max-nested-callbacks.js b/tools/ui/node_modules/eslint/lib/rules/max-nested-callbacks.js new file mode 100644 index 0000000000000000000000000000000000000000..e97483a62db19fe618990b0d0016c080eb942a71 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/max-nested-callbacks.js @@ -0,0 +1,115 @@ +/** + * @fileoverview Rule to enforce a maximum number of nested callbacks. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce a maximum depth that callbacks can be nested", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-nested-callbacks", + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + type: "object", + properties: { + maximum: { + type: "integer", + minimum: 0, + }, + max: { + type: "integer", + minimum: 0, + }, + }, + additionalProperties: false, + }, + ], + }, + ], + messages: { + exceed: "Too many nested callbacks ({{num}}). Maximum allowed is {{max}}.", + }, + }, + + create(context) { + //-------------------------------------------------------------------------- + // Constants + //-------------------------------------------------------------------------- + const option = context.options[0]; + let THRESHOLD = 10; + + if ( + typeof option === "object" && + (Object.hasOwn(option, "maximum") || Object.hasOwn(option, "max")) + ) { + THRESHOLD = option.maximum || option.max; + } else if (typeof option === "number") { + THRESHOLD = option; + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const callbackStack = []; + + /** + * Checks a given function node for too many callbacks. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function checkFunction(node) { + const parent = node.parent; + + if (parent.type === "CallExpression") { + callbackStack.push(node); + } + + if (callbackStack.length > THRESHOLD) { + const opts = { num: callbackStack.length, max: THRESHOLD }; + + context.report({ node, messageId: "exceed", data: opts }); + } + } + + /** + * Pops the call stack. + * @returns {void} + * @private + */ + function popStack() { + callbackStack.pop(); + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + ArrowFunctionExpression: checkFunction, + "ArrowFunctionExpression:exit": popStack, + + FunctionExpression: checkFunction, + "FunctionExpression:exit": popStack, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/max-params.js b/tools/ui/node_modules/eslint/lib/rules/max-params.js new file mode 100644 index 0000000000000000000000000000000000000000..eeb61edd4e6285526fa2ff7dcc1f40af4a52dfdc --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/max-params.js @@ -0,0 +1,129 @@ +/** + * @fileoverview Rule to flag when a function has too many parameters + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { upperCaseFirst } = require("../shared/string-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + dialects: ["typescript", "javascript"], + language: "javascript", + + docs: { + description: + "Enforce a maximum number of parameters in function definitions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-params", + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + type: "object", + properties: { + maximum: { + type: "integer", + minimum: 0, + }, + max: { + type: "integer", + minimum: 0, + }, + countVoidThis: { + type: "boolean", + description: + "Whether to count a `this` declaration when the type is `void`.", + }, + }, + additionalProperties: false, + }, + ], + }, + ], + messages: { + exceed: "{{name}} has too many parameters ({{count}}). Maximum allowed is {{max}}.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const option = context.options[0]; + let numParams = 3; + let countVoidThis = false; + + if (typeof option === "object") { + if ( + Object.hasOwn(option, "maximum") || + Object.hasOwn(option, "max") + ) { + numParams = option.maximum || option.max; + } + countVoidThis = option.countVoidThis; + } + if (typeof option === "number") { + numParams = option; + } + + /** + * Checks a function to see if it has too many parameters. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function checkFunction(node) { + const hasVoidThisParam = + node.params.length > 0 && + node.params[0].type === "Identifier" && + node.params[0].name === "this" && + node.params[0].typeAnnotation?.typeAnnotation.type === + "TSVoidKeyword"; + + const effectiveParamCount = + hasVoidThisParam && !countVoidThis + ? node.params.length - 1 + : node.params.length; + + if (effectiveParamCount > numParams) { + context.report({ + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + node, + messageId: "exceed", + data: { + name: upperCaseFirst( + astUtils.getFunctionNameWithKind(node), + ), + count: effectiveParamCount, + max: numParams, + }, + }); + } + } + + return { + FunctionDeclaration: checkFunction, + ArrowFunctionExpression: checkFunction, + FunctionExpression: checkFunction, + TSDeclareFunction: checkFunction, + TSFunctionType: checkFunction, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/max-statements-per-line.js b/tools/ui/node_modules/eslint/lib/rules/max-statements-per-line.js new file mode 100644 index 0000000000000000000000000000000000000000..48b37f4fcc670c91fa821d7b3dc9d540038d86c4 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/max-statements-per-line.js @@ -0,0 +1,224 @@ +/** + * @fileoverview Specify the maximum number of statements allowed per line. + * @author Kenneth Williams + * @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: "max-statements-per-line", + url: "https://eslint.style/rules/max-statements-per-line", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce a maximum number of statements allowed per line", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-statements-per-line", + }, + + schema: [ + { + type: "object", + properties: { + max: { + type: "integer", + minimum: 1, + default: 1, + }, + }, + additionalProperties: false, + }, + ], + messages: { + exceed: "This line has {{numberOfStatementsOnThisLine}} {{statements}}. Maximum allowed is {{maxStatementsPerLine}}.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode, + options = context.options[0] || {}, + maxStatementsPerLine = + typeof options.max !== "undefined" ? options.max : 1; + + let lastStatementLine = 0, + numberOfStatementsOnThisLine = 0, + firstExtraStatement; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const SINGLE_CHILD_ALLOWED = + /^(?:(?:DoWhile|For|ForIn|ForOf|If|Labeled|While)Statement|Export(?:Default|Named)Declaration)$/u; + + /** + * Reports with the first extra statement, and clears it. + * @returns {void} + */ + function reportFirstExtraStatementAndClear() { + if (firstExtraStatement) { + context.report({ + node: firstExtraStatement, + messageId: "exceed", + data: { + numberOfStatementsOnThisLine, + maxStatementsPerLine, + statements: + numberOfStatementsOnThisLine === 1 + ? "statement" + : "statements", + }, + }); + } + firstExtraStatement = null; + } + + /** + * Gets the actual last token of a given node. + * @param {ASTNode} node A node to get. This is a node except EmptyStatement. + * @returns {Token} The actual last token. + */ + function getActualLastToken(node) { + return sourceCode.getLastToken(node, astUtils.isNotSemicolonToken); + } + + /** + * Addresses a given node. + * It updates the state of this rule, then reports the node if the node violated this rule. + * @param {ASTNode} node A node to check. + * @returns {void} + */ + function enterStatement(node) { + const line = node.loc.start.line; + + /* + * Skip to allow non-block statements if this is direct child of control statements. + * `if (a) foo();` is counted as 1. + * But `if (a) foo(); else foo();` should be counted as 2. + */ + if ( + SINGLE_CHILD_ALLOWED.test(node.parent.type) && + node.parent.alternate !== node + ) { + return; + } + + // Update state. + if (line === lastStatementLine) { + numberOfStatementsOnThisLine += 1; + } else { + reportFirstExtraStatementAndClear(); + numberOfStatementsOnThisLine = 1; + lastStatementLine = line; + } + + // Reports if the node violated this rule. + if (numberOfStatementsOnThisLine === maxStatementsPerLine + 1) { + firstExtraStatement = firstExtraStatement || node; + } + } + + /** + * Updates the state of this rule with the end line of leaving node to check with the next statement. + * @param {ASTNode} node A node to check. + * @returns {void} + */ + function leaveStatement(node) { + const line = getActualLastToken(node).loc.end.line; + + // Update state. + if (line !== lastStatementLine) { + reportFirstExtraStatementAndClear(); + numberOfStatementsOnThisLine = 1; + lastStatementLine = line; + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + BreakStatement: enterStatement, + ClassDeclaration: enterStatement, + ContinueStatement: enterStatement, + DebuggerStatement: enterStatement, + DoWhileStatement: enterStatement, + ExpressionStatement: enterStatement, + ForInStatement: enterStatement, + ForOfStatement: enterStatement, + ForStatement: enterStatement, + FunctionDeclaration: enterStatement, + IfStatement: enterStatement, + ImportDeclaration: enterStatement, + LabeledStatement: enterStatement, + ReturnStatement: enterStatement, + SwitchStatement: enterStatement, + ThrowStatement: enterStatement, + TryStatement: enterStatement, + VariableDeclaration: enterStatement, + WhileStatement: enterStatement, + WithStatement: enterStatement, + ExportNamedDeclaration: enterStatement, + ExportDefaultDeclaration: enterStatement, + ExportAllDeclaration: enterStatement, + + "BreakStatement:exit": leaveStatement, + "ClassDeclaration:exit": leaveStatement, + "ContinueStatement:exit": leaveStatement, + "DebuggerStatement:exit": leaveStatement, + "DoWhileStatement:exit": leaveStatement, + "ExpressionStatement:exit": leaveStatement, + "ForInStatement:exit": leaveStatement, + "ForOfStatement:exit": leaveStatement, + "ForStatement:exit": leaveStatement, + "FunctionDeclaration:exit": leaveStatement, + "IfStatement:exit": leaveStatement, + "ImportDeclaration:exit": leaveStatement, + "LabeledStatement:exit": leaveStatement, + "ReturnStatement:exit": leaveStatement, + "SwitchStatement:exit": leaveStatement, + "ThrowStatement:exit": leaveStatement, + "TryStatement:exit": leaveStatement, + "VariableDeclaration:exit": leaveStatement, + "WhileStatement:exit": leaveStatement, + "WithStatement:exit": leaveStatement, + "ExportNamedDeclaration:exit": leaveStatement, + "ExportDefaultDeclaration:exit": leaveStatement, + "ExportAllDeclaration:exit": leaveStatement, + "Program:exit": reportFirstExtraStatementAndClear, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/max-statements.js b/tools/ui/node_modules/eslint/lib/rules/max-statements.js new file mode 100644 index 0000000000000000000000000000000000000000..c38482cd1a1b8be717fdca5b154420ae49959761 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/max-statements.js @@ -0,0 +1,188 @@ +/** + * @fileoverview A rule to set the maximum number of statements in a function. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { upperCaseFirst } = require("../shared/string-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce a maximum number of statements allowed in function blocks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-statements", + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + type: "object", + properties: { + maximum: { + type: "integer", + minimum: 0, + }, + max: { + type: "integer", + minimum: 0, + }, + }, + additionalProperties: false, + }, + ], + }, + { + type: "object", + properties: { + ignoreTopLevelFunctions: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + messages: { + exceed: "{{name}} has too many statements ({{count}}). Maximum allowed is {{max}}.", + }, + }, + + create(context) { + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const functionStack = [], + option = context.options[0], + ignoreTopLevelFunctions = + (context.options[1] && + context.options[1].ignoreTopLevelFunctions) || + false, + topLevelFunctions = []; + let maxStatements = 10; + + if ( + typeof option === "object" && + (Object.hasOwn(option, "maximum") || Object.hasOwn(option, "max")) + ) { + maxStatements = option.maximum || option.max; + } else if (typeof option === "number") { + maxStatements = option; + } + + /** + * Reports a node if it has too many statements + * @param {ASTNode} node node to evaluate + * @param {number} count Number of statements in node + * @param {number} max Maximum number of statements allowed + * @returns {void} + * @private + */ + function reportIfTooManyStatements(node, count, max) { + if (count > max) { + const name = upperCaseFirst( + astUtils.getFunctionNameWithKind(node), + ); + + context.report({ + node, + messageId: "exceed", + data: { name, count, max }, + }); + } + } + + /** + * When parsing a new function, store it in our function stack + * @returns {void} + * @private + */ + function startFunction() { + functionStack.push(0); + } + + /** + * Evaluate the node at the end of function + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function endFunction(node) { + const count = functionStack.pop(); + + /* + * This rule does not apply to class static blocks, but we have to track them so + * that statements in them do not count as statements in the enclosing function. + */ + if (node.type === "StaticBlock") { + return; + } + + if (ignoreTopLevelFunctions && functionStack.length === 0) { + topLevelFunctions.push({ node, count }); + } else { + reportIfTooManyStatements(node, count, maxStatements); + } + } + + /** + * Increment the count of the functions + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function countStatements(node) { + functionStack[functionStack.length - 1] += node.body.length; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + FunctionDeclaration: startFunction, + FunctionExpression: startFunction, + ArrowFunctionExpression: startFunction, + StaticBlock: startFunction, + + BlockStatement: countStatements, + + "FunctionDeclaration:exit": endFunction, + "FunctionExpression:exit": endFunction, + "ArrowFunctionExpression:exit": endFunction, + "StaticBlock:exit": endFunction, + + "Program:exit"() { + if (topLevelFunctions.length === 1) { + return; + } + + topLevelFunctions.forEach(element => { + const count = element.count; + const node = element.node; + + reportIfTooManyStatements(node, count, maxStatements); + }); + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/multiline-comment-style.js b/tools/ui/node_modules/eslint/lib/rules/multiline-comment-style.js new file mode 100644 index 0000000000000000000000000000000000000000..463e7a7343253ff25f29a45b7605c1e947847d45 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/multiline-comment-style.js @@ -0,0 +1,652 @@ +/** + * @fileoverview enforce a particular style for multiline comments + * @author Teddy Katz + * @deprecated in ESLint v9.3.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: "9.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: "multiline-comment-style", + url: "https://eslint.style/rules/multiline-comment-style", + }, + }, + ], + }, + type: "suggestion", + docs: { + description: "Enforce a particular style for multiline comments", + recommended: false, + url: "https://eslint.org/docs/latest/rules/multiline-comment-style", + }, + + fixable: "whitespace", + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["starred-block", "bare-block"], + }, + ], + additionalItems: false, + }, + { + type: "array", + items: [ + { + enum: ["separate-lines"], + }, + { + type: "object", + properties: { + checkJSDoc: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + additionalItems: false, + }, + ], + }, + messages: { + expectedBlock: + "Expected a block comment instead of consecutive line comments.", + expectedBareBlock: + "Expected a block comment without padding stars.", + startNewline: "Expected a linebreak after '/*'.", + endNewline: "Expected a linebreak before '*/'.", + missingStar: "Expected a '*' at the start of this line.", + alignment: + "Expected this line to be aligned with the start of the comment.", + expectedLines: + "Expected multiple line comments instead of a block comment.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const option = context.options[0] || "starred-block"; + const params = context.options[1] || {}; + const checkJSDoc = !!params.checkJSDoc; + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Checks if a comment line is starred. + * @param {string} line A string representing a comment line. + * @returns {boolean} Whether or not the comment line is starred. + */ + function isStarredCommentLine(line) { + return /^\s*\*/u.test(line); + } + + /** + * Checks if a comment group is in starred-block form. + * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment. + * @returns {boolean} Whether or not the comment group is in starred block form. + */ + function isStarredBlockComment([firstComment]) { + if (firstComment.type !== "Block") { + return false; + } + + const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER); + + // The first and last lines can only contain whitespace. + return ( + lines.length > 0 && + lines.every((line, i) => + (i === 0 || i === lines.length - 1 + ? /^\s*$/u + : /^\s*\*/u + ).test(line), + ) + ); + } + + /** + * Checks if a comment group is in JSDoc form. + * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment. + * @returns {boolean} Whether or not the comment group is in JSDoc form. + */ + function isJSDocComment([firstComment]) { + if (firstComment.type !== "Block") { + return false; + } + + const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER); + + return ( + /^\*\s*$/u.test(lines[0]) && + lines.slice(1, -1).every(line => /^\s* /u.test(line)) && + /^\s*$/u.test(lines.at(-1)) + ); + } + + /** + * Processes a comment group that is currently in separate-line form, calculating the offset for each line. + * @param {Token[]} commentGroup A group of comments containing multiple line comments. + * @returns {string[]} An array of the processed lines. + */ + function processSeparateLineComments(commentGroup) { + const allLinesHaveLeadingSpace = commentGroup + .map(({ value }) => value) + .filter(line => line.trim().length) + .every(line => line.startsWith(" ")); + + return commentGroup.map(({ value }) => + allLinesHaveLeadingSpace ? value.replace(/^ /u, "") : value, + ); + } + + /** + * Processes a comment group that is currently in starred-block form, calculating the offset for each line. + * @param {Token} comment A single block comment token in starred-block form. + * @returns {string[]} An array of the processed lines. + */ + function processStarredBlockComment(comment) { + const lines = comment.value + .split(astUtils.LINEBREAK_MATCHER) + .filter( + (line, i, linesArr) => + !(i === 0 || i === linesArr.length - 1), + ) + .map(line => line.replace(/^\s*$/u, "")); + const allLinesHaveLeadingSpace = lines + .map(line => line.replace(/\s*\*/u, "")) + .filter(line => line.trim().length) + .every(line => line.startsWith(" ")); + + return lines.map(line => + line.replace( + allLinesHaveLeadingSpace ? /\s*\* ?/u : /\s*\*/u, + "", + ), + ); + } + + /** + * Processes a comment group that is currently in bare-block form, calculating the offset for each line. + * @param {Token} comment A single block comment token in bare-block form. + * @returns {string[]} An array of the processed lines. + */ + function processBareBlockComment(comment) { + const lines = comment.value + .split(astUtils.LINEBREAK_MATCHER) + .map(line => line.replace(/^\s*$/u, "")); + const leadingWhitespace = `${sourceCode.text.slice(comment.range[0] - comment.loc.start.column, comment.range[0])} `; + let offset = ""; + + /* + * Calculate the offset of the least indented line and use that as the basis for offsetting all the lines. + * The first line should not be checked because it is inline with the opening block comment delimiter. + */ + for (const [i, line] of lines.entries()) { + if (!line.trim().length || i === 0) { + continue; + } + + const [, lineOffset] = line.match(/^(\s*\*?\s*)/u); + + if (lineOffset.length < leadingWhitespace.length) { + const newOffset = leadingWhitespace.slice( + lineOffset.length - leadingWhitespace.length, + ); + + if (newOffset.length > offset.length) { + offset = newOffset; + } + } + } + + return lines.map(line => { + const match = line.match(/^(\s*\*?\s*)(.*)/u); + const [, lineOffset, lineContents] = match; + + if (lineOffset.length > leadingWhitespace.length) { + return `${lineOffset.slice(leadingWhitespace.length - (offset.length + lineOffset.length))}${lineContents}`; + } + + if (lineOffset.length < leadingWhitespace.length) { + return `${lineOffset.slice(leadingWhitespace.length)}${lineContents}`; + } + + return lineContents; + }); + } + + /** + * Gets a list of comment lines in a group, formatting leading whitespace as necessary. + * @param {Token[]} commentGroup A group of comments containing either multiple line comments or a single block comment. + * @returns {string[]} A list of comment lines. + */ + function getCommentLines(commentGroup) { + const [firstComment] = commentGroup; + + if (firstComment.type === "Line") { + return processSeparateLineComments(commentGroup); + } + + if (isStarredBlockComment(commentGroup)) { + return processStarredBlockComment(firstComment); + } + + return processBareBlockComment(firstComment); + } + + /** + * Gets the initial offset (whitespace) from the beginning of a line to a given comment token. + * @param {Token} comment The token to check. + * @returns {string} The offset from the beginning of a line to the token. + */ + function getInitialOffset(comment) { + return sourceCode.text.slice( + comment.range[0] - comment.loc.start.column, + comment.range[0], + ); + } + + /** + * Converts a comment into starred-block form + * @param {Token} firstComment The first comment of the group being converted + * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment + * @returns {string} A representation of the comment value in starred-block form, excluding start and end markers + */ + function convertToStarredBlock(firstComment, commentLinesList) { + const initialOffset = getInitialOffset(firstComment); + + return `/*\n${commentLinesList.map(line => `${initialOffset} * ${line}`).join("\n")}\n${initialOffset} */`; + } + + /** + * Converts a comment into separate-line form + * @param {Token} firstComment The first comment of the group being converted + * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment + * @returns {string} A representation of the comment value in separate-line form + */ + function convertToSeparateLines(firstComment, commentLinesList) { + return commentLinesList + .map(line => `// ${line}`) + .join(`\n${getInitialOffset(firstComment)}`); + } + + /** + * Converts a comment into bare-block form + * @param {Token} firstComment The first comment of the group being converted + * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment + * @returns {string} A representation of the comment value in bare-block form + */ + function convertToBlock(firstComment, commentLinesList) { + return `/* ${commentLinesList.join(`\n${getInitialOffset(firstComment)} `)} */`; + } + + /** + * Each method checks a group of comments to see if it's valid according to the given option. + * @param {Token[]} commentGroup A list of comments that appear together. This will either contain a single + * block comment or multiple line comments. + * @returns {void} + */ + const commentGroupCheckers = { + "starred-block"(commentGroup) { + const [firstComment] = commentGroup; + const commentLines = getCommentLines(commentGroup); + + if (commentLines.some(value => value.includes("*/"))) { + return; + } + + if (commentGroup.length > 1) { + context.report({ + loc: { + start: firstComment.loc.start, + end: commentGroup.at(-1).loc.end, + }, + messageId: "expectedBlock", + fix(fixer) { + const range = [ + firstComment.range[0], + commentGroup.at(-1).range[1], + ]; + + return commentLines.some(value => + value.startsWith("/"), + ) + ? null + : fixer.replaceTextRange( + range, + convertToStarredBlock( + firstComment, + commentLines, + ), + ); + }, + }); + } else { + const lines = firstComment.value.split( + astUtils.LINEBREAK_MATCHER, + ); + const expectedLeadingWhitespace = + getInitialOffset(firstComment); + const expectedLinePrefix = `${expectedLeadingWhitespace} *`; + + if (!/^\*?\s*$/u.test(lines[0])) { + const start = firstComment.value.startsWith("*") + ? firstComment.range[0] + 1 + : firstComment.range[0]; + + context.report({ + loc: { + start: firstComment.loc.start, + end: { + line: firstComment.loc.start.line, + column: firstComment.loc.start.column + 2, + }, + }, + messageId: "startNewline", + fix: fixer => + fixer.insertTextAfterRange( + [start, start + 2], + `\n${expectedLinePrefix}`, + ), + }); + } + + if (!/^\s*$/u.test(lines.at(-1))) { + context.report({ + loc: { + start: { + line: firstComment.loc.end.line, + column: firstComment.loc.end.column - 2, + }, + end: firstComment.loc.end, + }, + messageId: "endNewline", + fix: fixer => + fixer.replaceTextRange( + [ + firstComment.range[1] - 2, + firstComment.range[1], + ], + `\n${expectedLinePrefix}/`, + ), + }); + } + + for ( + let lineNumber = firstComment.loc.start.line + 1; + lineNumber <= firstComment.loc.end.line; + lineNumber++ + ) { + const lineText = sourceCode.lines[lineNumber - 1]; + const errorType = isStarredCommentLine(lineText) + ? "alignment" + : "missingStar"; + + if (!lineText.startsWith(expectedLinePrefix)) { + context.report({ + loc: { + start: { line: lineNumber, column: 0 }, + end: { + line: lineNumber, + column: lineText.length, + }, + }, + messageId: errorType, + fix(fixer) { + const lineStartIndex = + sourceCode.getIndexFromLoc({ + line: lineNumber, + column: 0, + }); + + if (errorType === "alignment") { + const [, commentTextPrefix = ""] = + lineText.match(/^(\s*\*)/u) || []; + const commentTextStartIndex = + lineStartIndex + + commentTextPrefix.length; + + return fixer.replaceTextRange( + [ + lineStartIndex, + commentTextStartIndex, + ], + expectedLinePrefix, + ); + } + + const [, commentTextPrefix = ""] = + lineText.match(/^(\s*)/u) || []; + const commentTextStartIndex = + lineStartIndex + + commentTextPrefix.length; + let offset; + + for (const [idx, line] of lines.entries()) { + if (!/\S+/u.test(line)) { + continue; + } + + const lineTextToAlignWith = + sourceCode.lines[ + firstComment.loc.start.line - + 1 + + idx + ]; + const [ + , + prefix = "", + initialOffset = "", + ] = + lineTextToAlignWith.match( + /^(\s*(?:\/?\*)?(\s*))/u, + ) || []; + + offset = `${commentTextPrefix.slice(prefix.length)}${initialOffset}`; + + if ( + /^\s*\//u.test(lineText) && + offset.length === 0 + ) { + offset += " "; + } + break; + } + + return fixer.replaceTextRange( + [lineStartIndex, commentTextStartIndex], + `${expectedLinePrefix}${offset}`, + ); + }, + }); + } + } + } + }, + "separate-lines"(commentGroup) { + const [firstComment] = commentGroup; + + const isJSDoc = isJSDocComment(commentGroup); + + if (firstComment.type !== "Block" || (!checkJSDoc && isJSDoc)) { + return; + } + + let commentLines = getCommentLines(commentGroup); + + if (isJSDoc) { + commentLines = commentLines.slice( + 1, + commentLines.length - 1, + ); + } + + const tokenAfter = sourceCode.getTokenAfter(firstComment, { + includeComments: true, + }); + + if ( + tokenAfter && + firstComment.loc.end.line === tokenAfter.loc.start.line + ) { + return; + } + + context.report({ + loc: { + start: firstComment.loc.start, + end: { + line: firstComment.loc.start.line, + column: firstComment.loc.start.column + 2, + }, + }, + messageId: "expectedLines", + fix(fixer) { + return fixer.replaceText( + firstComment, + convertToSeparateLines(firstComment, commentLines), + ); + }, + }); + }, + "bare-block"(commentGroup) { + if (isJSDocComment(commentGroup)) { + return; + } + + const [firstComment] = commentGroup; + const commentLines = getCommentLines(commentGroup); + + // Disallows consecutive line comments in favor of using a block comment. + if ( + firstComment.type === "Line" && + commentLines.length > 1 && + !commentLines.some(value => value.includes("*/")) + ) { + context.report({ + loc: { + start: firstComment.loc.start, + end: commentGroup.at(-1).loc.end, + }, + messageId: "expectedBlock", + fix(fixer) { + return fixer.replaceTextRange( + [ + firstComment.range[0], + commentGroup.at(-1).range[1], + ], + convertToBlock(firstComment, commentLines), + ); + }, + }); + } + + // Prohibits block comments from having a * at the beginning of each line. + if (isStarredBlockComment(commentGroup)) { + context.report({ + loc: { + start: firstComment.loc.start, + end: { + line: firstComment.loc.start.line, + column: firstComment.loc.start.column + 2, + }, + }, + messageId: "expectedBareBlock", + fix(fixer) { + return fixer.replaceText( + firstComment, + convertToBlock(firstComment, commentLines), + ); + }, + }); + } + }, + }; + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + Program() { + return sourceCode + .getAllComments() + .filter(comment => comment.type !== "Shebang") + .filter( + comment => + !astUtils.COMMENTS_IGNORE_PATTERN.test( + comment.value, + ), + ) + .filter(comment => { + const tokenBefore = sourceCode.getTokenBefore(comment, { + includeComments: true, + }); + + return ( + !tokenBefore || + tokenBefore.loc.end.line < comment.loc.start.line + ); + }) + .reduce((commentGroups, comment, index, commentList) => { + const tokenBefore = sourceCode.getTokenBefore(comment, { + includeComments: true, + }); + + if ( + comment.type === "Line" && + index && + commentList[index - 1].type === "Line" && + tokenBefore && + tokenBefore.loc.end.line === + comment.loc.start.line - 1 && + tokenBefore === commentList[index - 1] + ) { + commentGroups.at(-1).push(comment); + } else { + commentGroups.push([comment]); + } + + return commentGroups; + }, []) + .filter( + commentGroup => + !( + commentGroup.length === 1 && + commentGroup[0].loc.start.line === + commentGroup[0].loc.end.line + ), + ) + .forEach(commentGroupCheckers[option]); + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/multiline-ternary.js b/tools/ui/node_modules/eslint/lib/rules/multiline-ternary.js new file mode 100644 index 0000000000000000000000000000000000000000..5590fe4523ba70b0fb56c01c91b8e1ded00a5b83 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/multiline-ternary.js @@ -0,0 +1,257 @@ +/** + * @fileoverview Enforce newlines between operands of ternary expressions + * @author Kai Cataldo + * @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: "multiline-ternary", + url: "https://eslint.style/rules/multiline-ternary", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce newlines between operands of ternary expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/multiline-ternary", + }, + + schema: [ + { + enum: ["always", "always-multiline", "never"], + }, + ], + + messages: { + expectedTestCons: + "Expected newline between test and consequent of ternary expression.", + expectedConsAlt: + "Expected newline between consequent and alternate of ternary expression.", + unexpectedTestCons: + "Unexpected newline between test and consequent of ternary expression.", + unexpectedConsAlt: + "Unexpected newline between consequent and alternate of ternary expression.", + }, + + fixable: "whitespace", + }, + + create(context) { + const sourceCode = context.sourceCode; + const option = context.options[0]; + const multiline = option !== "never"; + const allowSingleLine = option === "always-multiline"; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + ConditionalExpression(node) { + const questionToken = sourceCode.getTokenAfter( + node.test, + astUtils.isNotClosingParenToken, + ); + const colonToken = sourceCode.getTokenAfter( + node.consequent, + astUtils.isNotClosingParenToken, + ); + + const firstTokenOfTest = sourceCode.getFirstToken(node); + const lastTokenOfTest = + sourceCode.getTokenBefore(questionToken); + const firstTokenOfConsequent = + sourceCode.getTokenAfter(questionToken); + const lastTokenOfConsequent = + sourceCode.getTokenBefore(colonToken); + const firstTokenOfAlternate = + sourceCode.getTokenAfter(colonToken); + + const areTestAndConsequentOnSameLine = + astUtils.isTokenOnSameLine( + lastTokenOfTest, + firstTokenOfConsequent, + ); + const areConsequentAndAlternateOnSameLine = + astUtils.isTokenOnSameLine( + lastTokenOfConsequent, + firstTokenOfAlternate, + ); + + const hasComments = !!sourceCode.getCommentsInside(node).length; + + if (!multiline) { + if (!areTestAndConsequentOnSameLine) { + context.report({ + node: node.test, + loc: { + start: firstTokenOfTest.loc.start, + end: lastTokenOfTest.loc.end, + }, + messageId: "unexpectedTestCons", + fix(fixer) { + if (hasComments) { + return null; + } + const fixers = []; + const areTestAndQuestionOnSameLine = + astUtils.isTokenOnSameLine( + lastTokenOfTest, + questionToken, + ); + const areQuestionAndConsOnSameLine = + astUtils.isTokenOnSameLine( + questionToken, + firstTokenOfConsequent, + ); + + if (!areTestAndQuestionOnSameLine) { + fixers.push( + fixer.removeRange([ + lastTokenOfTest.range[1], + questionToken.range[0], + ]), + ); + } + if (!areQuestionAndConsOnSameLine) { + fixers.push( + fixer.removeRange([ + questionToken.range[1], + firstTokenOfConsequent.range[0], + ]), + ); + } + + return fixers; + }, + }); + } + + if (!areConsequentAndAlternateOnSameLine) { + context.report({ + node: node.consequent, + loc: { + start: firstTokenOfConsequent.loc.start, + end: lastTokenOfConsequent.loc.end, + }, + messageId: "unexpectedConsAlt", + fix(fixer) { + if (hasComments) { + return null; + } + const fixers = []; + const areConsAndColonOnSameLine = + astUtils.isTokenOnSameLine( + lastTokenOfConsequent, + colonToken, + ); + const areColonAndAltOnSameLine = + astUtils.isTokenOnSameLine( + colonToken, + firstTokenOfAlternate, + ); + + if (!areConsAndColonOnSameLine) { + fixers.push( + fixer.removeRange([ + lastTokenOfConsequent.range[1], + colonToken.range[0], + ]), + ); + } + if (!areColonAndAltOnSameLine) { + fixers.push( + fixer.removeRange([ + colonToken.range[1], + firstTokenOfAlternate.range[0], + ]), + ); + } + + return fixers; + }, + }); + } + } else { + if ( + allowSingleLine && + node.loc.start.line === node.loc.end.line + ) { + return; + } + + if (areTestAndConsequentOnSameLine) { + context.report({ + node: node.test, + loc: { + start: firstTokenOfTest.loc.start, + end: lastTokenOfTest.loc.end, + }, + messageId: "expectedTestCons", + fix: fixer => + hasComments + ? null + : fixer.replaceTextRange( + [ + lastTokenOfTest.range[1], + questionToken.range[0], + ], + "\n", + ), + }); + } + + if (areConsequentAndAlternateOnSameLine) { + context.report({ + node: node.consequent, + loc: { + start: firstTokenOfConsequent.loc.start, + end: lastTokenOfConsequent.loc.end, + }, + messageId: "expectedConsAlt", + fix: fixer => + hasComments + ? null + : fixer.replaceTextRange( + [ + lastTokenOfConsequent.range[1], + colonToken.range[0], + ], + "\n", + ), + }); + } + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/new-cap.js b/tools/ui/node_modules/eslint/lib/rules/new-cap.js new file mode 100644 index 0000000000000000000000000000000000000000..caea1a8bea8939e281c655d1bb628adf131b2543 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/new-cap.js @@ -0,0 +1,277 @@ +/** + * @fileoverview Rule to flag use of constructors without capital letters + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const CAPS_ALLOWED = [ + "Array", + "Boolean", + "Date", + "Error", + "Function", + "Number", + "Object", + "RegExp", + "String", + "Symbol", + "BigInt", +]; + +/** + * A reducer function to invert an array to an Object mapping the string form of the key, to `true`. + * @param {Object} map Accumulator object for the reduce. + * @param {string} key Object key to set to `true`. + * @returns {Object} Returns the updated Object for further reduction. + */ +function invert(map, key) { + map[key] = true; + return map; +} + +/** + * Creates an object with the cap is new exceptions as its keys and true as their values. + * @param {Object} config Rule configuration + * @returns {Object} Object with cap is new exceptions. + */ +function calculateCapIsNewExceptions(config) { + const capIsNewExceptions = Array.from( + new Set([...config.capIsNewExceptions, ...CAPS_ALLOWED]), + ); + + return capIsNewExceptions.reduce(invert, {}); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Require constructor names to begin with a capital letter", + recommended: false, + url: "https://eslint.org/docs/latest/rules/new-cap", + }, + + schema: [ + { + type: "object", + properties: { + newIsCap: { + type: "boolean", + }, + capIsNew: { + type: "boolean", + }, + newIsCapExceptions: { + type: "array", + items: { + type: "string", + }, + }, + newIsCapExceptionPattern: { + type: "string", + }, + capIsNewExceptions: { + type: "array", + items: { + type: "string", + }, + }, + capIsNewExceptionPattern: { + type: "string", + }, + properties: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + defaultOptions: [ + { + capIsNew: true, + capIsNewExceptions: CAPS_ALLOWED, + newIsCap: true, + newIsCapExceptions: [], + properties: true, + }, + ], + + messages: { + upper: "A function with a name starting with an uppercase letter should only be used as a constructor.", + lower: "A constructor name should not start with a lowercase letter.", + }, + }, + + create(context) { + const [config] = context.options; + const skipProperties = !config.properties; + + const newIsCapExceptions = config.newIsCapExceptions.reduce(invert, {}); + const newIsCapExceptionPattern = config.newIsCapExceptionPattern + ? new RegExp(config.newIsCapExceptionPattern, "u") + : null; + + const capIsNewExceptions = calculateCapIsNewExceptions(config); + const capIsNewExceptionPattern = config.capIsNewExceptionPattern + ? new RegExp(config.capIsNewExceptionPattern, "u") + : null; + + const listeners = {}; + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Get exact callee name from expression + * @param {ASTNode} node CallExpression or NewExpression node + * @returns {string} name + */ + function extractNameFromExpression(node) { + return node.callee.type === "Identifier" + ? node.callee.name + : astUtils.getStaticPropertyName(node.callee) || ""; + } + + /** + * Returns the capitalization state of the string - + * Whether the first character is uppercase, lowercase, or non-alphabetic + * @param {string} str String + * @returns {string} capitalization state: "non-alpha", "lower", or "upper" + */ + function getCap(str) { + const firstChar = str.charAt(0); + + const firstCharLower = firstChar.toLowerCase(); + const firstCharUpper = firstChar.toUpperCase(); + + if (firstCharLower === firstCharUpper) { + // char has no uppercase variant, so it's non-alphabetic + return "non-alpha"; + } + if (firstChar === firstCharLower) { + return "lower"; + } + return "upper"; + } + + /** + * Check if capitalization is allowed for a CallExpression + * @param {Object} allowedMap Object mapping calleeName to a Boolean + * @param {ASTNode} node CallExpression node + * @param {string} calleeName Capitalized callee name from a CallExpression + * @param {Object} pattern RegExp object from options pattern + * @returns {boolean} Returns true if the callee may be capitalized + */ + function isCapAllowed(allowedMap, node, calleeName, pattern) { + const sourceText = sourceCode.getText(node.callee); + + if (allowedMap[calleeName] || allowedMap[sourceText]) { + return true; + } + + if (pattern && pattern.test(sourceText)) { + return true; + } + + const callee = astUtils.skipChainExpression(node.callee); + + if (calleeName === "UTC" && callee.type === "MemberExpression") { + // allow if callee is Date.UTC + return ( + callee.object.type === "Identifier" && + callee.object.name === "Date" + ); + } + + return skipProperties && callee.type === "MemberExpression"; + } + + /** + * Reports the given messageId for the given node. The location will be the start of the property or the callee. + * @param {ASTNode} node CallExpression or NewExpression node. + * @param {string} messageId The messageId to report. + * @returns {void} + */ + function report(node, messageId) { + let callee = astUtils.skipChainExpression(node.callee); + + if (callee.type === "MemberExpression") { + callee = callee.property; + } + + context.report({ node, loc: callee.loc, messageId }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + if (config.newIsCap) { + listeners.NewExpression = function (node) { + const constructorName = extractNameFromExpression(node); + + if (constructorName) { + const capitalization = getCap(constructorName); + const isAllowed = + capitalization !== "lower" || + isCapAllowed( + newIsCapExceptions, + node, + constructorName, + newIsCapExceptionPattern, + ); + + if (!isAllowed) { + report(node, "lower"); + } + } + }; + } + + if (config.capIsNew) { + listeners.CallExpression = function (node) { + const calleeName = extractNameFromExpression(node); + + if (calleeName) { + const capitalization = getCap(calleeName); + const isAllowed = + capitalization !== "upper" || + isCapAllowed( + capIsNewExceptions, + node, + calleeName, + capIsNewExceptionPattern, + ); + + if (!isAllowed) { + report(node, "upper"); + } + } + }; + } + + return listeners; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/new-parens.js b/tools/ui/node_modules/eslint/lib/rules/new-parens.js new file mode 100644 index 0000000000000000000000000000000000000000..e8cb8db2ace07c3b4d32a95efe556ecf6e355d57 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/new-parens.js @@ -0,0 +1,120 @@ +/** + * @fileoverview Rule to flag when using constructor without parentheses + * @author Ilya Volodin + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// 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: "new-parens", + url: "https://eslint.style/rules/new-parens", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce or disallow parentheses when invoking a constructor with no arguments", + recommended: false, + url: "https://eslint.org/docs/latest/rules/new-parens", + }, + + fixable: "code", + schema: [ + { + enum: ["always", "never"], + }, + ], + messages: { + missing: "Missing '()' invoking a constructor.", + unnecessary: + "Unnecessary '()' invoking a constructor with no arguments.", + }, + }, + + create(context) { + const options = context.options; + const always = options[0] !== "never"; // Default is always + + const sourceCode = context.sourceCode; + + return { + NewExpression(node) { + if (node.arguments.length !== 0) { + return; // if there are arguments, there have to be parens + } + + const lastToken = sourceCode.getLastToken(node); + const hasLastParen = + lastToken && astUtils.isClosingParenToken(lastToken); + + // `hasParens` is true only if the new expression ends with its own parens, e.g., new new foo() does not end with its own parens + const hasParens = + hasLastParen && + astUtils.isOpeningParenToken( + sourceCode.getTokenBefore(lastToken), + ) && + node.callee.range[1] < node.range[1]; + + if (always) { + if (!hasParens) { + context.report({ + node, + messageId: "missing", + fix: fixer => fixer.insertTextAfter(node, "()"), + }); + } + } else { + if (hasParens) { + context.report({ + node, + messageId: "unnecessary", + fix: fixer => [ + fixer.remove( + sourceCode.getTokenBefore(lastToken), + ), + fixer.remove(lastToken), + fixer.insertTextBefore(node, "("), + fixer.insertTextAfter(node, ")"), + ], + }); + } + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/newline-after-var.js b/tools/ui/node_modules/eslint/lib/rules/newline-after-var.js new file mode 100644 index 0000000000000000000000000000000000000000..76d29117c39099af2dd066ae5370e61410be4ca4 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/newline-after-var.js @@ -0,0 +1,307 @@ +/** + * @fileoverview Rule to check empty newline after "var" statement + * @author Gopal Venkatesan + * @deprecated in ESLint v4.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: + "Require or disallow an empty line after variable declarations", + recommended: false, + url: "https://eslint.org/docs/latest/rules/newline-after-var", + }, + schema: [ + { + enum: ["never", "always"], + }, + ], + fixable: "whitespace", + messages: { + expected: "Expected blank line after variable declarations.", + unexpected: "Unexpected blank line after variable declarations.", + }, + + 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; + + // Default `mode` to "always". + const mode = context.options[0] === "never" ? "never" : "always"; + + // Cache starting and ending line numbers of comments for faster lookup + const commentEndLine = sourceCode + .getAllComments() + .reduce((result, token) => { + result[token.loc.start.line] = token.loc.end.line; + return result; + }, {}); + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Gets a token from the given node to compare line to the next statement. + * + * In general, the token is the last token of the node. However, the token is the second last token if the following conditions satisfy. + * + * - The last token is semicolon. + * - The semicolon is on a different line from the previous token of the semicolon. + * + * This behavior would address semicolon-less style code. e.g.: + * + * var foo = 1 + * + * ;(a || b).doSomething() + * @param {ASTNode} node The node to get. + * @returns {Token} The token to compare line to the next statement. + */ + function getLastToken(node) { + const lastToken = sourceCode.getLastToken(node); + + if (lastToken.type === "Punctuator" && lastToken.value === ";") { + const prevToken = sourceCode.getTokenBefore(lastToken); + + if (prevToken.loc.end.line !== lastToken.loc.start.line) { + return prevToken; + } + } + + return lastToken; + } + + /** + * Determine if provided keyword is a variable declaration + * @private + * @param {string} keyword keyword to test + * @returns {boolean} True if `keyword` is a type of var + */ + function isVar(keyword) { + return ( + keyword === "var" || keyword === "let" || keyword === "const" + ); + } + + /** + * 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" + ); + } + + /** + * Determine if provided keyword is an export specifiers + * @private + * @param {string} nodeType nodeType to test + * @returns {boolean} True if `nodeType` is an export specifier + */ + function isExportSpecifier(nodeType) { + return ( + nodeType === "ExportNamedDeclaration" || + nodeType === "ExportSpecifier" || + nodeType === "ExportDefaultDeclaration" || + nodeType === "ExportAllDeclaration" + ); + } + + /** + * Determine if provided node is the last of their parent block. + * @private + * @param {ASTNode} node node to test + * @returns {boolean} True if `node` is last of their parent block. + */ + function isLastNode(node) { + const token = sourceCode.getTokenAfter(node); + + return ( + !token || (token.type === "Punctuator" && token.value === "}") + ); + } + + /** + * Gets the last line of a group of consecutive comments + * @param {number} commentStartLine The starting line of the group + * @returns {number} The number of the last comment line of the group + */ + function getLastCommentLineOfBlock(commentStartLine) { + const currentCommentEnd = commentEndLine[commentStartLine]; + + return commentEndLine[currentCommentEnd + 1] + ? getLastCommentLineOfBlock(currentCommentEnd + 1) + : currentCommentEnd; + } + + /** + * Determine if a token starts more than one line after a comment ends + * @param {token} token The token being checked + * @param {integer} commentStartLine The line number on which the comment starts + * @returns {boolean} True if `token` does not start immediately after a comment + */ + function hasBlankLineAfterComment(token, commentStartLine) { + return ( + token.loc.start.line > + getLastCommentLineOfBlock(commentStartLine) + 1 + ); + } + + /** + * Checks that a blank line exists after a variable declaration when mode is + * set to "always", or checks that there is no blank line when mode is set + * to "never" + * @private + * @param {ASTNode} node `VariableDeclaration` node to test + * @returns {void} + */ + function checkForBlankLine(node) { + /* + * lastToken is the last token on the node's line. It will usually also be the last token of the node, but it will + * sometimes be second-last if there is a semicolon on a different line. + */ + const lastToken = getLastToken(node), + /* + * If lastToken is the last token of the node, nextToken should be the token after the node. Otherwise, nextToken + * is the last token of the node. + */ + nextToken = + lastToken === sourceCode.getLastToken(node) + ? sourceCode.getTokenAfter(node) + : sourceCode.getLastToken(node), + nextLineNum = lastToken.loc.end.line + 1; + + // Ignore if there is no following statement + if (!nextToken) { + return; + } + + // Ignore if parent of node is a for variant + if (isForTypeSpecifier(node.parent.type)) { + return; + } + + // Ignore if parent of node is an export specifier + if (isExportSpecifier(node.parent.type)) { + return; + } + + /* + * Some coding styles use multiple `var` statements, so do nothing if + * the next token is a `var` statement. + */ + if (nextToken.type === "Keyword" && isVar(nextToken.value)) { + return; + } + + // Ignore if it is last statement in a block + if (isLastNode(node)) { + return; + } + + // Next statement is not a `var`... + const noNextLineToken = nextToken.loc.start.line > nextLineNum; + const hasNextLineComment = + typeof commentEndLine[nextLineNum] !== "undefined"; + + if (mode === "never" && noNextLineToken && !hasNextLineComment) { + context.report({ + node, + messageId: "unexpected", + fix(fixer) { + const linesBetween = sourceCode + .getText() + .slice(lastToken.range[1], nextToken.range[0]) + .split(astUtils.LINEBREAK_MATCHER); + + return fixer.replaceTextRange( + [lastToken.range[1], nextToken.range[0]], + `${linesBetween.slice(0, -1).join("")}\n${linesBetween.at(-1)}`, + ); + }, + }); + } + + // Token on the next line, or comment without blank line + if ( + mode === "always" && + (!noNextLineToken || + (hasNextLineComment && + !hasBlankLineAfterComment(nextToken, nextLineNum))) + ) { + context.report({ + node, + messageId: "expected", + fix(fixer) { + if ( + (noNextLineToken + ? getLastCommentLineOfBlock(nextLineNum) + : lastToken.loc.end.line) === + nextToken.loc.start.line + ) { + return fixer.insertTextBefore(nextToken, "\n\n"); + } + + return fixer.insertTextBeforeRange( + [ + nextToken.range[0] - nextToken.loc.start.column, + nextToken.range[1], + ], + "\n", + ); + }, + }); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + VariableDeclaration: checkForBlankLine, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/newline-before-return.js b/tools/ui/node_modules/eslint/lib/rules/newline-before-return.js new file mode 100644 index 0000000000000000000000000000000000000000..d9ebc9c18007a04c31d448e19a1774b5c7a98ab1 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/newline-per-chained-call.js b/tools/ui/node_modules/eslint/lib/rules/newline-per-chained-call.js new file mode 100644 index 0000000000000000000000000000000000000000..c56e946606ac0b7b71a0b4f67c808ab9a2a9c130 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-alert.js b/tools/ui/node_modules/eslint/lib/rules/no-alert.js new file mode 100644 index 0000000000000000000000000000000000000000..d1a3c5baadf5167882e2d864d76375e35d4f91cd --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-array-constructor.js b/tools/ui/node_modules/eslint/lib/rules/no-array-constructor.js new file mode 100644 index 0000000000000000000000000000000000000000..46e8f6b748634d900f3264d9b627cb17fc11c7e9 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-array-constructor.js @@ -0,0 +1,195 @@ +/** + * @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: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "suggestion", + + docs: { + description: "Disallow `Array` constructors", + 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/tools/ui/node_modules/eslint/lib/rules/no-async-promise-executor.js b/tools/ui/node_modules/eslint/lib/rules/no-async-promise-executor.js new file mode 100644 index 0000000000000000000000000000000000000000..22edd48f7a339545d12f670f980a00655bf332ff --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-async-promise-executor.js @@ -0,0 +1,45 @@ +/** + * @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) { + return { + "NewExpression[callee.name='Promise'][arguments.0.async=true]"( + node, + ) { + context.report({ + node: context.sourceCode.getFirstToken( + node.arguments[0], + token => token.value === "async", + ), + messageId: "async", + }); + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/no-await-in-loop.js b/tools/ui/node_modules/eslint/lib/rules/no-await-in-loop.js new file mode 100644 index 0000000000000000000000000000000000000000..2945257d11047d6bb396b2b1e2b2ae04ab5843ad --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-bitwise.js b/tools/ui/node_modules/eslint/lib/rules/no-bitwise.js new file mode 100644 index 0000000000000000000000000000000000000000..10149ed618e99618776150b2c2daff859028e6f8 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-buffer-constructor.js b/tools/ui/node_modules/eslint/lib/rules/no-buffer-constructor.js new file mode 100644 index 0000000000000000000000000000000000000000..6a48b55737b1e3bbbc91a54a17a2b2b4d455d955 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-caller.js b/tools/ui/node_modules/eslint/lib/rules/no-caller.js new file mode 100644 index 0000000000000000000000000000000000000000..50790ff0e179a1a865136fdbe0cd4f3466740e22 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-case-declarations.js b/tools/ui/node_modules/eslint/lib/rules/no-case-declarations.js new file mode 100644 index 0000000000000000000000000000000000000000..168594aad9dce8c26c7265e24dc217ac1ca10bcd --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-catch-shadow.js b/tools/ui/node_modules/eslint/lib/rules/no-catch-shadow.js new file mode 100644 index 0000000000000000000000000000000000000000..b47ac324830551cae063e97e89fdfa4f385baac4 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-class-assign.js b/tools/ui/node_modules/eslint/lib/rules/no-class-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..649769598d3dd32f205d3c6fc2063e4e6ee7195b --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-compare-neg-zero.js b/tools/ui/node_modules/eslint/lib/rules/no-compare-neg-zero.js new file mode 100644 index 0000000000000000000000000000000000000000..a5683164f81ea076c2ec89af3ec2deb064c07236 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-cond-assign.js b/tools/ui/node_modules/eslint/lib/rules/no-cond-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..a686e690a6712431a51b48c30e6077271a3e2791 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-confusing-arrow.js b/tools/ui/node_modules/eslint/lib/rules/no-confusing-arrow.js new file mode 100644 index 0000000000000000000000000000000000000000..1b3e7982888ce256bb06aea9d071e964d40cb34e --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-console.js b/tools/ui/node_modules/eslint/lib/rules/no-console.js new file mode 100644 index 0000000000000000000000000000000000000000..1d734442e3de18f01cf3a6f2830bebb8aace0a86 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-console.js @@ -0,0 +1,221 @@ +/** + * @fileoverview Rule to flag use of console object + * @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: [{}], + + 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 {eslint-scope.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 {eslint-scope.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 {eslint-scope.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/tools/ui/node_modules/eslint/lib/rules/no-const-assign.js b/tools/ui/node_modules/eslint/lib/rules/no-const-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..5e126c80e327e13011db54655e58061da19834d2 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-constant-binary-expression.js b/tools/ui/node_modules/eslint/lib/rules/no-constant-binary-expression.js new file mode 100644 index 0000000000000000000000000000000000000000..e360631147e2fff316646ef6dbdd2512f3de5945 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-constant-condition.js b/tools/ui/node_modules/eslint/lib/rules/no-constant-condition.js new file mode 100644 index 0000000000000000000000000000000000000000..4ecd5a3d2e74fd70234dd9e20d4163d93246d7e2 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-constructor-return.js b/tools/ui/node_modules/eslint/lib/rules/no-constructor-return.js new file mode 100644 index 0000000000000000000000000000000000000000..ed9e03db4348c9283d8d6fbe48f3e70d77131187 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-continue.js b/tools/ui/node_modules/eslint/lib/rules/no-continue.js new file mode 100644 index 0000000000000000000000000000000000000000..6671c619b9d5cf295558b0ce5ded7657d590a81f --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-control-regex.js b/tools/ui/node_modules/eslint/lib/rules/no-control-regex.js new file mode 100644 index 0000000000000000000000000000000000000000..a0221b4b4308fd60d1d7e8d38903497b46511035 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-debugger.js b/tools/ui/node_modules/eslint/lib/rules/no-debugger.js new file mode 100644 index 0000000000000000000000000000000000000000..66bc1be1e620dff02e548ae8f0f58a20cfee0db9 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-delete-var.js b/tools/ui/node_modules/eslint/lib/rules/no-delete-var.js new file mode 100644 index 0000000000000000000000000000000000000000..7dfe002af4cc161c9a431fe706b5d3aff094e1f1 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-div-regex.js b/tools/ui/node_modules/eslint/lib/rules/no-div-regex.js new file mode 100644 index 0000000000000000000000000000000000000000..69845bbda93ef1ea00325dadec38abd8be2e1d39 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-dupe-args.js b/tools/ui/node_modules/eslint/lib/rules/no-dupe-args.js new file mode 100644 index 0000000000000000000000000000000000000000..788b98d8f7cd67fc787a3c207851b97a16f6f9a1 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-dupe-args.js @@ -0,0 +1,92 @@ +/** + * @fileoverview Rule to flag duplicate arguments + * @author Jamund Ferguson + */ + +"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 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 {eslint-scope.DefEntry} 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/tools/ui/node_modules/eslint/lib/rules/no-dupe-class-members.js b/tools/ui/node_modules/eslint/lib/rules/no-dupe-class-members.js new file mode 100644 index 0000000000000000000000000000000000000000..3b9292b78055a121e0f9f9a591217e417e74148a --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-dupe-class-members.js @@ -0,0 +1,117 @@ +/** + * @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", + dialects: ["javascript", "typescript"], + language: "javascript", + + docs: { + description: "Disallow duplicate class members", + 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/tools/ui/node_modules/eslint/lib/rules/no-dupe-else-if.js b/tools/ui/node_modules/eslint/lib/rules/no-dupe-else-if.js new file mode 100644 index 0000000000000000000000000000000000000000..7c4195819a1bda9250b33e1a03f39ccb3aaf78a7 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-dupe-keys.js b/tools/ui/node_modules/eslint/lib/rules/no-dupe-keys.js new file mode 100644 index 0000000000000000000000000000000000000000..a17cb343ddd466b02a02f90eb672083c28133ea4 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-duplicate-case.js b/tools/ui/node_modules/eslint/lib/rules/no-duplicate-case.js new file mode 100644 index 0000000000000000000000000000000000000000..161b1a0bdb7973a1ee1bbd27da2631421f28bedc --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-duplicate-imports.js b/tools/ui/node_modules/eslint/lib/rules/no-duplicate-imports.js new file mode 100644 index 0000000000000000000000000000000000000000..76270332762f852286a5b3bcc2d0a1da37c5869a --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-duplicate-imports.js @@ -0,0 +1,368 @@ +/** + * @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: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "problem", + + defaultOptions: [ + { + includeExports: false, + allowSeparateTypeImports: false, + }, + ], + + docs: { + description: "Disallow duplicate module imports", + 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/tools/ui/node_modules/eslint/lib/rules/no-else-return.js b/tools/ui/node_modules/eslint/lib/rules/no-else-return.js new file mode 100644 index 0000000000000000000000000000000000000000..40e11dbd26eb479f47607589aae5745fe256bd16 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-else-return.js @@ -0,0 +1,450 @@ +/** + * @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"); + +//------------------------------------------------------------------------------ +// 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 {eslint-scope.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 {eslint-scope.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/tools/ui/node_modules/eslint/lib/rules/no-empty-character-class.js b/tools/ui/node_modules/eslint/lib/rules/no-empty-character-class.js new file mode 100644 index 0000000000000000000000000000000000000000..eccee1d1a8cba7bd3003ce76214891d528da91d2 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-empty-function.js b/tools/ui/node_modules/eslint/lib/rules/no-empty-function.js new file mode 100644 index 0000000000000000000000000000000000000000..57bd77890f732f4eedc7e76626726c330a69501d --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-empty-function.js @@ -0,0 +1,236 @@ +/** + * @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: { + dialects: ["javascript", "typescript"], + language: "javascript", + hasSuggestions: true, + type: "suggestion", + + defaultOptions: [{ allow: [] }], + + docs: { + description: "Disallow empty functions", + 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/tools/ui/node_modules/eslint/lib/rules/no-empty-pattern.js b/tools/ui/node_modules/eslint/lib/rules/no-empty-pattern.js new file mode 100644 index 0000000000000000000000000000000000000000..da75ad954cd96a333aae07fd98022f8297104722 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-empty-static-block.js b/tools/ui/node_modules/eslint/lib/rules/no-empty-static-block.js new file mode 100644 index 0000000000000000000000000000000000000000..488b5ed726565903addfaa651403d273dc9f26c7 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-empty.js b/tools/ui/node_modules/eslint/lib/rules/no-empty.js new file mode 100644 index 0000000000000000000000000000000000000000..dd30e4197a836a7a5eeaae283b35fcbd11829ed6 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-eq-null.js b/tools/ui/node_modules/eslint/lib/rules/no-eq-null.js new file mode 100644 index 0000000000000000000000000000000000000000..edda5e6c9d66ab25acd29efe9513d9c652f24d2e --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-eval.js b/tools/ui/node_modules/eslint/lib/rules/no-eval.js new file mode 100644 index 0000000000000000000000000000000000000000..5d75097abce2e0dc817c53f43f38c2cb5285a77b --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-eval.js @@ -0,0 +1,295 @@ +/** + * @fileoverview Rule to flag use of eval() statement + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// 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 {eslint-scope.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 {eslint-scope.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/tools/ui/node_modules/eslint/lib/rules/no-ex-assign.js b/tools/ui/node_modules/eslint/lib/rules/no-ex-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..6215a5e05aad5bd328f296fa4416277376bd65f3 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-extend-native.js b/tools/ui/node_modules/eslint/lib/rules/no-extend-native.js new file mode 100644 index 0000000000000000000000000000000000000000..4d3b8c20ae257ccc166f45a70f52a55de126473e --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-extra-bind.js b/tools/ui/node_modules/eslint/lib/rules/no-extra-bind.js new file mode 100644 index 0000000000000000000000000000000000000000..73164f8d40946275a0f504b0a9347c5bc9a9f332 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-extra-boolean-cast.js b/tools/ui/node_modules/eslint/lib/rules/no-extra-boolean-cast.js new file mode 100644 index 0000000000000000000000000000000000000000..18019a8cd1cec3ed8294f8f4d49a31688c9852ef --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-extra-label.js b/tools/ui/node_modules/eslint/lib/rules/no-extra-label.js new file mode 100644 index 0000000000000000000000000000000000000000..c191eee7ffd93808bfa30b3ad06d486ab7acbe78 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-extra-parens.js b/tools/ui/node_modules/eslint/lib/rules/no-extra-parens.js new file mode 100644 index 0000000000000000000000000000000000000000..5b534b67f74ae0b38f5724fe38beae3d69690663 --- /dev/null +++ b/tools/ui/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.isSpaceBetweenTokens( + 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/tools/ui/node_modules/eslint/lib/rules/no-extra-semi.js b/tools/ui/node_modules/eslint/lib/rules/no-extra-semi.js new file mode 100644 index 0000000000000000000000000000000000000000..a408edaf9555ef04d7a2c908c5ad328d79199c64 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-fallthrough.js b/tools/ui/node_modules/eslint/lib/rules/no-fallthrough.js new file mode 100644 index 0000000000000000000000000000000000000000..4dd210d7b972f71a3aaddd6045e66a0045c395c5 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-fallthrough.js @@ -0,0 +1,260 @@ +/** + * @fileoverview Rule to flag fall-through cases in switch statements. + * @author Matt DuVall + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { directivesPattern } = require("../shared/directives"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const DEFAULT_FALLTHROUGH_COMMENT = /falls?\s?through/iu; + +/** + * 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; +} + +/** + * 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/tools/ui/node_modules/eslint/lib/rules/no-floating-decimal.js b/tools/ui/node_modules/eslint/lib/rules/no-floating-decimal.js new file mode 100644 index 0000000000000000000000000000000000000000..569be727ec8736566acd007e3e0be807d5392853 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-func-assign.js b/tools/ui/node_modules/eslint/lib/rules/no-func-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..a17d4b8e6cccb213dc91f66c21365af6af1c4e6b --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-global-assign.js b/tools/ui/node_modules/eslint/lib/rules/no-global-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..6f238449559214174a0064050a7e4fa0886f0124 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-implicit-coercion.js b/tools/ui/node_modules/eslint/lib/rules/no-implicit-coercion.js new file mode 100644 index 0000000000000000000000000000000000000000..fb6d6a8e95435bf22b5f46fc1bf8bbb0d3810562 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-implicit-globals.js b/tools/ui/node_modules/eslint/lib/rules/no-implicit-globals.js new file mode 100644 index 0000000000000000000000000000000000000000..c291cd86bb6533c91689a5c20fdc97f20c6db2da --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-implied-eval.js b/tools/ui/node_modules/eslint/lib/rules/no-implied-eval.js new file mode 100644 index 0000000000000000000000000000000000000000..7757d5a735d04c3423bf32a715a15597c13038d8 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-implied-eval.js @@ -0,0 +1,170 @@ +/** + * @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", + ]); + 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/tools/ui/node_modules/eslint/lib/rules/no-import-assign.js b/tools/ui/node_modules/eslint/lib/rules/no-import-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..7fe526b66fffe760a4138afa3c6415b563f4e88a --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-inline-comments.js b/tools/ui/node_modules/eslint/lib/rules/no-inline-comments.js new file mode 100644 index 0000000000000000000000000000000000000000..dac9eec1a1ecadb630298bc54e45a9c84a8cb086 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-inner-declarations.js b/tools/ui/node_modules/eslint/lib/rules/no-inner-declarations.js new file mode 100644 index 0000000000000000000000000000000000000000..ec6c4952ad5444d29ab4407b25319cf2b27aad95 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-invalid-regexp.js b/tools/ui/node_modules/eslint/lib/rules/no-invalid-regexp.js new file mode 100644 index 0000000000000000000000000000000000000000..c3937a419f6904589d40bfde8dcaae027ba96358 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-invalid-regexp.js @@ -0,0 +1,243 @@ +/** + * @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", + }, + }, + }, + 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/tools/ui/node_modules/eslint/lib/rules/no-invalid-this.js b/tools/ui/node_modules/eslint/lib/rules/no-invalid-this.js new file mode 100644 index 0000000000000000000000000000000000000000..9e2f97ce90cf00657f1294afd0cb3a85d4c9f1ef --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-invalid-this.js @@ -0,0 +1,178 @@ +/** + * @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: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "suggestion", + + defaultOptions: [{ capIsConstructor: true }], + + docs: { + description: + "Disallow use of `this` in contexts where the value of `this` is `undefined`", + 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/tools/ui/node_modules/eslint/lib/rules/no-irregular-whitespace.js b/tools/ui/node_modules/eslint/lib/rules/no-irregular-whitespace.js new file mode 100644 index 0000000000000000000000000000000000000000..4aaaad1d267f91b92efb43bf135fcf377c7e939d --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-iterator.js b/tools/ui/node_modules/eslint/lib/rules/no-iterator.js new file mode 100644 index 0000000000000000000000000000000000000000..6451e334d2efe664f3bcaeb56fc6317ae871bfd2 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-label-var.js b/tools/ui/node_modules/eslint/lib/rules/no-label-var.js new file mode 100644 index 0000000000000000000000000000000000000000..a878941307300d65678d69df30cbfdc73dd62f5e --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-labels.js b/tools/ui/node_modules/eslint/lib/rules/no-labels.js new file mode 100644 index 0000000000000000000000000000000000000000..45eb8af74393712af900222a930e074474cb8b72 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-lone-blocks.js b/tools/ui/node_modules/eslint/lib/rules/no-lone-blocks.js new file mode 100644 index 0000000000000000000000000000000000000000..94421b8f86ba188be7da20341af272f1f8963868 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-lonely-if.js b/tools/ui/node_modules/eslint/lib/rules/no-lonely-if.js new file mode 100644 index 0000000000000000000000000000000000000000..65af96071242eb4740f14485ed8695231c500388 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-loop-func.js b/tools/ui/node_modules/eslint/lib/rules/no-loop-func.js new file mode 100644 index 0000000000000000000000000000000000000000..df6c8c5ecc7475312a18861d373067e713c686a5 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-loop-func.js @@ -0,0 +1,267 @@ +/** + * @fileoverview Rule to flag creation of function inside a loop + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// 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", + dialects: ["typescript", "javascript"], + language: "javascript", + + docs: { + description: + "Disallow function declarations that contain unsafe references inside loop statements", + 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 {eslint-scope.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 {eslint-scope.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/tools/ui/node_modules/eslint/lib/rules/no-loss-of-precision.js b/tools/ui/node_modules/eslint/lib/rules/no-loss-of-precision.js new file mode 100644 index 0000000000000000000000000000000000000000..8e2005f151c380ba3ae728ac5b60be4ad5f805a1 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-loss-of-precision.js @@ -0,0 +1,249 @@ +/** + * @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", + dialects: ["typescript", "javascript"], + language: "javascript", + + docs: { + description: "Disallow literal numbers that lose precision", + 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/tools/ui/node_modules/eslint/lib/rules/no-magic-numbers.js b/tools/ui/node_modules/eslint/lib/rules/no-magic-numbers.js new file mode 100644 index 0000000000000000000000000000000000000000..bed61a0684fb63b9827211c34a1c2aa3355917db --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-magic-numbers.js @@ -0,0 +1,365 @@ +/** + * @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", + dialects: ["typescript", "javascript"], + language: "javascript", + + docs: { + description: "Disallow magic numbers", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-magic-numbers", + }, + + schema: [ + { + type: "object", + properties: { + detectObjects: { + type: "boolean", + default: false, + }, + enforceConst: { + type: "boolean", + default: false, + }, + ignore: { + type: "array", + items: { + anyOf: [ + { type: "number" }, + { + type: "string", + pattern: "^[+-]?(?:0|[1-9][0-9]*)n$", + }, + ], + }, + uniqueItems: true, + }, + ignoreArrayIndexes: { + type: "boolean", + default: false, + }, + ignoreDefaultValues: { + type: "boolean", + default: false, + }, + ignoreClassFieldInitialValues: { + type: "boolean", + default: false, + }, + ignoreEnums: { + type: "boolean", + default: false, + }, + ignoreNumericLiteralTypes: { + type: "boolean", + default: false, + }, + ignoreReadonlyClassProperties: { + type: "boolean", + default: false, + }, + ignoreTypeIndexes: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + useConst: "Number constants declarations must use 'const'.", + noMagic: "No magic number: {{raw}}.", + }, + }, + + create(context) { + const config = context.options[0] || {}, + detectObjects = !!config.detectObjects, + enforceConst = !!config.enforceConst, + ignore = new Set((config.ignore || []).map(normalizeIgnoreValue)), + ignoreArrayIndexes = !!config.ignoreArrayIndexes, + ignoreDefaultValues = !!config.ignoreDefaultValues, + ignoreClassFieldInitialValues = + !!config.ignoreClassFieldInitialValues, + ignoreEnums = !!config.ignoreEnums, + ignoreNumericLiteralTypes = !!config.ignoreNumericLiteralTypes, + ignoreReadonlyClassProperties = + !!config.ignoreReadonlyClassProperties, + ignoreTypeIndexes = !!config.ignoreTypeIndexes; + + 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/tools/ui/node_modules/eslint/lib/rules/no-misleading-character-class.js b/tools/ui/node_modules/eslint/lib/rules/no-misleading-character-class.js new file mode 100644 index 0000000000000000000000000000000000000000..c7223335fc4105da2b6d539833d23825225c740b --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-mixed-operators.js b/tools/ui/node_modules/eslint/lib/rules/no-mixed-operators.js new file mode 100644 index 0000000000000000000000000000000000000000..73dc127a4aa5ff1fec9cfb176e856276e70d1cce --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-mixed-requires.js b/tools/ui/node_modules/eslint/lib/rules/no-mixed-requires.js new file mode 100644 index 0000000000000000000000000000000000000000..0d8bb55863348766bc73b9dac9d6a87cbead55c1 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-mixed-spaces-and-tabs.js b/tools/ui/node_modules/eslint/lib/rules/no-mixed-spaces-and-tabs.js new file mode 100644 index 0000000000000000000000000000000000000000..5983d7cfd00e24be25e24c537cb821aa9953d623 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-multi-assign.js b/tools/ui/node_modules/eslint/lib/rules/no-multi-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..b4d6ddb4e6a4f76b1470dae89120ca507fc73c78 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-multi-spaces.js b/tools/ui/node_modules/eslint/lib/rules/no-multi-spaces.js new file mode 100644 index 0000000000000000000000000000000000000000..93704760a46139b0d872a2366ba5cd38edba3b0b --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-multi-str.js b/tools/ui/node_modules/eslint/lib/rules/no-multi-str.js new file mode 100644 index 0000000000000000000000000000000000000000..4258dc2e31f09a4cb4745248361606a5309622ac --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-multiple-empty-lines.js b/tools/ui/node_modules/eslint/lib/rules/no-multiple-empty-lines.js new file mode 100644 index 0000000000000000000000000000000000000000..1f6d72647d96c7b40b76e11213cad411b6d491f0 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-native-reassign.js b/tools/ui/node_modules/eslint/lib/rules/no-native-reassign.js new file mode 100644 index 0000000000000000000000000000000000000000..f4eef063276b5ad5bd851fb5482f2dcc31ab0f9c --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-negated-condition.js b/tools/ui/node_modules/eslint/lib/rules/no-negated-condition.js new file mode 100644 index 0000000000000000000000000000000000000000..33c150e8909d3ea32b9876f32c3c59747bde4918 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-negated-in-lhs.js b/tools/ui/node_modules/eslint/lib/rules/no-negated-in-lhs.js new file mode 100644 index 0000000000000000000000000000000000000000..f003cb30625502b275efa48d9656aefdd759a2b5 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-nested-ternary.js b/tools/ui/node_modules/eslint/lib/rules/no-nested-ternary.js new file mode 100644 index 0000000000000000000000000000000000000000..8e5dbb78c849a99f691541990fc48c432cba5897 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-new-func.js b/tools/ui/node_modules/eslint/lib/rules/no-new-func.js new file mode 100644 index 0000000000000000000000000000000000000000..760dc640f8617595cbd2d37ed9a41a37fd81dc4f --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-new-native-nonconstructor.js b/tools/ui/node_modules/eslint/lib/rules/no-new-native-nonconstructor.js new file mode 100644 index 0000000000000000000000000000000000000000..0ae892cd53c07e0870342622dd4b71cdfc11a147 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-new-object.js b/tools/ui/node_modules/eslint/lib/rules/no-new-object.js new file mode 100644 index 0000000000000000000000000000000000000000..f18bf974f5f1d57476fc9ebb24772908ccc8d2a9 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-new-require.js b/tools/ui/node_modules/eslint/lib/rules/no-new-require.js new file mode 100644 index 0000000000000000000000000000000000000000..09d136c83c43f1f6c3a485374f686ddb5803664d --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-new-symbol.js b/tools/ui/node_modules/eslint/lib/rules/no-new-symbol.js new file mode 100644 index 0000000000000000000000000000000000000000..838f502f55aab013059c963c4f61f7bc1332d058 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-new-wrappers.js b/tools/ui/node_modules/eslint/lib/rules/no-new-wrappers.js new file mode 100644 index 0000000000000000000000000000000000000000..84025dbf13b749e9a4155096814c152f7e6ffb98 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-new.js b/tools/ui/node_modules/eslint/lib/rules/no-new.js new file mode 100644 index 0000000000000000000000000000000000000000..8f91835b293b58b4329d4822725aea47f085c420 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-nonoctal-decimal-escape.js b/tools/ui/node_modules/eslint/lib/rules/no-nonoctal-decimal-escape.js new file mode 100644 index 0000000000000000000000000000000000000000..d09b7994b186819d4f0dc48a02e53f4337488f23 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-obj-calls.js b/tools/ui/node_modules/eslint/lib/rules/no-obj-calls.js new file mode 100644 index 0000000000000000000000000000000000000000..df76b482e329c291d652bae22dd4b9e66c67fcc5 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-obj-calls.js @@ -0,0 +1,99 @@ +/** + * @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"]; + +/** + * 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/tools/ui/node_modules/eslint/lib/rules/no-object-constructor.js b/tools/ui/node_modules/eslint/lib/rules/no-object-constructor.js new file mode 100644 index 0000000000000000000000000000000000000000..fffa61227e0848f91544062fba8b99f55028e6f6 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-octal-escape.js b/tools/ui/node_modules/eslint/lib/rules/no-octal-escape.js new file mode 100644 index 0000000000000000000000000000000000000000..975b308547ec13b7691ce9f8a8bdcc5fb9d1b71a --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-octal.js b/tools/ui/node_modules/eslint/lib/rules/no-octal.js new file mode 100644 index 0000000000000000000000000000000000000000..e5ea9bda0b01f397cc91b0fd6f3e26959f0332ef --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-param-reassign.js b/tools/ui/node_modules/eslint/lib/rules/no-param-reassign.js new file mode 100644 index 0000000000000000000000000000000000000000..ec22030a718753059bb8f9f6bf96c3070dc7b9d8 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-path-concat.js b/tools/ui/node_modules/eslint/lib/rules/no-path-concat.js new file mode 100644 index 0000000000000000000000000000000000000000..230a39438557ddc891324577197bb3c54d41a069 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-plusplus.js b/tools/ui/node_modules/eslint/lib/rules/no-plusplus.js new file mode 100644 index 0000000000000000000000000000000000000000..1f3a9f0f87f842b03ae2cbdb01f8ea19f5e6f40b --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-process-env.js b/tools/ui/node_modules/eslint/lib/rules/no-process-env.js new file mode 100644 index 0000000000000000000000000000000000000000..c9dc353ff7fc7f79975d376b446c8595c2afbbe9 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-process-exit.js b/tools/ui/node_modules/eslint/lib/rules/no-process-exit.js new file mode 100644 index 0000000000000000000000000000000000000000..79f8153a636880e86be5729bd831e7e91b234196 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-promise-executor-return.js b/tools/ui/node_modules/eslint/lib/rules/no-promise-executor-return.js new file mode 100644 index 0000000000000000000000000000000000000000..647f3ac08469392f526ca5ff9f7cb215fff141dc --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-proto.js b/tools/ui/node_modules/eslint/lib/rules/no-proto.js new file mode 100644 index 0000000000000000000000000000000000000000..d68509e115ed90ba1757c00723a6b64ad1c2d35a --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-prototype-builtins.js b/tools/ui/node_modules/eslint/lib/rules/no-prototype-builtins.js new file mode 100644 index 0000000000000000000000000000000000000000..c75fdacf8e0e92aed192bd863258b40fc8aa49c9 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-redeclare.js b/tools/ui/node_modules/eslint/lib/rules/no-redeclare.js new file mode 100644 index 0000000000000000000000000000000000000000..4f8c06c97096f7ea3eca4fd29f8e40fdd6c29e16 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-regex-spaces.js b/tools/ui/node_modules/eslint/lib/rules/no-regex-spaces.js new file mode 100644 index 0000000000000000000000000000000000000000..71924097573141e2b08bf91021d9aac7ecca75b7 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-restricted-exports.js b/tools/ui/node_modules/eslint/lib/rules/no-restricted-exports.js new file mode 100644 index 0000000000000000000000000000000000000000..fd5ff4b5abe2611a4e335ea14a77efeb3c4ae835 --- /dev/null +++ b/tools/ui/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, + }, + ], + }, + ], + + messages: { + restrictedNamed: + "'{{name}}' is restricted from being used as an exported name.", + restrictedDefault: "Exporting 'default' is restricted.", + }, + }, + + create(context) { + const restrictedNames = new Set( + context.options[0] && context.options[0].restrictedNamedExports, + ); + const restrictedNamePattern = + context.options[0] && + context.options[0].restrictedNamedExportsPattern; + const restrictDefaultExports = + context.options[0] && context.options[0].restrictDefaultExports; + 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/tools/ui/node_modules/eslint/lib/rules/no-restricted-globals.js b/tools/ui/node_modules/eslint/lib/rules/no-restricted-globals.js new file mode 100644 index 0000000000000000000000000000000000000000..a883988c4f3ab338fb9dc5237f193a2b67c94232 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-restricted-globals.js @@ -0,0 +1,266 @@ +/** + * @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: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "suggestion", + + docs: { + description: "Disallow specified global variables", + 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/tools/ui/node_modules/eslint/lib/rules/no-restricted-imports.js b/tools/ui/node_modules/eslint/lib/rules/no-restricted-imports.js new file mode 100644 index 0000000000000000000000000000000000000000..a52cafe393f96faab10dd1d3fd516b24690eceea --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-restricted-imports.js @@ -0,0 +1,850 @@ +/** + * @fileoverview Restrict usage of specified node imports. + * @author Guy Ellis + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// 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", + dialects: ["typescript", "javascript"], + language: "javascript", + + docs: { + description: "Disallow specified modules when loaded by `import`", + 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}}' is 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}}' is 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}}' is 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}}' is 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}}' import(s) is/are 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}}' import(s) is/are allowed. {{customMessage}}", + + everythingWithAllowImportNames: + "* import is invalid because only '{{allowedImportNames}}' from '{{importSource}}' is/are 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}}' is/are 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: restrictedImportNames, + customMessage, + }, + }); + } else if (allowedImportNames) { + context.report({ + node, + messageId: customMessage + ? "everythingWithAllowImportNamesAndCustomMessage" + : "everythingWithAllowImportNames", + loc: specifier.loc, + data: { + importSource, + 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, + }, + }); + }); + } + }); + }, + ); + } + + /** + * 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: restrictedImportNames, + customMessage, + }, + }); + } else if (allowedImportNames) { + context.report({ + node, + messageId: customMessage + ? "everythingWithAllowImportNamesAndCustomMessage" + : "everythingWithAllowImportNames", + loc: specifier.loc, + data: { + importSource, + 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, + }, + }); + }); + } 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/tools/ui/node_modules/eslint/lib/rules/no-restricted-modules.js b/tools/ui/node_modules/eslint/lib/rules/no-restricted-modules.js new file mode 100644 index 0000000000000000000000000000000000000000..c09cb7d9e6bb6a2a36a0c8c2e501924459830f0a --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-restricted-properties.js b/tools/ui/node_modules/eslint/lib/rules/no-restricted-properties.js new file mode 100644 index 0000000000000000000000000000000000000000..95dbd67d87feb00ed29731dfb7662bfac3f95e6d --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-restricted-properties.js @@ -0,0 +1,233 @@ +/** + * @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, + }, + + 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/tools/ui/node_modules/eslint/lib/rules/no-restricted-syntax.js b/tools/ui/node_modules/eslint/lib/rules/no-restricted-syntax.js new file mode 100644 index 0000000000000000000000000000000000000000..447d29cf1bc0452beae50f215155ba88f83f7a11 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-restricted-syntax.js @@ -0,0 +1,74 @@ +/** + * @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, + }, + + 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/tools/ui/node_modules/eslint/lib/rules/no-return-assign.js b/tools/ui/node_modules/eslint/lib/rules/no-return-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..92999ddf2b61bdcae561ed450c5d6e3387614ddc --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-return-await.js b/tools/ui/node_modules/eslint/lib/rules/no-return-await.js new file mode 100644 index 0000000000000000000000000000000000000000..21627eddf7f7d796d072392d7fdd7d3a48542702 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-script-url.js b/tools/ui/node_modules/eslint/lib/rules/no-script-url.js new file mode 100644 index 0000000000000000000000000000000000000000..fe550b6dec00933df2a2e4b5d92b89f51bc35021 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-self-assign.js b/tools/ui/node_modules/eslint/lib/rules/no-self-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..c1831bb03a5dd7c1eea4d14d1244c129915561d9 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-self-compare.js b/tools/ui/node_modules/eslint/lib/rules/no-self-compare.js new file mode 100644 index 0000000000000000000000000000000000000000..ee05d3a6028b9b5c84d20cbc4f7666b0a3b71bf4 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-sequences.js b/tools/ui/node_modules/eslint/lib/rules/no-sequences.js new file mode 100644 index 0000000000000000000000000000000000000000..96a8ba4e33a6a2178448247e16907f5cbc726d8d --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-setter-return.js b/tools/ui/node_modules/eslint/lib/rules/no-setter-return.js new file mode 100644 index 0000000000000000000000000000000000000000..63e0de53bfa46c767564303a3bd25aeb4f678c65 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-shadow-restricted-names.js b/tools/ui/node_modules/eslint/lib/rules/no-shadow-restricted-names.js new file mode 100644 index 0000000000000000000000000000000000000000..949eed8e6ed62d2a1cca271a02d478c05bfdfb52 --- /dev/null +++ b/tools/ui/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: false, + }, + ], + + 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/tools/ui/node_modules/eslint/lib/rules/no-shadow.js b/tools/ui/node_modules/eslint/lib/rules/no-shadow.js new file mode 100644 index 0000000000000000000000000000000000000000..bbd0f9e401b7f4c858ddebc2d989b755be2ef9e7 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-shadow.js @@ -0,0 +1,624 @@ +/** + * @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"); + +//------------------------------------------------------------------------------ +// 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", + dialects: ["typescript", "javascript"], + language: "javascript", + + 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", + 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] + ); + } + + /** + * Checks if a variable is inside the initializer of scopeVar. + * + * To avoid reporting at declarations such as `var a = function a() {};`. + * But it should report `var a = function(a) {};` or `var a = function() { function a() {} };`. + * @param {Object} variable The variable to check. + * @param {Object} scopeVar The scope variable to look for. + * @returns {boolean} Whether or not the variable is inside initializer of scopeVar. + */ + function isOnInitializer(variable, scopeVar) { + const outerScope = scopeVar.scope; + const outerDef = scopeVar.defs[0]; + const outer = outerDef && outerDef.parent && outerDef.parent.range; + const innerScope = variable.scope; + const innerDef = variable.defs[0]; + const inner = innerDef && innerDef.name.range; + + return ( + outer && + inner && + outer[0] < inner[0] && + inner[1] < outer[1] && + ((innerDef.type === "FunctionName" && + innerDef.node.type === "FunctionExpression") || + innerDef.node.type === "ClassExpression") && + outerScope === innerScope.upper + ); + } + + /** + * 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 {eslint-scope.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 Fixme + * @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)) && + !isOnInitializer(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/tools/ui/node_modules/eslint/lib/rules/no-spaced-func.js b/tools/ui/node_modules/eslint/lib/rules/no-spaced-func.js new file mode 100644 index 0000000000000000000000000000000000000000..037015b7fe0f481308ca22ee749e3bf8bd03e384 --- /dev/null +++ b/tools/ui/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.isSpaceBetweenTokens(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/tools/ui/node_modules/eslint/lib/rules/no-sparse-arrays.js b/tools/ui/node_modules/eslint/lib/rules/no-sparse-arrays.js new file mode 100644 index 0000000000000000000000000000000000000000..f805ecef3e09c21734a65277fcc4e1cff31d19f5 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-sync.js b/tools/ui/node_modules/eslint/lib/rules/no-sync.js new file mode 100644 index 0000000000000000000000000000000000000000..50b5860ee1ed90057e10b32e75b19a30d8c472c7 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-tabs.js b/tools/ui/node_modules/eslint/lib/rules/no-tabs.js new file mode 100644 index 0000000000000000000000000000000000000000..f35f4da0d09b3249b59dc9665e2948f01290647d --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-template-curly-in-string.js b/tools/ui/node_modules/eslint/lib/rules/no-template-curly-in-string.js new file mode 100644 index 0000000000000000000000000000000000000000..901e1aeadfd267b644722365b3462451f0ebea98 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-ternary.js b/tools/ui/node_modules/eslint/lib/rules/no-ternary.js new file mode 100644 index 0000000000000000000000000000000000000000..f58136d5e650dba11091cc45d0c3692fb556ab6d --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-this-before-super.js b/tools/ui/node_modules/eslint/lib/rules/no-this-before-super.js new file mode 100644 index 0000000000000000000000000000000000000000..16d049c48d7ffcf7489d3581639d04382ea753a0 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-this-before-super.js @@ -0,0 +1,365 @@ +/** + * @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/tools/ui/node_modules/eslint/lib/rules/no-throw-literal.js b/tools/ui/node_modules/eslint/lib/rules/no-throw-literal.js new file mode 100644 index 0000000000000000000000000000000000000000..877224be1a723f7cc4e8011a5e9a59bf13fa4047 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-trailing-spaces.js b/tools/ui/node_modules/eslint/lib/rules/no-trailing-spaces.js new file mode 100644 index 0000000000000000000000000000000000000000..14c66db4ae377cf6bf7c522576dfa30676291efa --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-unassigned-vars.js b/tools/ui/node_modules/eslint/lib/rules/no-unassigned-vars.js new file mode 100644 index 0000000000000000000000000000000000000000..3fcd83958d7860cffdde47ae4630c6d138fa7f58 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-unassigned-vars.js @@ -0,0 +1,80 @@ +/** + * @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", + dialects: ["typescript", "javascript"], + language: "javascript", + + docs: { + description: + "Disallow `let` or `var` variables that are read but never assigned", + recommended: false, + 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/tools/ui/node_modules/eslint/lib/rules/no-undef-init.js b/tools/ui/node_modules/eslint/lib/rules/no-undef-init.js new file mode 100644 index 0000000000000000000000000000000000000000..77a120043e2c7c9bae5d219acc5885aa11e27b14 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-undef.js b/tools/ui/node_modules/eslint/lib/rules/no-undef.js new file mode 100644 index 0000000000000000000000000000000000000000..fbda877330743a65d7c55438dbbafd247d21f155 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-undefined.js b/tools/ui/node_modules/eslint/lib/rules/no-undefined.js new file mode 100644 index 0000000000000000000000000000000000000000..044efeab8e1f16a614a98a2c8fb0560cb9eba08c --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-undefined.js @@ -0,0 +1,85 @@ +/** + * @fileoverview Rule to flag references to the undefined variable. + * @author Michael Ficarra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// 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 {eslint-scope.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/tools/ui/node_modules/eslint/lib/rules/no-underscore-dangle.js b/tools/ui/node_modules/eslint/lib/rules/no-underscore-dangle.js new file mode 100644 index 0000000000000000000000000000000000000000..24b7237098832943ec1e6e1dd7e98b301363e3f1 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-unexpected-multiline.js b/tools/ui/node_modules/eslint/lib/rules/no-unexpected-multiline.js new file mode 100644 index 0000000000000000000000000000000000000000..0e91cdca8e7b807683a0292432e2db5fe7e6b50f --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js b/tools/ui/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js new file mode 100644 index 0000000000000000000000000000000000000000..1796489229fa872bc75c57ef6857b57546668b23 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js @@ -0,0 +1,360 @@ +/** + * @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"); + +//------------------------------------------------------------------------------ +// 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 {eslint-scope.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 {eslint-scope.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 {eslint-scope.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 {eslint-scope.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 {eslint-scope.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; +} + +/** + * Updates the "modified" flags of given loop conditions with given modifiers. + * @param {LoopConditionInfo[]} conditions The loop conditions to be updated. + * @param {eslint-scope.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]; + let funcNode, funcVar; + + /* + * Besides checking for the condition being in the loop, we want to + * check the function that this modifier is belonging to is called + * in the loop. + * FIXME: This should probably be extracted to a function. + */ + const inLoop = + condition.isInLoop(modifier) || + Boolean( + (funcNode = getEncloseFunctionDeclaration(modifier)) && + (funcVar = astUtils.getVariableByName( + modifier.from.upper, + funcNode.id.name, + )) && + funcVar.references.some(condition.isInLoop), + ); + + condition.modified = inLoop; + } + } +} + +//------------------------------------------------------------------------------ +// 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 {eslint-scope.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 {eslint-scope.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/tools/ui/node_modules/eslint/lib/rules/no-unneeded-ternary.js b/tools/ui/node_modules/eslint/lib/rules/no-unneeded-ternary.js new file mode 100644 index 0000000000000000000000000000000000000000..24e65b67e1db7cf080eabcc9661aad37b0a69d81 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-unreachable-loop.js b/tools/ui/node_modules/eslint/lib/rules/no-unreachable-loop.js new file mode 100644 index 0000000000000000000000000000000000000000..63e3c977df87bc8aeec1b8b3821e1252dd483ec1 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-unreachable-loop.js @@ -0,0 +1,190 @@ +/** + * @fileoverview Rule to disallow loops with a body that allows only one iteration + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const allLoopTypes = [ + "WhileStatement", + "DoWhileStatement", + "ForStatement", + "ForInStatement", + "ForOfStatement", +]; + +/** + * 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; +} + +/** + * 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/tools/ui/node_modules/eslint/lib/rules/no-unreachable.js b/tools/ui/node_modules/eslint/lib/rules/no-unreachable.js new file mode 100644 index 0000000000000000000000000000000000000000..7be94bb3f5579a5d7ab3468cc03958193ca18a39 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-unreachable.js @@ -0,0 +1,300 @@ +/** + * @fileoverview Checks for unreachable code due to return, throws, break, and continue. + * @author Joel Feenstra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// 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); +} + +/** + * Checks all segments in a set and returns true if all are unreachable. + * @param {Set} segments The segments to check. + * @returns {boolean} True if all segments are unreachable; false otherwise. + */ +function areAllSegmentsUnreachable(segments) { + for (const segment of segments) { + if (segment.reachable) { + return false; + } + } + + return true; +} + +/** + * 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" || + areAllSegmentsUnreachable(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/tools/ui/node_modules/eslint/lib/rules/no-unsafe-finally.js b/tools/ui/node_modules/eslint/lib/rules/no-unsafe-finally.js new file mode 100644 index 0000000000000000000000000000000000000000..4c6393e60ef352a11dcb68c1af110c30fe808da4 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-unsafe-negation.js b/tools/ui/node_modules/eslint/lib/rules/no-unsafe-negation.js new file mode 100644 index 0000000000000000000000000000000000000000..17e0271068e29ca9350040e06ca6c55063786fc7 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-unsafe-optional-chaining.js b/tools/ui/node_modules/eslint/lib/rules/no-unsafe-optional-chaining.js new file mode 100644 index 0000000000000000000000000000000000000000..95875b7ebf75ec38376c4cc4c0f164bb737cd755 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-unused-expressions.js b/tools/ui/node_modules/eslint/lib/rules/no-unused-expressions.js new file mode 100644 index 0000000000000000000000000000000000000000..3c530e6effb28a100a31704375e0b9ede7a442e2 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-unused-expressions.js @@ -0,0 +1,227 @@ +/** + * @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: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "suggestion", + + docs: { + description: "Disallow unused expressions", + 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/tools/ui/node_modules/eslint/lib/rules/no-unused-labels.js b/tools/ui/node_modules/eslint/lib/rules/no-unused-labels.js new file mode 100644 index 0000000000000000000000000000000000000000..d7fe3e42749577c2b5f8167ba447ad89bb18de09 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-unused-private-class-members.js b/tools/ui/node_modules/eslint/lib/rules/no-unused-private-class-members.js new file mode 100644 index 0000000000000000000000000000000000000000..51029cc498cc1afb0ae5adc25e8e747037e5c83e --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-unused-private-class-members.js @@ -0,0 +1,219 @@ +/** + * @fileoverview Rule to flag declared but unused private class members + * @author Tim van der Lippe + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + 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.", + }, + }, + + create(context) { + const trackedClasses = []; + + /** + * 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, + 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; + } + + /* + * 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, isUsed }, + ] of unusedPrivateMembers.entries()) { + if (isUsed) { + continue; + } + context.report({ + node: declaredNode, + loc: declaredNode.key.loc, + messageId: "unusedPrivateClassMember", + data: { + classMemberName: `#${classMemberName}`, + }, + }); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/no-unused-vars.js b/tools/ui/node_modules/eslint/lib/rules/no-unused-vars.js new file mode 100644 index 0000000000000000000000000000000000000000..da5361fa774504858112f1a7a94f2854fa506034 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-unused-vars.js @@ -0,0 +1,1739 @@ +/** + * @fileoverview Rule to flag declared but unused variables + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// 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. + */ + +//------------------------------------------------------------------------------ +// 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, + }, + ], + }, + ], + + 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; + + const config = { + vars: "all", + args: "after-used", + ignoreRestSiblings: false, + caughtErrors: "all", + ignoreClassWithStaticInitBlock: false, + ignoreUsingDeclarations: false, + reportUsedIgnorePattern: false, + }; + + const firstOption = context.options[0]; + + if (firstOption) { + if (typeof firstOption === "string") { + config.vars = firstOption; + } else { + config.vars = firstOption.vars || config.vars; + config.args = firstOption.args || config.args; + config.ignoreRestSiblings = + firstOption.ignoreRestSiblings || config.ignoreRestSiblings; + config.caughtErrors = + firstOption.caughtErrors || config.caughtErrors; + config.ignoreClassWithStaticInitBlock = + firstOption.ignoreClassWithStaticInitBlock || + config.ignoreClassWithStaticInitBlock; + config.ignoreUsingDeclarations = + firstOption.ignoreUsingDeclarations || + config.ignoreUsingDeclarations; + config.reportUsedIgnorePattern = + firstOption.reportUsedIgnorePattern || + config.reportUsedIgnorePattern; + + 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 {eslint-scope.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 {eslint-scope.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 {eslint-scope.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/tools/ui/node_modules/eslint/lib/rules/no-use-before-define.js b/tools/ui/node_modules/eslint/lib/rules/no-use-before-define.js new file mode 100644 index 0000000000000000000000000000000000000000..870a36798aa6723cd01c2103992f49dbbbffa03e --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-use-before-define.js @@ -0,0 +1,446 @@ +/** + * @fileoverview Rule to flag use of variables before they are defined + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// 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 {eslint-scope.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 {eslint-scope.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: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "problem", + + docs: { + description: + "Disallow the use of variables before they are defined", + 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 {eslint-scope.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 {eslint-scope.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/tools/ui/node_modules/eslint/lib/rules/no-useless-assignment.js b/tools/ui/node_modules/eslint/lib/rules/no-useless-assignment.js new file mode 100644 index 0000000000000000000000000000000000000000..786744634ce00c0f5ff15cacc7443375b27fbc49 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-useless-assignment.js @@ -0,0 +1,654 @@ +/** + * @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: false, + url: "https://eslint.org/docs/latest/rules/no-useless-assignment", + }, + + schema: [], + + messages: { + unnecessaryAssignment: + "This assigned value 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 => ref.identifier.type !== "Identifier", + ) + ) { + /** + * 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", + }); + } + + // 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(node) { + for (const segment of scopeStack.currentSegments) { + const segmentInfo = scopeStack.segments[segment.id]; + + if (!segmentInfo.first) { + segmentInfo.first = node; + } + segmentInfo.last = node; + } + }, + ":matches(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/tools/ui/node_modules/eslint/lib/rules/no-useless-backreference.js b/tools/ui/node_modules/eslint/lib/rules/no-useless-backreference.js new file mode 100644 index 0000000000000000000000000000000000000000..73cce577a2fc779ea855e4897b06462dac22cb97 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-useless-call.js b/tools/ui/node_modules/eslint/lib/rules/no-useless-call.js new file mode 100644 index 0000000000000000000000000000000000000000..2a04ad2909229d6bb11735bd5bb603cb488777ef --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-useless-catch.js b/tools/ui/node_modules/eslint/lib/rules/no-useless-catch.js new file mode 100644 index 0000000000000000000000000000000000000000..e3df3093cbedceefbed7ebe858c18fa9dec5d57f --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-useless-computed-key.js b/tools/ui/node_modules/eslint/lib/rules/no-useless-computed-key.js new file mode 100644 index 0000000000000000000000000000000000000000..3c61c767216b63d518a0522006aa8802f2efe8d3 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-useless-concat.js b/tools/ui/node_modules/eslint/lib/rules/no-useless-concat.js new file mode 100644 index 0000000000000000000000000000000000000000..d1d1274853ce5bf970ff9d1c7b51e4498287aa4a --- /dev/null +++ b/tools/ui/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"; +} + +/** + * Get's 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; +} + +/** + * Get's 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/tools/ui/node_modules/eslint/lib/rules/no-useless-constructor.js b/tools/ui/node_modules/eslint/lib/rules/no-useless-constructor.js new file mode 100644 index 0000000000000000000000000000000000000000..123dce31f3ba10fa34cbe79d7c5fa0aaccce70bc --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-useless-constructor.js @@ -0,0 +1,252 @@ +/** + * @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: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "suggestion", + + docs: { + description: "Disallow unnecessary constructors", + 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) { + /** + * 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; + + if ( + superClass + ? isRedundantSuperCall(body, ctorParams) + : body.length === 0 + ) { + context.report({ + node, + messageId: "noUselessConstructor", + suggest: [ + { + messageId: "removeConstructor", + *fix(fixer) { + const nextToken = + context.sourceCode.getTokenAfter(node); + const addSemiColon = + nextToken.type === "Punctuator" && + nextToken.value === "[" && + astUtils.needsPrecedingSemicolon( + context.sourceCode, + node, + ); + + yield fixer.replaceText( + node, + addSemiColon ? ";" : "", + ); + }, + }, + ], + }); + } + } + + return { + MethodDefinition: checkForConstructor, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/no-useless-escape.js b/tools/ui/node_modules/eslint/lib/rules/no-useless-escape.js new file mode 100644 index 0000000000000000000000000000000000000000..480b5159773ac9ddd1d248f29243b1de8ff6eb80 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-useless-rename.js b/tools/ui/node_modules/eslint/lib/rules/no-useless-rename.js new file mode 100644 index 0000000000000000000000000000000000000000..13c76861c9649b7a00b55723acfb2241d8edceef --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-useless-return.js b/tools/ui/node_modules/eslint/lib/rules/no-useless-return.js new file mode 100644 index 0000000000000000000000000000000000000000..e911885a709aa16925fd706e70847c17a9282fe8 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-useless-return.js @@ -0,0 +1,401 @@ +/** + * @fileoverview Disallow redundant return statements + * @author Teddy Katz + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"), + FixTracker = require("./utils/fix-tracker"); + +//------------------------------------------------------------------------------ +// 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; +} + +/** + * 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; +} + +//------------------------------------------------------------------------------ +// 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/tools/ui/node_modules/eslint/lib/rules/no-var.js b/tools/ui/node_modules/eslint/lib/rules/no-var.js new file mode 100644 index 0000000000000000000000000000000000000000..39562d82e3b7b3fa4115c23289a10ceb3854256d --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-var.js @@ -0,0 +1,367 @@ +/** + * @fileoverview Rule to check for the usage of var. + * @author Jamund Ferguson + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Check whether a given variable is a global variable or not. + * @param {eslint-scope.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 {eslint-scope.Scope} scope The scope to traverse. + * @returns {eslint-scope.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 {eslint-scope.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 {eslint-scope.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 {eslint-scope.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 {eslint-scope.Variable} variable The variable to check. + * @returns {boolean} `true` if the variable has a disallowed name. + */ +function hasNameDisallowedForLetDeclarations(variable) { + return variable.name === "let"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + dialects: ["typescript", "javascript"], + language: "javascript", + + docs: { + description: "Require `let` or `const` instead of `var`", + 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 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); + + if ( + node.parent.type === "SwitchCase" || + node.declarations.some(hasSelfReferenceInTDZ) || + variables.some(isGlobal) || + variables.some(isRedeclared) || + variables.some(isUsedFromOutsideOf(scopeNode)) || + variables.some(hasNameDisallowedForLetDeclarations) + ) { + 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 + ) && + !astUtils.STATEMENT_LIST_PARENTS.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/tools/ui/node_modules/eslint/lib/rules/no-void.js b/tools/ui/node_modules/eslint/lib/rules/no-void.js new file mode 100644 index 0000000000000000000000000000000000000000..7e99fd3c14887e4e603b43d39ba8fafeebcbcf92 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-warning-comments.js b/tools/ui/node_modules/eslint/lib/rules/no-warning-comments.js new file mode 100644 index 0000000000000000000000000000000000000000..8f1a7c36b488c4fddce510676ad7f24c334c8584 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/no-whitespace-before-property.js b/tools/ui/node_modules/eslint/lib/rules/no-whitespace-before-property.js new file mode 100644 index 0000000000000000000000000000000000000000..834e6f1620581778f704a65bc9707f69940196e8 --- /dev/null +++ b/tools/ui/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.isSpaceBetweenTokens(leftToken, rightToken)) { + reportError(node, leftToken, rightToken); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/no-with.js b/tools/ui/node_modules/eslint/lib/rules/no-with.js new file mode 100644 index 0000000000000000000000000000000000000000..d8be31f7e09ae3b901c2dd4627fefb1877ea66a3 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/no-with.js @@ -0,0 +1,37 @@ +/** + * @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) { + return { + WithStatement(node) { + context.report({ node, messageId: "unexpectedWith" }); + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/nonblock-statement-body-position.js b/tools/ui/node_modules/eslint/lib/rules/nonblock-statement-body-position.js new file mode 100644 index 0000000000000000000000000000000000000000..dbfd1063fbabcd92411eef19722c4858c4d633f3 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/object-curly-newline.js b/tools/ui/node_modules/eslint/lib/rules/object-curly-newline.js new file mode 100644 index 0000000000000000000000000000000000000000..e0b860b3d3936e9003c03e3962628c205ddf1ea0 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/object-curly-spacing.js b/tools/ui/node_modules/eslint/lib/rules/object-curly-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..fbd177369ea3b8c026181a8b3c1af3119fa5dd7b --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/object-curly-spacing.js @@ -0,0 +1,375 @@ +/** + * @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.isSpaceBetweenTokens( + 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.isSpaceBetweenTokens( + 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/tools/ui/node_modules/eslint/lib/rules/object-property-newline.js b/tools/ui/node_modules/eslint/lib/rules/object-property-newline.js new file mode 100644 index 0000000000000000000000000000000000000000..6921e048a6ee316947dee4b6f755d99766c90f09 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/object-shorthand.js b/tools/ui/node_modules/eslint/lib/rules/object-shorthand.js new file mode 100644 index 0000000000000000000000000000000000000000..916d5374d4a88b34a4a9e4d87bb895ebdf575587 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/object-shorthand.js @@ -0,0 +1,652 @@ +/** + * @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, + }, + ], + }, + + 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] || OPTIONS.always; + 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/tools/ui/node_modules/eslint/lib/rules/one-var-declaration-per-line.js b/tools/ui/node_modules/eslint/lib/rules/one-var-declaration-per-line.js new file mode 100644 index 0000000000000000000000000000000000000000..3671e27213e491f89518a4a42baab307b22f0137 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/one-var.js b/tools/ui/node_modules/eslint/lib/rules/one-var.js new file mode 100644 index 0000000000000000000000000000000000000000..6a4cc074d667a4c3968317019594996b2a8e5238 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/one-var.js @@ -0,0 +1,717 @@ +/** + * @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, + }, + ], + }, + ], + + 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] || MODE_ALWAYS; + + 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/tools/ui/node_modules/eslint/lib/rules/operator-assignment.js b/tools/ui/node_modules/eslint/lib/rules/operator-assignment.js new file mode 100644 index 0000000000000000000000000000000000000000..50ae9996da1e32ab7fc9fabdcb7ad30276b3c9eb --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/operator-linebreak.js b/tools/ui/node_modules/eslint/lib/rules/operator-linebreak.js new file mode 100644 index 0000000000000000000000000000000000000000..f0b7d46fa2f1ddf96c5c047b9b1a6d0f2531cbb7 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/padded-blocks.js b/tools/ui/node_modules/eslint/lib/rules/padded-blocks.js new file mode 100644 index 0000000000000000000000000000000000000000..2df44f890f17db73085ed5b21f3a5718b4f8a1e5 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/padding-line-between-statements.js b/tools/ui/node_modules/eslint/lib/rules/padding-line-between-statements.js new file mode 100644 index 0000000000000000000000000000000000000000..153bf820a4527695786e7baa352a52b0ec42818d --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/prefer-arrow-callback.js b/tools/ui/node_modules/eslint/lib/rules/prefer-arrow-callback.js new file mode 100644 index 0000000000000000000000000000000000000000..0f05b52ad06a17766acaa469dc196f27af3815d3 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/prefer-arrow-callback.js @@ -0,0 +1,437 @@ +/** + * @fileoverview A rule to suggest using arrow functions as callbacks. + * @author Toru Nagashima + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given variable is a function name. + * @param {eslint-scope.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 {eslint-scope.Scope} scope A scope to get. + * @returns {eslint-scope.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", + dialects: ["javascript", "typescript"], + language: "javascript", + + defaultOptions: [ + { allowNamedFunctions: false, allowUnboundThis: true }, + ], + + docs: { + description: "Require using arrow functions for callbacks", + 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; + } + + // 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 functionToken = sourceCode.getFirstToken( + node, + node.async ? 1 : 0, + ); + const leftParenToken = sourceCode.getTokenAfter( + functionToken, + astUtils.isOpeningParenToken, + ); + 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/tools/ui/node_modules/eslint/lib/rules/prefer-const.js b/tools/ui/node_modules/eslint/lib/rules/prefer-const.js new file mode 100644 index 0000000000000000000000000000000000000000..8d5ae29ad48e709c71feef1e29313208a31bdc76 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/prefer-const.js @@ -0,0 +1,546 @@ +/** + * @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"); + +//------------------------------------------------------------------------------ +// 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 {eslint-scope.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 {eslint-scope.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 {eslint-scope.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 {eslint-scope.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 {(eslint-scope.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/tools/ui/node_modules/eslint/lib/rules/prefer-destructuring.js b/tools/ui/node_modules/eslint/lib/rules/prefer-destructuring.js new file mode 100644 index 0000000000000000000000000000000000000000..09d0e5be3ad59de6f9c17ff3b537aa964ce0d9bb --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/prefer-exponentiation-operator.js b/tools/ui/node_modules/eslint/lib/rules/prefer-exponentiation-operator.js new file mode 100644 index 0000000000000000000000000000000000000000..beb78438b59888ff954d825998f83c341ea52f42 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/prefer-named-capture-group.js b/tools/ui/node_modules/eslint/lib/rules/prefer-named-capture-group.js new file mode 100644 index 0000000000000000000000000000000000000000..d5c1f46028e277310e67eddb929a340651b0f8da --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/prefer-numeric-literals.js b/tools/ui/node_modules/eslint/lib/rules/prefer-numeric-literals.js new file mode 100644 index 0000000000000000000000000000000000000000..86dec88797807b95f580ca079b28934c0a3f85db --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/prefer-object-has-own.js b/tools/ui/node_modules/eslint/lib/rules/prefer-object-has-own.js new file mode 100644 index 0000000000000000000000000000000000000000..3e0bb5209c588c53566df6c0fe3ca9e012c448f6 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/prefer-object-spread.js b/tools/ui/node_modules/eslint/lib/rules/prefer-object-spread.js new file mode 100644 index 0000000000000000000000000000000000000000..6827e2c25dc02b261d75188563d3cff68e9e3128 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/prefer-promise-reject-errors.js b/tools/ui/node_modules/eslint/lib/rules/prefer-promise-reject-errors.js new file mode 100644 index 0000000000000000000000000000000000000000..7043f296d386ed410d5018d83c3188c9dd11640f --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/prefer-reflect.js b/tools/ui/node_modules/eslint/lib/rules/prefer-reflect.js new file mode 100644 index 0000000000000000000000000000000000000000..4eae98afb5e422d20f2fddec3a180a7c26dbff6c --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/prefer-regex-literals.js b/tools/ui/node_modules/eslint/lib/rules/prefer-regex-literals.js new file mode 100644 index 0000000000000000000000000000000000000000..f1414dfa91a35ef658574606c5850bb18bea8708 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/preserve-caught-error.js b/tools/ui/node_modules/eslint/lib/rules/preserve-caught-error.js new file mode 100644 index 0000000000000000000000000000000000000000..a09c05194d389c43d789e1fc717ef915ba3c2378 --- /dev/null +++ b/tools/ui/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: false, + 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/tools/ui/node_modules/eslint/lib/rules/quote-props.js b/tools/ui/node_modules/eslint/lib/rules/quote-props.js new file mode 100644 index 0000000000000000000000000000000000000000..5cbf77d56f1f56350a66a2ff6134e5748087c9f7 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/quotes.js b/tools/ui/node_modules/eslint/lib/rules/quotes.js new file mode 100644 index 0000000000000000000000000000000000000000..4de678cd35bc5255af3b1add815ed6d5a15f9b0f --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/radix.js b/tools/ui/node_modules/eslint/lib/rules/radix.js new file mode 100644 index 0000000000000000000000000000000000000000..b342636c4a819d9a045885c97c14670f67fa2ca6 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/radix.js @@ -0,0 +1,216 @@ +/** + * @fileoverview Rule to flag use of parseInt without a radix argument + * @author James Allardice + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const MODE_ALWAYS = "always", + MODE_AS_NEEDED = "as-needed"; + +const validRadixValues = new Set( + Array.from({ length: 37 - 2 }, (_, index) => index + 2), +); + +/** + * Checks whether a given variable is shadowed or not. + * @param {eslint-scope.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") + ); +} + +/** + * Checks whether a given node is a default value of radix or not. + * @param {ASTNode} radix A node of radix to check. + * @returns {boolean} `true` if the node is the literal node of `10`. + */ +function isDefaultRadix(radix) { + return radix.type === "Literal" && radix.value === 10; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [MODE_ALWAYS], + + docs: { + description: + "Enforce the consistent use of the radix argument when using `parseInt()`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/radix", + }, + + hasSuggestions: true, + + schema: [ + { + enum: ["always", "as-needed"], + }, + ], + + messages: { + missingParameters: "Missing parameters.", + redundantRadix: "Redundant radix parameter.", + 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 [mode] = context.options; + 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: + if (mode === MODE_ALWAYS) { + 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 (mode === MODE_AS_NEEDED && isDefaultRadix(args[1])) { + context.report({ + node, + messageId: "redundantRadix", + }); + } else 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/tools/ui/node_modules/eslint/lib/rules/require-atomic-updates.js b/tools/ui/node_modules/eslint/lib/rules/require-atomic-updates.js new file mode 100644 index 0000000000000000000000000000000000000000..c3935cca87205325c4d37773fa25afa3479cbbfe --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/require-await.js b/tools/ui/node_modules/eslint/lib/rules/require-await.js new file mode 100644 index 0000000000000000000000000000000000000000..7f3194979c37bad63cbe237533467d717fa0f083 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/require-await.js @@ -0,0 +1,184 @@ +/** + * @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 = + nextToken.type === "Punctuator" && + (nextToken.value === "[" || nextToken.value === "(") && + (nodeWithAsyncKeyword.type === "MethodDefinition" || + astUtils.isStartOfExpressionStatement( + nodeWithAsyncKeyword, + )) && + 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/tools/ui/node_modules/eslint/lib/rules/require-unicode-regexp.js b/tools/ui/node_modules/eslint/lib/rules/require-unicode-regexp.js new file mode 100644 index 0000000000000000000000000000000000000000..fd039afe14773d0788bfe4694be30d98aeb9ef0f --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/require-yield.js b/tools/ui/node_modules/eslint/lib/rules/require-yield.js new file mode 100644 index 0000000000000000000000000000000000000000..0cc8d20cb3fd86b4b2a2e11485e597cf1986c758 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/require-yield.js @@ -0,0 +1,76 @@ +/** + * @fileoverview Rule to flag the generator functions that does not have yield. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// 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 = []; + + /** + * 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({ node, 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/tools/ui/node_modules/eslint/lib/rules/rest-spread-spacing.js b/tools/ui/node_modules/eslint/lib/rules/rest-spread-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..d9b6c74adabf4063224396b8d7074f446fb508b0 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/rest-spread-spacing.js @@ -0,0 +1,153 @@ +/** + * @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.isSpaceBetweenTokens( + 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/tools/ui/node_modules/eslint/lib/rules/semi-spacing.js b/tools/ui/node_modules/eslint/lib/rules/semi-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..f8b9b6621e8f595cd6709b456e89cc45717607ea --- /dev/null +++ b/tools/ui/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.isSpaceBetweenTokens(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.isSpaceBetweenTokens(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/tools/ui/node_modules/eslint/lib/rules/semi-style.js b/tools/ui/node_modules/eslint/lib/rules/semi-style.js new file mode 100644 index 0000000000000000000000000000000000000000..43b32e1486f7286f36778c8d8a84ceedfad9b125 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/semi.js b/tools/ui/node_modules/eslint/lib/rules/semi.js new file mode 100644 index 0000000000000000000000000000000000000000..b6d28d88e19d70066dfe0a8d8176064852d5f794 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/sort-imports.js b/tools/ui/node_modules/eslint/lib/rules/sort-imports.js new file mode 100644 index 0000000000000000000000000000000000000000..e97f3f05fce1e253c64621aa9bf5f0650634b31f --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/sort-keys.js b/tools/ui/node_modules/eslint/lib/rules/sort-keys.js new file mode 100644 index 0000000000000000000000000000000000000000..bbb2dc2b6b738c5af72528f884d9daf061511fe5 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/sort-vars.js b/tools/ui/node_modules/eslint/lib/rules/sort-vars.js new file mode 100644 index 0000000000000000000000000000000000000000..34081b955979840da76a14989435259ac52cfec8 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/space-before-blocks.js b/tools/ui/node_modules/eslint/lib/rules/space-before-blocks.js new file mode 100644 index 0000000000000000000000000000000000000000..0d35276a8661fe2cdc83041971c32dd1d4240765 --- /dev/null +++ b/tools/ui/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.isSpaceBetweenTokens( + 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/tools/ui/node_modules/eslint/lib/rules/space-before-function-paren.js b/tools/ui/node_modules/eslint/lib/rules/space-before-function-paren.js new file mode 100644 index 0000000000000000000000000000000000000000..dad6fde8fd985094a199942b7be233d7e30ded31 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/space-before-function-paren.js @@ -0,0 +1,205 @@ +/** + * @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.isSpaceBetweenTokens( + 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/tools/ui/node_modules/eslint/lib/rules/space-in-parens.js b/tools/ui/node_modules/eslint/lib/rules/space-in-parens.js new file mode 100644 index 0000000000000000000000000000000000000000..623bb381f718a4ed10c8145bd4da50dffcbc423a --- /dev/null +++ b/tools/ui/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.isSpaceBetweenTokens( + 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.isSpaceBetweenTokens( + 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.isSpaceBetweenTokens( + 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.isSpaceBetweenTokens( + 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/tools/ui/node_modules/eslint/lib/rules/space-infix-ops.js b/tools/ui/node_modules/eslint/lib/rules/space-infix-ops.js new file mode 100644 index 0000000000000000000000000000000000000000..825ba05a4bf2340c3a33a7be822e87897403602e --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/space-infix-ops.js @@ -0,0 +1,252 @@ +/** + * @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.isSpaceBetweenTokens(prev, operator) || + !sourceCode.isSpaceBetweenTokens(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.isSpaceBetweenTokens( + leftToken, + operatorToken, + ) || + !sourceCode.isSpaceBetweenTokens(operatorToken, rightToken) + ) { + report(node, operatorToken); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/space-unary-ops.js b/tools/ui/node_modules/eslint/lib/rules/space-unary-ops.js new file mode 100644 index 0000000000000000000000000000000000000000..ee58714741b1b6a2052aaef924f341f3836f9261 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/spaced-comment.js b/tools/ui/node_modules/eslint/lib/rules/spaced-comment.js new file mode 100644 index 0000000000000000000000000000000000000000..cb2a97822ed5a6e14d5cfcb5a25b019404a7a592 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/strict.js b/tools/ui/node_modules/eslint/lib/rules/strict.js new file mode 100644 index 0000000000000000000000000000000000000000..381ad6f5d8a86cea3710dda38c52ed41e559baf3 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/strict.js @@ -0,0 +1,314 @@ +/** + * @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); + } + } + } + + 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 + ) { + context.report({ node, 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/tools/ui/node_modules/eslint/lib/rules/switch-colon-spacing.js b/tools/ui/node_modules/eslint/lib/rules/switch-colon-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..410345b69d91cd7d8cc229da04f156b07be9455e --- /dev/null +++ b/tools/ui/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.isSpaceBetweenTokens(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/tools/ui/node_modules/eslint/lib/rules/symbol-description.js b/tools/ui/node_modules/eslint/lib/rules/symbol-description.js new file mode 100644 index 0000000000000000000000000000000000000000..054c16bec7cff676be1f1bbce336e64d9c48601e --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/template-curly-spacing.js b/tools/ui/node_modules/eslint/lib/rules/template-curly-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..25e3aad027b54c90664ab3bb0ddee85b0cf054f1 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/template-tag-spacing.js b/tools/ui/node_modules/eslint/lib/rules/template-tag-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..10ffe6804e797bf1c242a3bbe7ffd893394dc3fe --- /dev/null +++ b/tools/ui/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.isSpaceBetweenTokens( + 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/tools/ui/node_modules/eslint/lib/rules/unicode-bom.js b/tools/ui/node_modules/eslint/lib/rules/unicode-bom.js new file mode 100644 index 0000000000000000000000000000000000000000..7b054489182cbc55e41febfa814fde7f6658de26 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/use-isnan.js b/tools/ui/node_modules/eslint/lib/rules/use-isnan.js new file mode 100644 index 0000000000000000000000000000000000000000..2c73acf7e219bdbf61b9ff7aa1404c99b3abd152 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/utils/ast-utils.js b/tools/ui/node_modules/eslint/lib/rules/utils/ast-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..dff0945d3c3cfceae5148381495507a07276cd0d --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/utils/ast-utils.js @@ -0,0 +1,2733 @@ +/** + * @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"); + +//------------------------------------------------------------------------------ +// 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 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); +} + +/** + * 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 = sourceCode.getJSDocComment(node); + + 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)); +} + +/** + * 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"; +} + +/** + * 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; +} + +/** + * Determines whether an opening parenthesis `(`, bracket `[` or backtick ``` ` ``` needs to be preceded by a semicolon. + * This opening parenthesis or bracket should be at the start of an `ExpressionStatement`, a `MethodDefinition` 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 or bracket 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]); + + 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, + 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 {eslint-scope.Scope} initScope A scope to start find. + * @param {string} name A variable name to find. + * @returns {eslint-scope.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)) { + 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, + needsPrecedingSemicolon, + isImportAttributeKey, + getOpeningParenOfParams, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/utils/char-source.js b/tools/ui/node_modules/eslint/lib/rules/utils/char-source.js new file mode 100644 index 0000000000000000000000000000000000000000..7a25b27b98970c33619e4fe047b6e03a1ecc3d55 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/utils/fix-tracker.js b/tools/ui/node_modules/eslint/lib/rules/utils/fix-tracker.js new file mode 100644 index 0000000000000000000000000000000000000000..5721717b87d457dd58147bd1884655d16b218e6d --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/utils/keywords.js b/tools/ui/node_modules/eslint/lib/rules/utils/keywords.js new file mode 100644 index 0000000000000000000000000000000000000000..eca2076eb4dd8cc4a453cec0ef5fc4e7590bc5df --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/utils/lazy-loading-rule-map.js b/tools/ui/node_modules/eslint/lib/rules/utils/lazy-loading-rule-map.js new file mode 100644 index 0000000000000000000000000000000000000000..b93395095b9c6fc2899be87dfab7137bbcbef3cb --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/utils/regular-expressions.js b/tools/ui/node_modules/eslint/lib/rules/utils/regular-expressions.js new file mode 100644 index 0000000000000000000000000000000000000000..6d80654b6ee54f5c7b18092ad7a10ae7fe38221e --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/utils/unicode/index.js b/tools/ui/node_modules/eslint/lib/rules/utils/unicode/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0e7d5d53c148a28d410a63296161eb61999f33a1 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/utils/unicode/is-combining-character.js b/tools/ui/node_modules/eslint/lib/rules/utils/unicode/is-combining-character.js new file mode 100644 index 0000000000000000000000000000000000000000..8a36b223f027f46fd44cb36fbd3348f0f832925b --- /dev/null +++ b/tools/ui/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 belongs to the category, any of `Mc`, `Me`, and `Mn`. + */ +module.exports = function isCombiningCharacter(codePoint) { + return /^[\p{Mc}\p{Me}\p{Mn}]$/u.test(String.fromCodePoint(codePoint)); +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/utils/unicode/is-emoji-modifier.js b/tools/ui/node_modules/eslint/lib/rules/utils/unicode/is-emoji-modifier.js new file mode 100644 index 0000000000000000000000000000000000000000..526ac91d6bd6779c323a1039933cade9b1290541 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/utils/unicode/is-regional-indicator-symbol.js b/tools/ui/node_modules/eslint/lib/rules/utils/unicode/is-regional-indicator-symbol.js new file mode 100644 index 0000000000000000000000000000000000000000..019d9da0afd0d6c9077bbd280c6603227cce1c0f --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/utils/unicode/is-surrogate-pair.js b/tools/ui/node_modules/eslint/lib/rules/utils/unicode/is-surrogate-pair.js new file mode 100644 index 0000000000000000000000000000000000000000..fbe6a4017c6fb065d3b5e6275c5796700fa6e395 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/valid-typeof.js b/tools/ui/node_modules/eslint/lib/rules/valid-typeof.js new file mode 100644 index 0000000000000000000000000000000000000000..fd4f3d204802e56f1fa80862d2f86ff8b20ebd12 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/vars-on-top.js b/tools/ui/node_modules/eslint/lib/rules/vars-on-top.js new file mode 100644 index 0000000000000000000000000000000000000000..c790ccbd5cfabc1f753add1178673cd6be778615 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/wrap-iife.js b/tools/ui/node_modules/eslint/lib/rules/wrap-iife.js new file mode 100644 index 0000000000000000000000000000000000000000..3ba53a15198e374b600821fe31c93a00d410e028 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/wrap-regex.js b/tools/ui/node_modules/eslint/lib/rules/wrap-regex.js new file mode 100644 index 0000000000000000000000000000000000000000..def392a4c17054e6abaf66a0aa2c0360a534f56b --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/rules/yield-star-spacing.js b/tools/ui/node_modules/eslint/lib/rules/yield-star-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..05666e2142be27c0a620aa860e636146263eb6d5 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/yield-star-spacing.js @@ -0,0 +1,159 @@ +/** + * @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.isSpaceBetweenTokens(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/tools/ui/node_modules/eslint/lib/rules/yoda.js b/tools/ui/node_modules/eslint/lib/rules/yoda.js new file mode 100644 index 0000000000000000000000000000000000000000..1ee74712da0962c87010fa0e50d56bb91c16ddde --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/services/parser-service.js b/tools/ui/node_modules/eslint/lib/services/parser-service.js new file mode 100644 index 0000000000000000000000000000000000000000..580bb69d5948ac13ec01121febe72ad428fb4f04 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/services/parser-service.js @@ -0,0 +1,65 @@ +/** + * @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, + nodeType: null, + fatal: true, + severity: 2, + message: `Parsing error: ${error.message}`, + line: error.line, + column: error.column, + })), + }; + } +} + +module.exports = { ParserService }; diff --git a/tools/ui/node_modules/eslint/lib/services/processor-service.js b/tools/ui/node_modules/eslint/lib/services/processor-service.js new file mode 100644 index 0000000000000000000000000000000000000000..a5447a80afc70d678ab2b4691f29ac6a744d47bc --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/services/processor-service.js @@ -0,0 +1,101 @@ +/** + * @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, + nodeType: null, + }, + ], + }; + } + + 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/tools/ui/node_modules/eslint/lib/services/suppressions-service.js b/tools/ui/node_modules/eslint/lib/services/suppressions-service.js new file mode 100644 index 0000000000000000000000000000000000000000..c02e59f3eda3744ce2aaf97a9d79ee9c081741c3 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/services/suppressions-service.js @@ -0,0 +1,302 @@ +/** + * @fileoverview Manages the suppressed violations. + * @author Iacovos Constantinou + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const fs = require("node:fs"); +const path = require("node:path"); +const { calculateStatsPerFile } = require("../eslint/eslint-helpers"); +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 { + 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/tools/ui/node_modules/eslint/lib/services/warning-service.js b/tools/ui/node_modules/eslint/lib/services/warning-service.js new file mode 100644 index 0000000000000000000000000000000000000000..38d63fe774ee5d6726ebd8873707ae01d3458d0a --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/services/warning-service.js @@ -0,0 +1,111 @@ +/** + * @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#ignoring-files', + "ESLintIgnoreWarning", + ); + } + + /** + * Emits a warning when the ESLINT_USE_FLAT_CONFIG environment variable is set to "false". + * @returns {void} + */ + emitESLintRCWarning() { + this.emitWarning( + "You are using an eslintrc configuration file, which is deprecated and support will be removed in v10.0.0. Please migrate to an eslint.config.js file. See https://eslint.org/docs/latest/use/configure/migration-guide for details. An eslintrc configuration file is used because you have the ESLINT_USE_FLAT_CONFIG environment variable set to false. If you want to use an eslint.config.js file, remove the environment variable. If you want to find the location of the eslintrc configuration file, use the --debug flag.", + "ESLintRCWarning", + ); + } + + /** + * 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", + ); + } + + /** + * Emits a warning when eslint-env configuration comments are found. + * @param {string} filename The name of the file being linted. + * @param {number} line The line number of the comment. + * @returns {void} + */ + emitESLintEnvWarning(filename, line) { + this.emitWarning( + `/* eslint-env */ comments are no longer recognized when linting with flat config and will be reported as errors as of v10.0.0. Replace them with /* global */ comments or define globals in your config file. See https://eslint.org/docs/latest/use/configure/migration-guide#eslint-env-configuration-comments for details. Found in ${filename} at line ${line}.`, + "ESLintEnvWarning", + ); + } +} + +module.exports = { WarningService }; diff --git a/tools/ui/node_modules/eslint/lib/shared/ajv.js b/tools/ui/node_modules/eslint/lib/shared/ajv.js new file mode 100644 index 0000000000000000000000000000000000000000..5c5c41bd7470bd190bd4efb5caab88c73ae01f56 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/shared/assert.js b/tools/ui/node_modules/eslint/lib/shared/assert.js new file mode 100644 index 0000000000000000000000000000000000000000..4dcaf41f86c5d8b6558a0b38f7ef878b413d1d26 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/shared/ast-utils.js b/tools/ui/node_modules/eslint/lib/shared/ast-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..f7736828b77e98a3b795e850495ad41b72a6c913 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/shared/deep-merge-arrays.js b/tools/ui/node_modules/eslint/lib/shared/deep-merge-arrays.js new file mode 100644 index 0000000000000000000000000000000000000000..4a8289c46e7980d9ea58dafdd74444ee345fd8e9 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/shared/directives.js b/tools/ui/node_modules/eslint/lib/shared/directives.js new file mode 100644 index 0000000000000000000000000000000000000000..f1dddf597d23043cb52d81aa8042031364afa294 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/shared/flags.js b/tools/ui/node_modules/eslint/lib/shared/flags.js new file mode 100644 index 0000000000000000000000000000000000000000..e87e633c3d72a72c40a908375a81872da64771e0 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/shared/flags.js @@ -0,0 +1,108 @@ +/** + * @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."], + [ + "v10_config_lookup_from_file", + "Look up `eslint.config.js` from the file being linted.", + ], + [ + "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.", + }, + ], + [ + "unstable_ts_config", + { + description: "Enable TypeScript configuration files.", + replacedBy: null, + }, + ], + [ + "unstable_config_lookup_from_file", + { + description: + "Look up `eslint.config.js` from the file being linted.", + replacedBy: "v10_config_lookup_from_file", + }, + ], +]); + +/** + * 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/tools/ui/node_modules/eslint/lib/shared/logging.js b/tools/ui/node_modules/eslint/lib/shared/logging.js new file mode 100644 index 0000000000000000000000000000000000000000..3e8dfb0b071a65317f1d1b39fd6adeb8b7359b05 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/shared/naming.js b/tools/ui/node_modules/eslint/lib/shared/naming.js new file mode 100644 index 0000000000000000000000000000000000000000..86621d1382633dcaea7a68e1011d2be7967575ae --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/shared/option-utils.js b/tools/ui/node_modules/eslint/lib/shared/option-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..0917ba5213fde11d1dc2c213bb466f4f6772030e --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/shared/relative-module-resolver.js b/tools/ui/node_modules/eslint/lib/shared/relative-module-resolver.js new file mode 100644 index 0000000000000000000000000000000000000000..14e7eec16d8d9f5af6038640a9e9a40f10404cc3 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/shared/runtime-info.js b/tools/ui/node_modules/eslint/lib/shared/runtime-info.js new file mode 100644 index 0000000000000000000000000000000000000000..54fd7609da920c1d1d10ce969de89200b546e39b --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/shared/serialization.js b/tools/ui/node_modules/eslint/lib/shared/serialization.js new file mode 100644 index 0000000000000000000000000000000000000000..01cacf5ee84eaf2fa11b0a96b47d3c208ae0f3f9 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/shared/severity.js b/tools/ui/node_modules/eslint/lib/shared/severity.js new file mode 100644 index 0000000000000000000000000000000000000000..382704b5a66fa04a5cc6adff686ed2a5e9e1df22 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/shared/stats.js b/tools/ui/node_modules/eslint/lib/shared/stats.js new file mode 100644 index 0000000000000000000000000000000000000000..791b770833017787e68316d36092b85e6b63ab72 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/shared/string-utils.js b/tools/ui/node_modules/eslint/lib/shared/string-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..954c5bfff4aeccdba32e1bdc15961b9c30b53a74 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/shared/text-table.js b/tools/ui/node_modules/eslint/lib/shared/text-table.js new file mode 100644 index 0000000000000000000000000000000000000000..1dfd48166b5002b38ea4446f4ec55002475bfe00 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/shared/translate-cli-options.js b/tools/ui/node_modules/eslint/lib/shared/translate-cli-options.js new file mode 100644 index 0000000000000000000000000000000000000000..d765f8046d567fafa48831870758cc525d53eb9d --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/shared/translate-cli-options.js @@ -0,0 +1,281 @@ +/** + * @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").ESLint.LegacyOptions} LegacyESLintOptions */ +/** @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. + * @param {"flat"|"eslintrc"} [configType="eslintrc"] The format of the config to generate. + * @returns {Promise} The options object for the ESLint constructor. + */ +async function translateOptions( + { + cache, + cacheFile, + cacheLocation, + cacheStrategy, + concurrency, + config, + configLookup, + env, + errorOnUnmatchedPattern, + eslintrc, + ext, + fix, + fixDryRun, + fixType, + flag, + global, + ignore, + ignorePath, + ignorePattern, + inlineConfig, + parser, + parserOptions, + plugin, + quiet, + reportUnusedDisableDirectives, + reportUnusedDisableDirectivesSeverity, + reportUnusedInlineConfigs, + resolvePluginsRelativeTo, + rule, + rulesdir, + stats, + warnIgnored, + passOnNoPatterns, + maxWarnings, + }, + configType, +) { + let overrideConfig, overrideConfigFile; + const importer = new ModuleImporter(); + + if (configType === "flat") { + 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); + } + + 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}`, + ), + }); + } + } else { + overrideConfigFile = config; + + overrideConfig = { + env: + env && + env.reduce((obj, name) => { + obj[name] = true; + return obj; + }, {}), + globals: + global && + global.reduce((obj, name) => { + if (name.endsWith(":true")) { + obj[name.slice(0, -5)] = "writable"; + } else { + obj[name] = "readonly"; + } + return obj; + }, {}), + ignorePatterns: ignorePattern, + parser, + parserOptions, + plugins: plugin, + rules: rule, + }; + } + + const options = { + allowInlineConfig: inlineConfig, + cache, + cacheLocation: cacheLocation || cacheFile, + cacheStrategy, + errorOnUnmatchedPattern, + fix: (fix || fixDryRun) && (quiet ? quietFixPredicate : true), + fixTypes: fixType, + ignore, + overrideConfig, + overrideConfigFile, + passOnNoPatterns, + }; + + if (configType === "flat") { + options.concurrency = concurrency; + options.flags = flag; + options.ignorePatterns = ignorePattern; + options.stats = stats; + options.warnIgnored = warnIgnored; + + /* + * 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. + */ + options.ruleFilter = + quiet && maxWarnings === -1 ? quietRuleFilter : () => true; + } else { + options.resolvePluginsRelativeTo = resolvePluginsRelativeTo; + options.rulePaths = rulesdir; + options.useEslintrc = eslintrc; + options.extensions = ext; + options.ignorePath = ignorePath; + if ( + reportUnusedDisableDirectives || + reportUnusedDisableDirectivesSeverity !== void 0 + ) { + options.reportUnusedDisableDirectives = + reportUnusedDisableDirectives + ? "error" + : normalizeSeverityToString( + reportUnusedDisableDirectivesSeverity, + ); + } + } + + return options; +} + +module.exports = translateOptions; diff --git a/tools/ui/node_modules/eslint/lib/shared/traverser.js b/tools/ui/node_modules/eslint/lib/shared/traverser.js new file mode 100644 index 0000000000000000000000000000000000000000..e13b2cfa5e016c4f5f5c3f955425ce91b00df933 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/types/config-api.d.ts b/tools/ui/node_modules/eslint/lib/types/config-api.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e795add86e35df1082e91cd66c97a4de2efe53dd --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/types/config-api.d.ts @@ -0,0 +1,12 @@ +/** + * @fileoverview typings for "eslint/config" module + * @author Nicholas C. Zakas + */ + +import { + type Config, + defineConfig, + globalIgnores, +} from "@eslint/config-helpers"; + +export { type Config, defineConfig, globalIgnores }; diff --git a/tools/ui/node_modules/eslint/lib/types/index.d.ts b/tools/ui/node_modules/eslint/lib/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..546ca89bf787001901a0ca1d8e5c9ddb56b78def --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/types/index.d.ts @@ -0,0 +1,1915 @@ +/** + * @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 { + CustomRuleDefinitionType, + CustomRuleTypeDefinitions, + 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, + JavaScriptParserOptionsConfig, + 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, +} from "@eslint/core"; +import { LegacyESLint } from "./use-at-your-own-risk.js"; + +//------------------------------------------------------------------------------ +// 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 = [number, number]; + + interface Program extends ESTree.Program { + comments: ESTree.Comment[]; + tokens: Token[]; + loc: SourceLocation; + range: Range; + } +} + +export namespace Scope { + interface ScopeManager { + scopes: Scope[]; + globalScope: Scope | null; + + acquire(node: ESTree.Node, inner?: boolean): Scope | null; + + getDeclaredVariables(node: ESTree.Node): Variable[]; + } + + interface Scope { + type: + | "block" + | "catch" + | "class" + | "class-field-initializer" + | "class-static-block" + | "for" + | "function" + | "function-expression-name" + | "global" + | "module" + | "switch" + | "with" + | "TDZ"; + 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; + from: Scope; + resolved: Variable | null; + writeExpr: ESTree.Node | 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: "TDZ"; node: any; 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[]; + + /** @deprecated */ + getJSDocComment(node: ESTree.Node): ESTree.Comment | null; + + getNodeByRangeIndex(index: number): ESTree.Node | null; + + /** @deprecated Use `isSpaceBetween()` instead. */ + isSpaceBetweenTokens( + first: ESTree.Node | AST.Token, + second: ESTree.Node | AST.Token, + ): boolean; + + 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; + + /** @deprecated Use `getTokenBefore()` instead. */ + getTokenOrCommentBefore( + node: ESTree.Node | AST.Token | ESTree.Comment, + skip?: number | undefined, + ): AST.Token | ESTree.Comment | null; + + /** @deprecated Use `getTokenAfter()` instead. */ + getTokenOrCommentAfter( + node: ESTree.Node | AST.Token | ESTree.Comment, + skip?: number | undefined, + ): AST.Token | ESTree.Comment | null; + + 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 RuleVisitor { + ArrayExpression?: + | ((node: ESTree.ArrayExpression & NodeParentExtension) => void) + | undefined; + "ArrayExpression:exit"?: + | ((node: ESTree.ArrayExpression & NodeParentExtension) => void) + | undefined; + ArrayPattern?: + | ((node: ESTree.ArrayPattern & NodeParentExtension) => void) + | undefined; + "ArrayPattern:exit"?: + | ((node: ESTree.ArrayPattern & NodeParentExtension) => void) + | undefined; + ArrowFunctionExpression?: + | (( + node: ESTree.ArrowFunctionExpression & NodeParentExtension, + ) => void) + | undefined; + "ArrowFunctionExpression:exit"?: + | (( + node: ESTree.ArrowFunctionExpression & NodeParentExtension, + ) => void) + | undefined; + AssignmentExpression?: + | (( + node: ESTree.AssignmentExpression & NodeParentExtension, + ) => void) + | undefined; + "AssignmentExpression:exit"?: + | (( + node: ESTree.AssignmentExpression & NodeParentExtension, + ) => void) + | undefined; + AssignmentPattern?: + | ((node: ESTree.AssignmentPattern & NodeParentExtension) => void) + | undefined; + "AssignmentPattern:exit"?: + | ((node: ESTree.AssignmentPattern & NodeParentExtension) => void) + | undefined; + AwaitExpression?: + | ((node: ESTree.AwaitExpression & NodeParentExtension) => void) + | undefined; + "AwaitExpression:exit"?: + | ((node: ESTree.AwaitExpression & NodeParentExtension) => void) + | undefined; + BinaryExpression?: + | ((node: ESTree.BinaryExpression & NodeParentExtension) => void) + | undefined; + "BinaryExpression:exit"?: + | ((node: ESTree.BinaryExpression & NodeParentExtension) => void) + | undefined; + BlockStatement?: + | ((node: ESTree.BlockStatement & NodeParentExtension) => void) + | undefined; + "BlockStatement:exit"?: + | ((node: ESTree.BlockStatement & NodeParentExtension) => void) + | undefined; + BreakStatement?: + | ((node: ESTree.BreakStatement & NodeParentExtension) => void) + | undefined; + "BreakStatement:exit"?: + | ((node: ESTree.BreakStatement & NodeParentExtension) => void) + | undefined; + CallExpression?: + | (( + node: ESTree.SimpleCallExpression & NodeParentExtension, + ) => void) + | undefined; + "CallExpression:exit"?: + | (( + node: ESTree.SimpleCallExpression & NodeParentExtension, + ) => void) + | undefined; + CatchClause?: + | ((node: ESTree.CatchClause & NodeParentExtension) => void) + | undefined; + "CatchClause:exit"?: + | ((node: ESTree.CatchClause & NodeParentExtension) => void) + | undefined; + ChainExpression?: + | ((node: ESTree.ChainExpression & NodeParentExtension) => void) + | undefined; + "ChainExpression:exit"?: + | ((node: ESTree.ChainExpression & NodeParentExtension) => void) + | undefined; + ClassBody?: + | ((node: ESTree.ClassBody & NodeParentExtension) => void) + | undefined; + "ClassBody:exit"?: + | ((node: ESTree.ClassBody & NodeParentExtension) => void) + | undefined; + ClassDeclaration?: + | ((node: ESTree.ClassDeclaration & NodeParentExtension) => void) + | undefined; + "ClassDeclaration:exit"?: + | ((node: ESTree.ClassDeclaration & NodeParentExtension) => void) + | undefined; + ClassExpression?: + | ((node: ESTree.ClassExpression & NodeParentExtension) => void) + | undefined; + "ClassExpression:exit"?: + | ((node: ESTree.ClassExpression & NodeParentExtension) => void) + | undefined; + ConditionalExpression?: + | (( + node: ESTree.ConditionalExpression & NodeParentExtension, + ) => void) + | undefined; + "ConditionalExpression:exit"?: + | (( + node: ESTree.ConditionalExpression & NodeParentExtension, + ) => void) + | undefined; + ContinueStatement?: + | ((node: ESTree.ContinueStatement & NodeParentExtension) => void) + | undefined; + "ContinueStatement:exit"?: + | ((node: ESTree.ContinueStatement & NodeParentExtension) => void) + | undefined; + DebuggerStatement?: + | ((node: ESTree.DebuggerStatement & NodeParentExtension) => void) + | undefined; + "DebuggerStatement:exit"?: + | ((node: ESTree.DebuggerStatement & NodeParentExtension) => void) + | undefined; + DoWhileStatement?: + | ((node: ESTree.DoWhileStatement & NodeParentExtension) => void) + | undefined; + "DoWhileStatement:exit"?: + | ((node: ESTree.DoWhileStatement & NodeParentExtension) => void) + | undefined; + EmptyStatement?: + | ((node: ESTree.EmptyStatement & NodeParentExtension) => void) + | undefined; + "EmptyStatement:exit"?: + | ((node: ESTree.EmptyStatement & NodeParentExtension) => void) + | undefined; + ExportAllDeclaration?: + | (( + node: ESTree.ExportAllDeclaration & NodeParentExtension, + ) => void) + | undefined; + "ExportAllDeclaration:exit"?: + | (( + node: ESTree.ExportAllDeclaration & NodeParentExtension, + ) => void) + | undefined; + ExportDefaultDeclaration?: + | (( + node: ESTree.ExportDefaultDeclaration & NodeParentExtension, + ) => void) + | undefined; + "ExportDefaultDeclaration:exit"?: + | (( + node: ESTree.ExportDefaultDeclaration & NodeParentExtension, + ) => void) + | undefined; + ExportNamedDeclaration?: + | (( + node: ESTree.ExportNamedDeclaration & NodeParentExtension, + ) => void) + | undefined; + "ExportNamedDeclaration:exit"?: + | (( + node: ESTree.ExportNamedDeclaration & NodeParentExtension, + ) => void) + | undefined; + ExportSpecifier?: + | ((node: ESTree.ExportSpecifier & NodeParentExtension) => void) + | undefined; + "ExportSpecifier:exit"?: + | ((node: ESTree.ExportSpecifier & NodeParentExtension) => void) + | undefined; + ExpressionStatement?: + | ((node: ESTree.ExpressionStatement & NodeParentExtension) => void) + | undefined; + "ExpressionStatement:exit"?: + | ((node: ESTree.ExpressionStatement & NodeParentExtension) => void) + | undefined; + ForInStatement?: + | ((node: ESTree.ForInStatement & NodeParentExtension) => void) + | undefined; + "ForInStatement:exit"?: + | ((node: ESTree.ForInStatement & NodeParentExtension) => void) + | undefined; + ForOfStatement?: + | ((node: ESTree.ForOfStatement & NodeParentExtension) => void) + | undefined; + "ForOfStatement:exit"?: + | ((node: ESTree.ForOfStatement & NodeParentExtension) => void) + | undefined; + ForStatement?: + | ((node: ESTree.ForStatement & NodeParentExtension) => void) + | undefined; + "ForStatement:exit"?: + | ((node: ESTree.ForStatement & NodeParentExtension) => void) + | undefined; + FunctionDeclaration?: + | ((node: ESTree.FunctionDeclaration & NodeParentExtension) => void) + | undefined; + "FunctionDeclaration:exit"?: + | ((node: ESTree.FunctionDeclaration & NodeParentExtension) => void) + | undefined; + FunctionExpression?: + | ((node: ESTree.FunctionExpression & NodeParentExtension) => void) + | undefined; + "FunctionExpression:exit"?: + | ((node: ESTree.FunctionExpression & NodeParentExtension) => void) + | undefined; + Identifier?: + | ((node: ESTree.Identifier & NodeParentExtension) => void) + | undefined; + "Identifier:exit"?: + | ((node: ESTree.Identifier & NodeParentExtension) => void) + | undefined; + IfStatement?: + | ((node: ESTree.IfStatement & NodeParentExtension) => void) + | undefined; + "IfStatement:exit"?: + | ((node: ESTree.IfStatement & NodeParentExtension) => void) + | undefined; + ImportDeclaration?: + | ((node: ESTree.ImportDeclaration & NodeParentExtension) => void) + | undefined; + "ImportDeclaration:exit"?: + | ((node: ESTree.ImportDeclaration & NodeParentExtension) => void) + | undefined; + ImportDefaultSpecifier?: + | (( + node: ESTree.ImportDefaultSpecifier & NodeParentExtension, + ) => void) + | undefined; + "ImportDefaultSpecifier:exit"?: + | (( + node: ESTree.ImportDefaultSpecifier & NodeParentExtension, + ) => void) + | undefined; + ImportExpression?: + | ((node: ESTree.ImportExpression & NodeParentExtension) => void) + | undefined; + "ImportExpression:exit"?: + | ((node: ESTree.ImportExpression & NodeParentExtension) => void) + | undefined; + ImportNamespaceSpecifier?: + | (( + node: ESTree.ImportNamespaceSpecifier & NodeParentExtension, + ) => void) + | undefined; + "ImportNamespaceSpecifier:exit"?: + | (( + node: ESTree.ImportNamespaceSpecifier & NodeParentExtension, + ) => void) + | undefined; + ImportSpecifier?: + | ((node: ESTree.ImportSpecifier & NodeParentExtension) => void) + | undefined; + "ImportSpecifier:exit"?: + | ((node: ESTree.ImportSpecifier & NodeParentExtension) => void) + | undefined; + LabeledStatement?: + | ((node: ESTree.LabeledStatement & NodeParentExtension) => void) + | undefined; + "LabeledStatement:exit"?: + | ((node: ESTree.LabeledStatement & NodeParentExtension) => void) + | undefined; + Literal?: + | ((node: ESTree.Literal & NodeParentExtension) => void) + | undefined; + "Literal:exit"?: + | ((node: ESTree.Literal & NodeParentExtension) => void) + | undefined; + LogicalExpression?: + | ((node: ESTree.LogicalExpression & NodeParentExtension) => void) + | undefined; + "LogicalExpression:exit"?: + | ((node: ESTree.LogicalExpression & NodeParentExtension) => void) + | undefined; + MemberExpression?: + | ((node: ESTree.MemberExpression & NodeParentExtension) => void) + | undefined; + "MemberExpression:exit"?: + | ((node: ESTree.MemberExpression & NodeParentExtension) => void) + | undefined; + MetaProperty?: + | ((node: ESTree.MetaProperty & NodeParentExtension) => void) + | undefined; + "MetaProperty:exit"?: + | ((node: ESTree.MetaProperty & NodeParentExtension) => void) + | undefined; + MethodDefinition?: + | ((node: ESTree.MethodDefinition & NodeParentExtension) => void) + | undefined; + "MethodDefinition:exit"?: + | ((node: ESTree.MethodDefinition & NodeParentExtension) => void) + | undefined; + NewExpression?: + | ((node: ESTree.NewExpression & NodeParentExtension) => void) + | undefined; + "NewExpression:exit"?: + | ((node: ESTree.NewExpression & NodeParentExtension) => void) + | undefined; + ObjectExpression?: + | ((node: ESTree.ObjectExpression & NodeParentExtension) => void) + | undefined; + "ObjectExpression:exit"?: + | ((node: ESTree.ObjectExpression & NodeParentExtension) => void) + | undefined; + ObjectPattern?: + | ((node: ESTree.ObjectPattern & NodeParentExtension) => void) + | undefined; + "ObjectPattern:exit"?: + | ((node: ESTree.ObjectPattern & NodeParentExtension) => void) + | undefined; + PrivateIdentifier?: + | ((node: ESTree.PrivateIdentifier & NodeParentExtension) => void) + | undefined; + "PrivateIdentifier:exit"?: + | ((node: ESTree.PrivateIdentifier & NodeParentExtension) => void) + | undefined; + Program?: ((node: AST.Program) => void) | undefined; + "Program:exit"?: ((node: AST.Program) => void) | undefined; + Property?: + | ((node: ESTree.Property & NodeParentExtension) => void) + | undefined; + "Property:exit"?: + | ((node: ESTree.Property & NodeParentExtension) => void) + | undefined; + PropertyDefinition?: + | ((node: ESTree.PropertyDefinition & NodeParentExtension) => void) + | undefined; + "PropertyDefinition:exit"?: + | ((node: ESTree.PropertyDefinition & NodeParentExtension) => void) + | undefined; + RestElement?: + | ((node: ESTree.RestElement & NodeParentExtension) => void) + | undefined; + "RestElement:exit"?: + | ((node: ESTree.RestElement & NodeParentExtension) => void) + | undefined; + ReturnStatement?: + | ((node: ESTree.ReturnStatement & NodeParentExtension) => void) + | undefined; + "ReturnStatement:exit"?: + | ((node: ESTree.ReturnStatement & NodeParentExtension) => void) + | undefined; + SequenceExpression?: + | ((node: ESTree.SequenceExpression & NodeParentExtension) => void) + | undefined; + "SequenceExpression:exit"?: + | ((node: ESTree.SequenceExpression & NodeParentExtension) => void) + | undefined; + SpreadElement?: + | ((node: ESTree.SpreadElement & NodeParentExtension) => void) + | undefined; + "SpreadElement:exit"?: + | ((node: ESTree.SpreadElement & NodeParentExtension) => void) + | undefined; + StaticBlock?: + | ((node: ESTree.StaticBlock & NodeParentExtension) => void) + | undefined; + "StaticBlock:exit"?: + | ((node: ESTree.StaticBlock & NodeParentExtension) => void) + | undefined; + Super?: + | ((node: ESTree.Super & NodeParentExtension) => void) + | undefined; + "Super:exit"?: + | ((node: ESTree.Super & NodeParentExtension) => void) + | undefined; + SwitchCase?: + | ((node: ESTree.SwitchCase & NodeParentExtension) => void) + | undefined; + "SwitchCase:exit"?: + | ((node: ESTree.SwitchCase & NodeParentExtension) => void) + | undefined; + SwitchStatement?: + | ((node: ESTree.SwitchStatement & NodeParentExtension) => void) + | undefined; + "SwitchStatement:exit"?: + | ((node: ESTree.SwitchStatement & NodeParentExtension) => void) + | undefined; + TaggedTemplateExpression?: + | (( + node: ESTree.TaggedTemplateExpression & NodeParentExtension, + ) => void) + | undefined; + "TaggedTemplateExpression:exit"?: + | (( + node: ESTree.TaggedTemplateExpression & NodeParentExtension, + ) => void) + | undefined; + TemplateElement?: + | ((node: ESTree.TemplateElement & NodeParentExtension) => void) + | undefined; + "TemplateElement:exit"?: + | ((node: ESTree.TemplateElement & NodeParentExtension) => void) + | undefined; + TemplateLiteral?: + | ((node: ESTree.TemplateLiteral & NodeParentExtension) => void) + | undefined; + "TemplateLiteral:exit"?: + | ((node: ESTree.TemplateLiteral & NodeParentExtension) => void) + | undefined; + ThisExpression?: + | ((node: ESTree.ThisExpression & NodeParentExtension) => void) + | undefined; + "ThisExpression:exit"?: + | ((node: ESTree.ThisExpression & NodeParentExtension) => void) + | undefined; + ThrowStatement?: + | ((node: ESTree.ThrowStatement & NodeParentExtension) => void) + | undefined; + "ThrowStatement:exit"?: + | ((node: ESTree.ThrowStatement & NodeParentExtension) => void) + | undefined; + TryStatement?: + | ((node: ESTree.TryStatement & NodeParentExtension) => void) + | undefined; + "TryStatement:exit"?: + | ((node: ESTree.TryStatement & NodeParentExtension) => void) + | undefined; + UnaryExpression?: + | ((node: ESTree.UnaryExpression & NodeParentExtension) => void) + | undefined; + "UnaryExpression:exit"?: + | ((node: ESTree.UnaryExpression & NodeParentExtension) => void) + | undefined; + UpdateExpression?: + | ((node: ESTree.UpdateExpression & NodeParentExtension) => void) + | undefined; + "UpdateExpression:exit"?: + | ((node: ESTree.UpdateExpression & NodeParentExtension) => void) + | undefined; + VariableDeclaration?: + | ((node: ESTree.VariableDeclaration & NodeParentExtension) => void) + | undefined; + "VariableDeclaration:exit"?: + | ((node: ESTree.VariableDeclaration & NodeParentExtension) => void) + | undefined; + VariableDeclarator?: + | ((node: ESTree.VariableDeclarator & NodeParentExtension) => void) + | undefined; + "VariableDeclarator:exit"?: + | ((node: ESTree.VariableDeclarator & NodeParentExtension) => void) + | undefined; + WhileStatement?: + | ((node: ESTree.WhileStatement & NodeParentExtension) => void) + | undefined; + "WhileStatement:exit"?: + | ((node: ESTree.WhileStatement & NodeParentExtension) => void) + | undefined; + WithStatement?: + | ((node: ESTree.WithStatement & NodeParentExtension) => void) + | undefined; + "WithStatement:exit"?: + | ((node: ESTree.WithStatement & NodeParentExtension) => void) + | undefined; + YieldExpression?: + | ((node: ESTree.YieldExpression & NodeParentExtension) => void) + | undefined; + "YieldExpression:exit"?: + | ((node: ESTree.YieldExpression & NodeParentExtension) => 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 CodePath { + id: string; + origin: CodePathOrigin; + initialSegment: CodePathSegment; + finalSegments: CodePathSegment[]; + returnedSegments: CodePathSegment[]; + thrownSegments: CodePathSegment[]; + upper: CodePath | null; + childCodePaths: CodePath[]; + } + + interface CodePathSegment { + id: string; + nextSegments: CodePathSegment[]; + prevSegments: 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 = ViolationReportBase; + + 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" | "eslintrc"; + }); + + verify( + code: SourceCode | string, + config: Linter.LegacyConfig | Linter.Config | Linter.Config[], + filename?: string, + ): Linter.LintMessage[]; + verify( + code: SourceCode | string, + config: Linter.LegacyConfig | Linter.Config | Linter.Config[], + options: Linter.LintOptions, + ): Linter.LintMessage[]; + + verifyAndFix( + code: string, + config: Linter.LegacyConfig | Linter.Config | Linter.Config[], + filename?: string, + ): Linter.FixReport; + verifyAndFix( + code: string, + config: Linter.LegacyConfig | Linter.Config | Linter.Config[], + options: Linter.FixOptions, + ): Linter.FixReport; + + getSourceCode(): SourceCode; + + defineRule(name: string, rule: Rule.RuleModule): void; + + defineRules(rules: { [name: string]: Rule.RuleModule }): void; + + getRules(): Map; + + defineParser(name: string, parser: Linter.Parser): void; + + 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) + */ + type ParserOptions = JavaScriptParserOptionsConfig; + + /** + * 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"; + + interface Options { + // File enumeration + cwd?: string | undefined; + errorOnUnmatchedPattern?: boolean | undefined; + globInputPaths?: boolean | undefined; + ignore?: boolean | undefined; + ignorePatterns?: string[] | null | undefined; + passOnNoPatterns?: boolean | undefined; + warnIgnored?: boolean | undefined; + + // Linting + allowInlineConfig?: boolean | undefined; + baseConfig?: Linter.Config | Linter.Config[] | null | undefined; + overrideConfig?: Linter.Config | Linter.Config[] | null | undefined; + overrideConfigFile?: string | true | null | undefined; + plugins?: Record | null | undefined; + ruleFilter?: + | ((arg: { + ruleId: string; + severity: Exclude; + }) => boolean) + | undefined; + stats?: boolean | undefined; + + // Autofix + fix?: boolean | ((message: Linter.LintMessage) => boolean) | undefined; + fixTypes?: FixType[] | null | undefined; + + // Cache-related + cache?: boolean | undefined; + cacheLocation?: string | undefined; + cacheStrategy?: CacheStrategy | undefined; + + // Other Options + concurrency?: number | "auto" | "off" | undefined; + flags?: string[] | undefined; + } + + interface LegacyOptions { + // File enumeration + cwd?: string | undefined; + errorOnUnmatchedPattern?: boolean | undefined; + extensions?: string[] | undefined; + globInputPaths?: boolean | undefined; + ignore?: boolean | undefined; + ignorePath?: string | undefined; + + // Linting + allowInlineConfig?: boolean | undefined; + baseConfig?: Linter.LegacyConfig | undefined; + overrideConfig?: Linter.LegacyConfig | undefined; + overrideConfigFile?: string | undefined; + plugins?: Record | undefined; + reportUnusedDisableDirectives?: Linter.StringSeverity | undefined; + resolvePluginsRelativeTo?: string | undefined; + rulePaths?: string[] | undefined; + useEslintrc?: boolean | undefined; + + // Autofix + fix?: boolean | ((message: Linter.LintMessage) => boolean) | undefined; + fixTypes?: FixType[] | null | undefined; + + // Cache-related + cache?: boolean | undefined; + cacheLocation?: string | undefined; + cacheStrategy?: CacheStrategy | undefined; + + // Other Options + 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 { + cwd: string; + maxWarningsExceeded?: MaxWarningsExceeded | undefined; + 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 { + /** + * 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 an optional `maxWarningsExceeded` property that will be + * passed to the underlying formatter function along with other properties set by ESLint. + * This argument can be omitted if `maxWarningsExceeded` is 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 + +export function loadESLint(options: { + useFlatConfig: true; +}): Promise; +export function loadESLint(options: { + useFlatConfig: false; +}): Promise; +export function loadESLint(options?: { + useFlatConfig?: boolean | undefined; +}): Promise; + +// #region RuleTester + +export class RuleTester { + static describe: ((...args: any) => any) | null; + static it: ((...args: any) => any) | null; + static itOnly: ((...args: any) => any) | null; + + constructor(config?: Linter.Config); + + run( + name: string, + rule: RuleDefinition, + tests: { + valid: Array; + invalid: RuleTester.InvalidTestCase[]; + }, + ): void; + + static only( + item: string | RuleTester.ValidTestCase | RuleTester.InvalidTestCase, + ): RuleTester.ValidTestCase | RuleTester.InvalidTestCase; +} + +export namespace RuleTester { + interface ValidTestCase { + name?: string; + code: string; + options?: any; + filename?: string | undefined; + only?: boolean; + languageOptions?: Linter.LanguageOptions | undefined; + settings?: { [name: string]: any } | undefined; + before?: () => void; + after?: () => void; + } + + interface SuggestionOutput { + messageId?: string; + desc?: string; + data?: Record | undefined; + output: string; + } + + interface InvalidTestCase extends ValidTestCase { + errors: number | Array; + output?: string | null | undefined; + } + + interface TestCaseError { + message?: string | RegExp; + messageId?: string; + /** + * @deprecated `type` is deprecated and will be removed in the next major version. + */ + type?: string | undefined; + data?: any; + line?: number | undefined; + column?: number | undefined; + endLine?: number | undefined; + endColumn?: number | undefined; + suggestions?: SuggestionOutput[] | undefined; + } +} + +// #endregion diff --git a/tools/ui/node_modules/eslint/lib/types/rules.d.ts b/tools/ui/node_modules/eslint/lib/types/rules.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e74eaf76d04bc4eb5c8634364b32f6875b37a531 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/types/rules.d.ts @@ -0,0 +1,5589 @@ +/** + * @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; + /** + * @default false + */ + countVoidThis: boolean; + }>, + ] + >; + + /** + * 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 false + */ + 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. + * + * @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. + * + * @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. + * + * @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 consistent 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/tools/ui/node_modules/eslint/lib/types/universal.d.ts b/tools/ui/node_modules/eslint/lib/types/universal.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..df4fdecda75df4a8ce63bd47c0e570d01339a649 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/types/use-at-your-own-risk.d.ts b/tools/ui/node_modules/eslint/lib/types/use-at-your-own-risk.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f97f4f341ea13ab3dcacf84f8a55d143b4890cca --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/types/use-at-your-own-risk.d.ts @@ -0,0 +1,87 @@ +/** + * @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 { ESLint, Rule } from "./index.js"; + +/** @deprecated */ +export const builtinRules: Map; + +/** @deprecated */ +export class FileEnumerator { + constructor(params?: { + cwd?: string; + configArrayFactory?: any; + extensions?: any; + globInputPaths?: boolean; + errorOnUnmatchedPattern?: boolean; + ignore?: boolean; + }); + isTargetPath(filePath: string, providedConfig?: any): boolean; + iterateFiles( + patternOrPatterns: string | string[], + ): IterableIterator<{ config: any; filePath: string; ignored: boolean }>; +} + +export { /** @deprecated */ ESLint as FlatESLint }; + +/** @deprecated */ +export class LegacyESLint { + static configType: "eslintrc"; + + static readonly version: string; + + static outputFixes(results: ESLint.LintResult[]): Promise; + + static getErrorResults(results: ESLint.LintResult[]): ESLint.LintResult[]; + + constructor(options?: ESLint.LegacyOptions); + + 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): false; + + calculateConfigForFile(filePath: string): Promise; + + isPathIgnored(filePath: string): Promise; + + loadFormatter(nameOrPath?: string): Promise; +} + +/** @deprecated */ +export function shouldUseFlatConfig(): Promise; diff --git a/tools/ui/node_modules/eslint/lib/universal.js b/tools/ui/node_modules/eslint/lib/universal.js new file mode 100644 index 0000000000000000000000000000000000000000..51bac58453c98b3b65b93fc3498317afe1ace747 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/lib/unsupported-api.js b/tools/ui/node_modules/eslint/lib/unsupported-api.js new file mode 100644 index 0000000000000000000000000000000000000000..2287728e196311d003bc4576e23945b84d5a182f --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/unsupported-api.js @@ -0,0 +1,29 @@ +/** + * @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 { FileEnumerator } = require("./cli-engine/file-enumerator"); +const { ESLint: FlatESLint, shouldUseFlatConfig } = require("./eslint/eslint"); +const { LegacyESLint } = require("./eslint/legacy-eslint"); +const builtinRules = require("./rules"); + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +module.exports = { + builtinRules, + FlatESLint, + shouldUseFlatConfig, + FileEnumerator, + LegacyESLint, +}; diff --git a/tools/ui/node_modules/eslint/messages/all-files-ignored.js b/tools/ui/node_modules/eslint/messages/all-files-ignored.js new file mode 100644 index 0000000000000000000000000000000000000000..3e795c9a4a4442307c08e59b946f5331a4128417 --- /dev/null +++ b/tools/ui/node_modules/eslint/messages/all-files-ignored.js @@ -0,0 +1,16 @@ +"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, try the following solutions: + +* Check your .eslintignore file, or the eslintIgnore property in package.json, to ensure that the files are not configured to be ignored. +* Explicitly list the files from this glob that you'd like to lint on the command-line, rather than providing a glob as an argument. +`.trimStart(); +}; diff --git a/tools/ui/node_modules/eslint/messages/all-matched-files-ignored.js b/tools/ui/node_modules/eslint/messages/all-matched-files-ignored.js new file mode 100644 index 0000000000000000000000000000000000000000..2621343bf0c22e4fe3e1926e4708109b1502d44c --- /dev/null +++ b/tools/ui/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#specifying-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/tools/ui/node_modules/eslint/messages/config-file-missing.js b/tools/ui/node_modules/eslint/messages/config-file-missing.js new file mode 100644 index 0000000000000000000000000000000000000000..c4f8ecdbf1629e41affff3b3e3ee0ce29f771467 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/messages/config-plugin-missing.js b/tools/ui/node_modules/eslint/messages/config-plugin-missing.js new file mode 100644 index 0000000000000000000000000000000000000000..207367491ba3b9a403311d31e7af7d7cd7278439 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/messages/config-serialize-function.js b/tools/ui/node_modules/eslint/messages/config-serialize-function.js new file mode 100644 index 0000000000000000000000000000000000000000..4300e47e452ac9a8f22ffb80fe45f5ffbcb011db --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/messages/eslintrc-incompat.js b/tools/ui/node_modules/eslint/messages/eslintrc-incompat.js new file mode 100644 index 0000000000000000000000000000000000000000..27fe8c9f4b1805b6fba32c0ca58fd201f8af63db --- /dev/null +++ b/tools/ui/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#configuring-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#using-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#using-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#configuring-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#using-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#ignoring-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#using-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#using-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#using-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#configuring-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#using-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/tools/ui/node_modules/eslint/messages/eslintrc-plugins.js b/tools/ui/node_modules/eslint/messages/eslintrc-plugins.js new file mode 100644 index 0000000000000000000000000000000000000000..68cee2099f17297a6c340936be29a56b6692ef56 --- /dev/null +++ b/tools/ui/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#importing-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#using-eslintrc-configs-in-flat-config +`; +}; diff --git a/tools/ui/node_modules/eslint/messages/extend-config-missing.js b/tools/ui/node_modules/eslint/messages/extend-config-missing.js new file mode 100644 index 0000000000000000000000000000000000000000..32e41e960c8c2eccf645d0811b677db3f8b5693a --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/messages/failed-to-read-json.js b/tools/ui/node_modules/eslint/messages/failed-to-read-json.js new file mode 100644 index 0000000000000000000000000000000000000000..3244e842876711b616e65c746238ca9bc3506e23 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/messages/file-not-found.js b/tools/ui/node_modules/eslint/messages/file-not-found.js new file mode 100644 index 0000000000000000000000000000000000000000..50e483bc1a3f35dc67d508bfd75746d3aae06a5e --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/messages/invalid-rule-options.js b/tools/ui/node_modules/eslint/messages/invalid-rule-options.js new file mode 100644 index 0000000000000000000000000000000000000000..05354cb4895138c11706382d0478eda1f2ddd788 --- /dev/null +++ b/tools/ui/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#using-configuration-files for configuring rules. +`.trimStart(); +}; diff --git a/tools/ui/node_modules/eslint/messages/invalid-rule-severity.js b/tools/ui/node_modules/eslint/messages/invalid-rule-severity.js new file mode 100644 index 0000000000000000000000000000000000000000..17e9b5d46e3fc2ae52a6297fb004e7ffe96319e4 --- /dev/null +++ b/tools/ui/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#using-configuration-files for configuring rules. +`.trimStart(); +}; diff --git a/tools/ui/node_modules/eslint/messages/no-config-found.js b/tools/ui/node_modules/eslint/messages/no-config-found.js new file mode 100644 index 0000000000000000000000000000000000000000..4421206dfa486e7eb134629219f0fc38af26335b --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/messages/plugin-conflict.js b/tools/ui/node_modules/eslint/messages/plugin-conflict.js new file mode 100644 index 0000000000000000000000000000000000000000..d90df0cae7683bdb5415ec80d34b9f8a6a834157 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/messages/plugin-invalid.js b/tools/ui/node_modules/eslint/messages/plugin-invalid.js new file mode 100644 index 0000000000000000000000000000000000000000..fc9ff6ab5187cc92b761f25ad49792e49797e2e1 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/messages/plugin-missing.js b/tools/ui/node_modules/eslint/messages/plugin-missing.js new file mode 100644 index 0000000000000000000000000000000000000000..6152a6a4472177efb4a2a7357d708153214c0066 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/messages/print-config-with-directory-path.js b/tools/ui/node_modules/eslint/messages/print-config-with-directory-path.js new file mode 100644 index 0000000000000000000000000000000000000000..9f37745f20b365617b841c20c10143685100c72c --- /dev/null +++ b/tools/ui/node_modules/eslint/messages/print-config-with-directory-path.js @@ -0,0 +1,8 @@ +"use strict"; + +module.exports = function () { + return ` +The '--print-config' CLI option requires a path to a source code file rather than a directory. +See also: https://eslint.org/docs/latest/use/command-line-interface#--print-config +`.trimStart(); +}; diff --git a/tools/ui/node_modules/eslint/messages/shared.js b/tools/ui/node_modules/eslint/messages/shared.js new file mode 100644 index 0000000000000000000000000000000000000000..4244ed6800263416b1fcfdacefdabe3834a3b2e8 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/messages/whitespace-found.js b/tools/ui/node_modules/eslint/messages/whitespace-found.js new file mode 100644 index 0000000000000000000000000000000000000000..c61602165ed40d66708e5cc635e3ce69b236e856 --- /dev/null +++ b/tools/ui/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/tools/ui/node_modules/eslint/node_modules/@eslint/js/LICENSE b/tools/ui/node_modules/eslint/node_modules/@eslint/js/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b607bb36e96c33fd8ef50897db0336c585b6137a --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/@eslint/js/LICENSE @@ -0,0 +1,19 @@ +Copyright OpenJS Foundation and other 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/tools/ui/node_modules/eslint/node_modules/@eslint/js/README.md b/tools/ui/node_modules/eslint/node_modules/@eslint/js/README.md new file mode 100644 index 0000000000000000000000000000000000000000..eae3d22e06c6fea6599596c25edf8c6b59e29f3b --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/@eslint/js/README.md @@ -0,0 +1,103 @@ +[![npm version](https://img.shields.io/npm/v/@eslint/js.svg)](https://www.npmjs.com/package/@eslint/js) +[![Downloads](https://img.shields.io/npm/dm/@eslint/js.svg)](https://www.npmjs.com/package/@eslint/js) +[![Build Status](https://github.com/eslint/eslint/workflows/CI/badge.svg)](https://github.com/eslint/eslint/actions) +
+[![Open Collective Backers](https://img.shields.io/opencollective/backers/eslint)](https://opencollective.com/eslint) +[![Open Collective Sponsors](https://img.shields.io/opencollective/sponsors/eslint)](https://opencollective.com/eslint) + +# ESLint JavaScript Plugin + +[Website](https://eslint.org) | +[Configure ESLint](https://eslint.org/docs/latest/use/configure) | +[Rules](https://eslint.org/docs/rules/) | +[Contribute to ESLint](https://eslint.org/docs/latest/contribute) | +[Report Bugs](https://eslint.org/docs/latest/contribute/report-bugs) | +[Code of Conduct](https://eslint.org/conduct) | +[X](https://x.com/geteslint) | +[Discord](https://eslint.org/chat) | +[Mastodon](https://fosstodon.org/@eslint) | +[Bluesky](https://bsky.app/profile/eslint.org) + +The beginnings of separating out JavaScript-specific functionality from ESLint. + +Right now, this plugin contains two configurations: + +- `recommended` - enables the rules recommended by the ESLint team (the replacement for `"eslint:recommended"`) +- `all` - enables all ESLint rules (the replacement for `"eslint:all"`) + +## Installation + +You can install ESLint using npm or other package managers: + +```shell +npm install eslint -D +# or +yarn add eslint -D +# or +pnpm install eslint -D +# or +bun add eslint -D +``` + +Then install this plugin: + +```shell +npm install @eslint/js -D +# or +yarn add @eslint/js -D +# or +pnpm install @eslint/js -D +# or +bun add @eslint/js -D +``` + +## Usage + +Use in your `eslint.config.js` file anytime you want to extend one of the configs: + +```js +import { defineConfig } from "eslint/config"; +import js from "@eslint/js"; + +export default defineConfig([ + // apply recommended rules to JS files + { + name: "your-project/recommended-rules", + files: ["**/*.js"], + plugins: { + js, + }, + extends: ["js/recommended"], + }, + + // apply recommended rules to JS files with an override + { + name: "your-project/recommended-rules-with-override", + files: ["**/*.js"], + plugins: { + js, + }, + extends: ["js/recommended"], + rules: { + "no-unused-vars": "warn", + }, + }, + + // apply all rules to JS files + { + name: "your-project/all-rules", + files: ["**/*.js"], + plugins: { + js, + }, + extends: ["js/all"], + rules: { + "no-unused-vars": "warn", + }, + }, +]); +``` + +## License + +MIT diff --git a/tools/ui/node_modules/eslint/node_modules/@eslint/js/package.json b/tools/ui/node_modules/eslint/node_modules/@eslint/js/package.json new file mode 100644 index 0000000000000000000000000000000000000000..243f06fd02e6fb081100a6e3b45c6d0771fd38cd --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/@eslint/js/package.json @@ -0,0 +1,36 @@ +{ + "name": "@eslint/js", + "version": "9.39.4", + "description": "ESLint JavaScript language implementation", + "funding": "https://eslint.org/donate", + "main": "./src/index.js", + "types": "./types/index.d.ts", + "scripts": { + "test:types": "tsc -p tests/types/tsconfig.json" + }, + "files": [ + "LICENSE", + "README.md", + "src", + "types" + ], + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "https://github.com/eslint/eslint.git", + "directory": "packages/js" + }, + "homepage": "https://eslint.org", + "bugs": "https://github.com/eslint/eslint/issues/", + "keywords": [ + "javascript", + "eslint-plugin", + "eslint" + ], + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } +} diff --git a/tools/ui/node_modules/eslint/node_modules/@eslint/js/src/configs/eslint-all.js b/tools/ui/node_modules/eslint/node_modules/@eslint/js/src/configs/eslint-all.js new file mode 100644 index 0000000000000000000000000000000000000000..248950d985e24f105c50f8d59fc7959371a5309a --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/@eslint/js/src/configs/eslint-all.js @@ -0,0 +1,217 @@ +/* + * WARNING: This file is autogenerated using the tools/update-eslint-all.js + * script. Do not edit manually. + */ +"use strict"; + +/* + * IMPORTANT! + * + * We cannot add a "name" property to this object because it's still used in eslintrc + * which doesn't support the "name" property. If we add a "name" property, it will + * cause an error. + */ + +module.exports = Object.freeze({ + rules: Object.freeze({ + "accessor-pairs": "error", + "array-callback-return": "error", + "arrow-body-style": "error", + "block-scoped-var": "error", + "camelcase": "error", + "capitalized-comments": "error", + "class-methods-use-this": "error", + "complexity": "error", + "consistent-return": "error", + "consistent-this": "error", + "constructor-super": "error", + "curly": "error", + "default-case": "error", + "default-case-last": "error", + "default-param-last": "error", + "dot-notation": "error", + "eqeqeq": "error", + "for-direction": "error", + "func-name-matching": "error", + "func-names": "error", + "func-style": "error", + "getter-return": "error", + "grouped-accessor-pairs": "error", + "guard-for-in": "error", + "id-denylist": "error", + "id-length": "error", + "id-match": "error", + "init-declarations": "error", + "logical-assignment-operators": "error", + "max-classes-per-file": "error", + "max-depth": "error", + "max-lines": "error", + "max-lines-per-function": "error", + "max-nested-callbacks": "error", + "max-params": "error", + "max-statements": "error", + "new-cap": "error", + "no-alert": "error", + "no-array-constructor": "error", + "no-async-promise-executor": "error", + "no-await-in-loop": "error", + "no-bitwise": "error", + "no-caller": "error", + "no-case-declarations": "error", + "no-class-assign": "error", + "no-compare-neg-zero": "error", + "no-cond-assign": "error", + "no-console": "error", + "no-const-assign": "error", + "no-constant-binary-expression": "error", + "no-constant-condition": "error", + "no-constructor-return": "error", + "no-continue": "error", + "no-control-regex": "error", + "no-debugger": "error", + "no-delete-var": "error", + "no-div-regex": "error", + "no-dupe-args": "error", + "no-dupe-class-members": "error", + "no-dupe-else-if": "error", + "no-dupe-keys": "error", + "no-duplicate-case": "error", + "no-duplicate-imports": "error", + "no-else-return": "error", + "no-empty": "error", + "no-empty-character-class": "error", + "no-empty-function": "error", + "no-empty-pattern": "error", + "no-empty-static-block": "error", + "no-eq-null": "error", + "no-eval": "error", + "no-ex-assign": "error", + "no-extend-native": "error", + "no-extra-bind": "error", + "no-extra-boolean-cast": "error", + "no-extra-label": "error", + "no-fallthrough": "error", + "no-func-assign": "error", + "no-global-assign": "error", + "no-implicit-coercion": "error", + "no-implicit-globals": "error", + "no-implied-eval": "error", + "no-import-assign": "error", + "no-inline-comments": "error", + "no-inner-declarations": "error", + "no-invalid-regexp": "error", + "no-invalid-this": "error", + "no-irregular-whitespace": "error", + "no-iterator": "error", + "no-label-var": "error", + "no-labels": "error", + "no-lone-blocks": "error", + "no-lonely-if": "error", + "no-loop-func": "error", + "no-loss-of-precision": "error", + "no-magic-numbers": "error", + "no-misleading-character-class": "error", + "no-multi-assign": "error", + "no-multi-str": "error", + "no-negated-condition": "error", + "no-nested-ternary": "error", + "no-new": "error", + "no-new-func": "error", + "no-new-native-nonconstructor": "error", + "no-new-wrappers": "error", + "no-nonoctal-decimal-escape": "error", + "no-obj-calls": "error", + "no-object-constructor": "error", + "no-octal": "error", + "no-octal-escape": "error", + "no-param-reassign": "error", + "no-plusplus": "error", + "no-promise-executor-return": "error", + "no-proto": "error", + "no-prototype-builtins": "error", + "no-redeclare": "error", + "no-regex-spaces": "error", + "no-restricted-exports": "error", + "no-restricted-globals": "error", + "no-restricted-imports": "error", + "no-restricted-properties": "error", + "no-restricted-syntax": "error", + "no-return-assign": "error", + "no-script-url": "error", + "no-self-assign": "error", + "no-self-compare": "error", + "no-sequences": "error", + "no-setter-return": "error", + "no-shadow": "error", + "no-shadow-restricted-names": "error", + "no-sparse-arrays": "error", + "no-template-curly-in-string": "error", + "no-ternary": "error", + "no-this-before-super": "error", + "no-throw-literal": "error", + "no-unassigned-vars": "error", + "no-undef": "error", + "no-undef-init": "error", + "no-undefined": "error", + "no-underscore-dangle": "error", + "no-unexpected-multiline": "error", + "no-unmodified-loop-condition": "error", + "no-unneeded-ternary": "error", + "no-unreachable": "error", + "no-unreachable-loop": "error", + "no-unsafe-finally": "error", + "no-unsafe-negation": "error", + "no-unsafe-optional-chaining": "error", + "no-unused-expressions": "error", + "no-unused-labels": "error", + "no-unused-private-class-members": "error", + "no-unused-vars": "error", + "no-use-before-define": "error", + "no-useless-assignment": "error", + "no-useless-backreference": "error", + "no-useless-call": "error", + "no-useless-catch": "error", + "no-useless-computed-key": "error", + "no-useless-concat": "error", + "no-useless-constructor": "error", + "no-useless-escape": "error", + "no-useless-rename": "error", + "no-useless-return": "error", + "no-var": "error", + "no-void": "error", + "no-warning-comments": "error", + "no-with": "error", + "object-shorthand": "error", + "one-var": "error", + "operator-assignment": "error", + "prefer-arrow-callback": "error", + "prefer-const": "error", + "prefer-destructuring": "error", + "prefer-exponentiation-operator": "error", + "prefer-named-capture-group": "error", + "prefer-numeric-literals": "error", + "prefer-object-has-own": "error", + "prefer-object-spread": "error", + "prefer-promise-reject-errors": "error", + "prefer-regex-literals": "error", + "prefer-rest-params": "error", + "prefer-spread": "error", + "prefer-template": "error", + "preserve-caught-error": "error", + "radix": "error", + "require-atomic-updates": "error", + "require-await": "error", + "require-unicode-regexp": "error", + "require-yield": "error", + "sort-imports": "error", + "sort-keys": "error", + "sort-vars": "error", + "strict": "error", + "symbol-description": "error", + "unicode-bom": "error", + "use-isnan": "error", + "valid-typeof": "error", + "vars-on-top": "error", + "yoda": "error" + }) +}); diff --git a/tools/ui/node_modules/eslint/node_modules/@eslint/js/src/configs/eslint-recommended.js b/tools/ui/node_modules/eslint/node_modules/@eslint/js/src/configs/eslint-recommended.js new file mode 100644 index 0000000000000000000000000000000000000000..9ff6a398f7389e27d2f6dbf848691a0697b60cec --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/@eslint/js/src/configs/eslint-recommended.js @@ -0,0 +1,79 @@ +/* + * WARNING: This file is autogenerated using the tools/update-eslint-recommended.js + * script. Do not edit manually. + */ +"use strict"; + +/* + * IMPORTANT! + * + * We cannot add a "name" property to this object because it's still used in eslintrc + * which doesn't support the "name" property. If we add a "name" property, it will + * cause an error. + */ + +module.exports = Object.freeze({ + rules: Object.freeze({ + "constructor-super": "error", + "for-direction": "error", + "getter-return": "error", + "no-async-promise-executor": "error", + "no-case-declarations": "error", + "no-class-assign": "error", + "no-compare-neg-zero": "error", + "no-cond-assign": "error", + "no-const-assign": "error", + "no-constant-binary-expression": "error", + "no-constant-condition": "error", + "no-control-regex": "error", + "no-debugger": "error", + "no-delete-var": "error", + "no-dupe-args": "error", + "no-dupe-class-members": "error", + "no-dupe-else-if": "error", + "no-dupe-keys": "error", + "no-duplicate-case": "error", + "no-empty": "error", + "no-empty-character-class": "error", + "no-empty-pattern": "error", + "no-empty-static-block": "error", + "no-ex-assign": "error", + "no-extra-boolean-cast": "error", + "no-fallthrough": "error", + "no-func-assign": "error", + "no-global-assign": "error", + "no-import-assign": "error", + "no-invalid-regexp": "error", + "no-irregular-whitespace": "error", + "no-loss-of-precision": "error", + "no-misleading-character-class": "error", + "no-new-native-nonconstructor": "error", + "no-nonoctal-decimal-escape": "error", + "no-obj-calls": "error", + "no-octal": "error", + "no-prototype-builtins": "error", + "no-redeclare": "error", + "no-regex-spaces": "error", + "no-self-assign": "error", + "no-setter-return": "error", + "no-shadow-restricted-names": "error", + "no-sparse-arrays": "error", + "no-this-before-super": "error", + "no-undef": "error", + "no-unexpected-multiline": "error", + "no-unreachable": "error", + "no-unsafe-finally": "error", + "no-unsafe-negation": "error", + "no-unsafe-optional-chaining": "error", + "no-unused-labels": "error", + "no-unused-private-class-members": "error", + "no-unused-vars": "error", + "no-useless-backreference": "error", + "no-useless-catch": "error", + "no-useless-escape": "error", + "no-with": "error", + "require-yield": "error", + "use-isnan": "error", + "valid-typeof": "error" + }), +}); diff --git a/tools/ui/node_modules/eslint/node_modules/@eslint/js/src/index.js b/tools/ui/node_modules/eslint/node_modules/@eslint/js/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ff6a21d8756426f0b21e79e05a09b795edfa8bc4 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/@eslint/js/src/index.js @@ -0,0 +1,23 @@ +/** + * @fileoverview Main package entrypoint. + * @author Nicholas C. Zakas + */ + +"use strict"; + +const { name, version } = require("../package.json"); + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + meta: { + name, + version, + }, + configs: { + all: require("./configs/eslint-all"), + recommended: require("./configs/eslint-recommended"), + }, +}; diff --git a/tools/ui/node_modules/eslint/node_modules/@eslint/js/types/index.d.ts b/tools/ui/node_modules/eslint/node_modules/@eslint/js/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d4921d8bfbfd66e585017ba7c51db3c8cbd6f952 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/@eslint/js/types/index.d.ts @@ -0,0 +1,14 @@ +import type { Linter } from "eslint"; + +declare const js: { + readonly meta: { + readonly name: string; + readonly version: string; + }; + readonly configs: { + readonly recommended: { readonly rules: Readonly }; + readonly all: { readonly rules: Readonly }; + }; +}; + +export = js; diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/.tonic_example.js b/tools/ui/node_modules/eslint/node_modules/ajv/.tonic_example.js new file mode 100644 index 0000000000000000000000000000000000000000..aa11812d87bbcf4d5110d0ee080d6185d94543a7 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/.tonic_example.js @@ -0,0 +1,20 @@ +var Ajv = require('ajv'); +var ajv = new Ajv({allErrors: true}); + +var schema = { + "properties": { + "foo": { "type": "string" }, + "bar": { "type": "number", "maximum": 3 } + } +}; + +var validate = ajv.compile(schema); + +test({"foo": "abc", "bar": 2}); +test({"foo": 2, "bar": 4}); + +function test(data) { + var valid = validate(data); + if (valid) console.log('Valid!'); + else console.log('Invalid: ' + ajv.errorsText(validate.errors)); +} \ No newline at end of file diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/LICENSE b/tools/ui/node_modules/eslint/node_modules/ajv/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..96ee719987f77868e3b3fe390f0c0c192acb5e9f --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015-2017 Evgeny Poberezkin + +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/tools/ui/node_modules/eslint/node_modules/ajv/README.md b/tools/ui/node_modules/eslint/node_modules/ajv/README.md new file mode 100644 index 0000000000000000000000000000000000000000..65077a0b3197e2c4fdc60c9f4cd81fb261287a1d --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/README.md @@ -0,0 +1,1505 @@ +Ajv logo + +# Ajv: Another JSON Schema Validator + +The fastest JSON Schema validator for Node.js and browser. Supports draft-04/06/07. + +[![Build Status](https://travis-ci.org/ajv-validator/ajv.svg?branch=master)](https://travis-ci.org/ajv-validator/ajv) +[![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv) +[![npm (beta)](https://img.shields.io/npm/v/ajv/beta)](https://www.npmjs.com/package/ajv/v/7.0.0-beta.4) +[![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) +[![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master) +[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) +[![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin) + + +## Ajv v7 beta is released + +[Ajv version 7 (beta)](https://github.com/ajv-validator/ajv/tree/v7-beta) is released with these changes: + +- support of JSON Schema draft-2019-09 features: [`unevaluatedProperties`](./json-schema.md#unevaluatedproperties) and [`unevaluatedItems`](./json-schema.md#unevaluateditems), [dynamic recursive references](./validation.md#extending-recursive-schemas) and other [additional keywords](./json-schema.md#json-schema-draft-2019-09). +- to reduce the mistakes in JSON schemas and unexpected validation results, [strict mode](./docs/strict-mode.md) is added - it prohibits ignored or ambiguous JSON Schema elements. +- to make code injection from untrusted schemas impossible, [code generation](./docs/codegen.md) is fully re-written to be safe and to allow code optimization (compiled schema code size is reduced by more than 10%). +- to simplify Ajv extensions, the new keyword API that is used by pre-defined keywords is available to user-defined keywords - it is much easier to define any keywords now, especially with subschemas. [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package was updated to use the new API (in [v4.0.0-beta.0](https://github.com/ajv-validator/ajv-keywords/releases/tag/v4.0.0-beta.0)) +- schemas are compiled to ES6 code (ES5 code generation is also supported with an option). +- to improve reliability and maintainability the code is migrated to TypeScript. + +**Please note**: + +- the support for JSON-Schema draft-04 is removed - if you have schemas using "id" attributes you have to replace them with "\$id" (or continue using version 6 that will be supported until 02/28/2021). +- all formats are separated to ajv-formats package - they have to be explicitely added if you use them. + +See [release notes](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0-beta.0) for the details. + +To install the new version: + +```bash +npm install ajv@beta +``` + +See [Getting started with v7](https://github.com/ajv-validator/ajv/tree/v7-beta#usage) for code example. + + +## Mozilla MOSS grant and OpenJS Foundation + +[](https://www.mozilla.org/en-US/moss/)     [](https://openjsf.org/blog/2020/08/14/ajv-joins-openjs-foundation-as-an-incubation-project/) + +Ajv has been awarded a grant from Mozilla’s [Open Source Support (MOSS) program](https://www.mozilla.org/en-US/moss/) in the “Foundational Technology” track! It will sponsor the development of Ajv support of [JSON Schema version 2019-09](https://tools.ietf.org/html/draft-handrews-json-schema-02) and of [JSON Type Definition](https://tools.ietf.org/html/draft-ucarion-json-type-definition-04). + +Ajv also joined [OpenJS Foundation](https://openjsf.org/) – having this support will help ensure the longevity and stability of Ajv for all its users. + +This [blog post](https://www.poberezkin.com/posts/2020-08-14-ajv-json-validator-mozilla-open-source-grant-openjs-foundation.html) has more details. + +I am looking for the long term maintainers of Ajv – working with [ReadySet](https://www.thereadyset.co/), also sponsored by Mozilla, to establish clear guidelines for the role of a "maintainer" and the contribution standards, and to encourage a wider, more inclusive, contribution from the community. + + +## Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin) + +Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant! + +Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released. + +Please sponsor Ajv via: +- [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it) +- [Ajv Open Collective️](https://opencollective.com/ajv) + +Thank you. + + +#### Open Collective sponsors + + + + + + + + + + + + + + + +## Using version 6 + +[JSON Schema draft-07](http://json-schema.org/latest/json-schema-validation.html) is published. + +[Ajv version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0) that supports draft-07 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas, draft-06 schemas will be supported without changes). + +__Please note__: To use Ajv with draft-06 schemas you need to explicitly add the meta-schema to the validator instance: + +```javascript +ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json')); +``` + +To use Ajv with draft-04 schemas in addition to explicitly adding meta-schema you also need to use option schemaId: + +```javascript +var ajv = new Ajv({schemaId: 'id'}); +// If you want to use both draft-04 and draft-06/07 schemas: +// var ajv = new Ajv({schemaId: 'auto'}); +ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json')); +``` + + +## Contents + +- [Performance](#performance) +- [Features](#features) +- [Getting started](#getting-started) +- [Frequently Asked Questions](https://github.com/ajv-validator/ajv/blob/master/FAQ.md) +- [Using in browser](#using-in-browser) + - [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp) +- [Command line interface](#command-line-interface) +- Validation + - [Keywords](#validation-keywords) + - [Annotation keywords](#annotation-keywords) + - [Formats](#formats) + - [Combining schemas with $ref](#ref) + - [$data reference](#data-reference) + - NEW: [$merge and $patch keywords](#merge-and-patch-keywords) + - [Defining custom keywords](#defining-custom-keywords) + - [Asynchronous schema compilation](#asynchronous-schema-compilation) + - [Asynchronous validation](#asynchronous-validation) +- [Security considerations](#security-considerations) + - [Security contact](#security-contact) + - [Untrusted schemas](#untrusted-schemas) + - [Circular references in objects](#circular-references-in-javascript-objects) + - [Trusted schemas](#security-risks-of-trusted-schemas) + - [ReDoS attack](#redos-attack) +- Modifying data during validation + - [Filtering data](#filtering-data) + - [Assigning defaults](#assigning-defaults) + - [Coercing data types](#coercing-data-types) +- API + - [Methods](#api) + - [Options](#options) + - [Validation errors](#validation-errors) +- [Plugins](#plugins) +- [Related packages](#related-packages) +- [Some packages using Ajv](#some-packages-using-ajv) +- [Tests, Contributing, Changes history](#tests) +- [Support, Code of conduct, License](#open-source-software-support) + + +## Performance + +Ajv generates code using [doT templates](https://github.com/olado/doT) to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization. + +Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: + +- [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place +- [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster +- [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) +- [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) + + +Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark): + +[![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=32,4,1&chs=600x416&chxl=-1:|djv|ajv|json-schema-validator-generator|jsen|is-my-json-valid|themis|z-schema|jsck|skeemas|json-schema-library|tv4&chd=t:100,98,72.1,66.8,50.1,15.1,6.1,3.8,1.2,0.7,0.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance) + + +## Features + +- Ajv implements full JSON Schema [draft-06/07](http://json-schema.org/) and draft-04 standards: + - all validation keywords (see [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md)) + - full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available) + - support of circular references between schemas + - correct string lengths for strings with unicode pairs (can be turned off) + - [formats](#formats) defined by JSON Schema draft-07 standard and custom formats (can be turned off) + - [validates schemas against meta-schema](#api-validateschema) +- supports [browsers](#using-in-browser) and Node.js 0.10-14.x +- [asynchronous loading](#asynchronous-schema-compilation) of referenced schemas during compilation +- "All errors" validation mode with [option allErrors](#options) +- [error messages with parameters](#validation-errors) describing error reasons to allow creating custom error messages +- i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package +- [filtering data](#filtering-data) from additional properties +- [assigning defaults](#assigning-defaults) to missing properties and items +- [coercing data](#coercing-data-types) to the types specified in `type` keywords +- [custom keywords](#defining-custom-keywords) +- draft-06/07 keywords `const`, `contains`, `propertyNames` and `if/then/else` +- draft-06 boolean schemas (`true`/`false` as a schema to always pass/fail). +- keywords `switch`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package +- [$data reference](#data-reference) to use values from the validated data as values for the schema keywords +- [asynchronous validation](#asynchronous-validation) of custom formats and keywords + + +## Install + +``` +npm install ajv +``` + + +## Getting started + +Try it in the Node.js REPL: https://tonicdev.com/npm/ajv + + +The fastest validation call: + +```javascript +// Node.js require: +var Ajv = require('ajv'); +// or ESM/TypeScript import +import Ajv from 'ajv'; + +var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true} +var validate = ajv.compile(schema); +var valid = validate(data); +if (!valid) console.log(validate.errors); +``` + +or with less code + +```javascript +// ... +var valid = ajv.validate(schema, data); +if (!valid) console.log(ajv.errors); +// ... +``` + +or + +```javascript +// ... +var valid = ajv.addSchema(schema, 'mySchema') + .validate('mySchema', data); +if (!valid) console.log(ajv.errorsText()); +// ... +``` + +See [API](#api) and [Options](#options) for more details. + +Ajv compiles schemas to functions and caches them in all cases (using schema serialized with [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) or a custom function as a key), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again. + +The best performance is achieved when using compiled functions returned by `compile` or `getSchema` methods (there is no additional function call). + +__Please note__: every time a validation function or `ajv.validate` are called `errors` property is overwritten. You need to copy `errors` array reference to another variable if you want to use it later (e.g., in the callback). See [Validation errors](#validation-errors) + +__Note for TypeScript users__: `ajv` provides its own TypeScript declarations +out of the box, so you don't need to install the deprecated `@types/ajv` +module. + + +## Using in browser + +You can require Ajv directly from the code you browserify - in this case Ajv will be a part of your bundle. + +If you need to use Ajv in several bundles you can create a separate UMD bundle using `npm run bundle` script (thanks to [siddo420](https://github.com/siddo420)). + +Then you need to load Ajv in the browser: +```html + +``` + +This bundle can be used with different module systems; it creates global `Ajv` if no module system is found. + +The browser bundle is available on [cdnjs](https://cdnjs.com/libraries/ajv). + +Ajv is tested with these browsers: + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/epoberezkin.svg)](https://saucelabs.com/u/epoberezkin) + +__Please note__: some frameworks, e.g. Dojo, may redefine global require in such way that is not compatible with CommonJS module format. In such case Ajv bundle has to be loaded before the framework and then you can use global Ajv (see issue [#234](https://github.com/ajv-validator/ajv/issues/234)). + + +### Ajv and Content Security Policies (CSP) + +If you're using Ajv to compile a schema (the typical use) in a browser document that is loaded with a Content Security Policy (CSP), that policy will require a `script-src` directive that includes the value `'unsafe-eval'`. +:warning: NOTE, however, that `unsafe-eval` is NOT recommended in a secure CSP[[1]](https://developer.chrome.com/extensions/contentSecurityPolicy#relaxing-eval), as it has the potential to open the document to cross-site scripting (XSS) attacks. + +In order to make use of Ajv without easing your CSP, you can [pre-compile a schema using the CLI](https://github.com/ajv-validator/ajv-cli#compile-schemas). This will transpile the schema JSON into a JavaScript file that exports a `validate` function that works simlarly to a schema compiled at runtime. + +Note that pre-compilation of schemas is performed using [ajv-pack](https://github.com/ajv-validator/ajv-pack) and there are [some limitations to the schema features it can compile](https://github.com/ajv-validator/ajv-pack#limitations). A successfully pre-compiled schema is equivalent to the same schema compiled at runtime. + + +## Command line interface + +CLI is available as a separate npm package [ajv-cli](https://github.com/ajv-validator/ajv-cli). It supports: + +- compiling JSON Schemas to test their validity +- BETA: generating standalone module exporting a validation function to be used without Ajv (using [ajv-pack](https://github.com/ajv-validator/ajv-pack)) +- migrate schemas to draft-07 (using [json-schema-migrate](https://github.com/epoberezkin/json-schema-migrate)) +- validating data file(s) against JSON Schema +- testing expected validity of data against JSON Schema +- referenced schemas +- custom meta-schemas +- files in JSON, JSON5, YAML, and JavaScript format +- all Ajv options +- reporting changes in data after validation in [JSON-patch](https://tools.ietf.org/html/rfc6902) format + + +## Validation keywords + +Ajv supports all validation keywords from draft-07 of JSON Schema standard: + +- [type](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#type) +- [for numbers](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf +- [for strings](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-strings) - maxLength, minLength, pattern, format +- [for arrays](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-arrays) - maxItems, minItems, uniqueItems, items, additionalItems, [contains](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#contains) +- [for objects](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minProperties, required, properties, patternProperties, additionalProperties, dependencies, [propertyNames](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#propertynames) +- [for all types](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, [const](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#const) +- [compound keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf, [if/then/else](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#ifthenelse) + +With [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package Ajv also supports validation keywords from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON Schema standard: + +- [patternRequired](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#patternrequired-proposed) - like `required` but with patterns that some property should match. +- [formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#formatmaximum--formatminimum-and-exclusiveformatmaximum--exclusiveformatminimum-proposed) - setting limits for date, time, etc. + +See [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md) for more details. + + +## Annotation keywords + +JSON Schema specification defines several annotation keywords that describe schema itself but do not perform any validation. + +- `title` and `description`: information about the data represented by that schema +- `$comment` (NEW in draft-07): information for developers. With option `$comment` Ajv logs or passes the comment string to the user-supplied function. See [Options](#options). +- `default`: a default value of the data instance, see [Assigning defaults](#assigning-defaults). +- `examples` (NEW in draft-06): an array of data instances. Ajv does not check the validity of these instances against the schema. +- `readOnly` and `writeOnly` (NEW in draft-07): marks data-instance as read-only or write-only in relation to the source of the data (database, api, etc.). +- `contentEncoding`: [RFC 2045](https://tools.ietf.org/html/rfc2045#section-6.1 ), e.g., "base64". +- `contentMediaType`: [RFC 2046](https://tools.ietf.org/html/rfc2046), e.g., "image/png". + +__Please note__: Ajv does not implement validation of the keywords `examples`, `contentEncoding` and `contentMediaType` but it reserves them. If you want to create a plugin that implements some of them, it should remove these keywords from the instance. + + +## Formats + +Ajv implements formats defined by JSON Schema specification and several other formats. It is recommended NOT to use "format" keyword implementations with untrusted data, as they use potentially unsafe regular expressions - see [ReDoS attack](#redos-attack). + +__Please note__: if you need to use "format" keyword to validate untrusted data, you MUST assess their suitability and safety for your validation scenarios. + +The following formats are implemented for string validation with "format" keyword: + +- _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6). +- _time_: time with optional time-zone. +- _date-time_: date-time from the same source (time-zone is mandatory). `date`, `time` and `date-time` validate ranges in `full` mode and only regexp in `fast` mode (see [options](#options)). +- _uri_: full URI. +- _uri-reference_: URI reference, including full and relative URIs. +- _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570) +- _url_ (deprecated): [URL record](https://url.spec.whatwg.org/#concept-url). +- _email_: email address. +- _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5). +- _ipv4_: IP address v4. +- _ipv6_: IP address v6. +- _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor. +- _uuid_: Universally Unique IDentifier according to [RFC4122](http://tools.ietf.org/html/rfc4122). +- _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901). +- _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00). + +__Please note__: JSON Schema draft-07 also defines formats `iri`, `iri-reference`, `idn-hostname` and `idn-email` for URLs, hostnames and emails with international characters. Ajv does not implement these formats. If you create Ajv plugin that implements them please make a PR to mention this plugin here. + +There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `uri-reference`, and `email`. See [Options](#options) for details. + +You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method. + +The option `unknownFormats` allows changing the default behaviour when an unknown format is encountered. In this case Ajv can either fail schema compilation (default) or ignore it (default in versions before 5.0.0). You also can allow specific format(s) that will be ignored. See [Options](#options) for details. + +You can find regular expressions used for format validation and the sources that were used in [formats.js](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js). + + +## Combining schemas with $ref + +You can structure your validation logic across multiple schema files and have schemas reference each other using `$ref` keyword. + +Example: + +```javascript +var schema = { + "$id": "http://example.com/schemas/schema.json", + "type": "object", + "properties": { + "foo": { "$ref": "defs.json#/definitions/int" }, + "bar": { "$ref": "defs.json#/definitions/str" } + } +}; + +var defsSchema = { + "$id": "http://example.com/schemas/defs.json", + "definitions": { + "int": { "type": "integer" }, + "str": { "type": "string" } + } +}; +``` + +Now to compile your schema you can either pass all schemas to Ajv instance: + +```javascript +var ajv = new Ajv({schemas: [schema, defsSchema]}); +var validate = ajv.getSchema('http://example.com/schemas/schema.json'); +``` + +or use `addSchema` method: + +```javascript +var ajv = new Ajv; +var validate = ajv.addSchema(defsSchema) + .compile(schema); +``` + +See [Options](#options) and [addSchema](#api) method. + +__Please note__: +- `$ref` is resolved as the uri-reference using schema $id as the base URI (see the example). +- References can be recursive (and mutually recursive) to implement the schemas for different data structures (such as linked lists, trees, graphs, etc.). +- You don't have to host your schema files at the URIs that you use as schema $id. These URIs are only used to identify the schemas, and according to JSON Schema specification validators should not expect to be able to download the schemas from these URIs. +- The actual location of the schema file in the file system is not used. +- You can pass the identifier of the schema as the second parameter of `addSchema` method or as a property name in `schemas` option. This identifier can be used instead of (or in addition to) schema $id. +- You cannot have the same $id (or the schema identifier) used for more than one schema - the exception will be thrown. +- You can implement dynamic resolution of the referenced schemas using `compileAsync` method. In this way you can store schemas in any system (files, web, database, etc.) and reference them without explicitly adding to Ajv instance. See [Asynchronous schema compilation](#asynchronous-schema-compilation). + + +## $data reference + +With `$data` option you can use values from the validated data as the values for the schema keywords. See [proposal](https://github.com/json-schema-org/json-schema-spec/issues/51) for more information about how it works. + +`$data` reference is supported in the keywords: const, enum, format, maximum/minimum, exclusiveMaximum / exclusiveMinimum, maxLength / minLength, maxItems / minItems, maxProperties / minProperties, formatMaximum / formatMinimum, formatExclusiveMaximum / formatExclusiveMinimum, multipleOf, pattern, required, uniqueItems. + +The value of "$data" should be a [JSON-pointer](https://tools.ietf.org/html/rfc6901) to the data (the root is always the top level data object, even if the $data reference is inside a referenced subschema) or a [relative JSON-pointer](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00) (it is relative to the current point in data; if the $data reference is inside a referenced subschema it cannot point to the data outside of the root level for this subschema). + +Examples. + +This schema requires that the value in property `smaller` is less or equal than the value in the property larger: + +```javascript +var ajv = new Ajv({$data: true}); + +var schema = { + "properties": { + "smaller": { + "type": "number", + "maximum": { "$data": "1/larger" } + }, + "larger": { "type": "number" } + } +}; + +var validData = { + smaller: 5, + larger: 7 +}; + +ajv.validate(schema, validData); // true +``` + +This schema requires that the properties have the same format as their field names: + +```javascript +var schema = { + "additionalProperties": { + "type": "string", + "format": { "$data": "0#" } + } +}; + +var validData = { + 'date-time': '1963-06-19T08:30:06.283185Z', + email: 'joe.bloggs@example.com' +} +``` + +`$data` reference is resolved safely - it won't throw even if some property is undefined. If `$data` resolves to `undefined` the validation succeeds (with the exclusion of `const` keyword). If `$data` resolves to incorrect type (e.g. not "number" for maximum keyword) the validation fails. + + +## $merge and $patch keywords + +With the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) you can use the keywords `$merge` and `$patch` that allow extending JSON Schemas with patches using formats [JSON Merge Patch (RFC 7396)](https://tools.ietf.org/html/rfc7396) and [JSON Patch (RFC 6902)](https://tools.ietf.org/html/rfc6902). + +To add keywords `$merge` and `$patch` to Ajv instance use this code: + +```javascript +require('ajv-merge-patch')(ajv); +``` + +Examples. + +Using `$merge`: + +```json +{ + "$merge": { + "source": { + "type": "object", + "properties": { "p": { "type": "string" } }, + "additionalProperties": false + }, + "with": { + "properties": { "q": { "type": "number" } } + } + } +} +``` + +Using `$patch`: + +```json +{ + "$patch": { + "source": { + "type": "object", + "properties": { "p": { "type": "string" } }, + "additionalProperties": false + }, + "with": [ + { "op": "add", "path": "/properties/q", "value": { "type": "number" } } + ] + } +} +``` + +The schemas above are equivalent to this schema: + +```json +{ + "type": "object", + "properties": { + "p": { "type": "string" }, + "q": { "type": "number" } + }, + "additionalProperties": false +} +``` + +The properties `source` and `with` in the keywords `$merge` and `$patch` can use absolute or relative `$ref` to point to other schemas previously added to the Ajv instance or to the fragments of the current schema. + +See the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) for more information. + + +## Defining custom keywords + +The advantages of using custom keywords are: + +- allow creating validation scenarios that cannot be expressed using JSON Schema +- simplify your schemas +- help bringing a bigger part of the validation logic to your schemas +- make your schemas more expressive, less verbose and closer to your application domain +- implement custom data processors that modify your data (`modifying` option MUST be used in keyword definition) and/or create side effects while the data is being validated + +If a keyword is used only for side-effects and its validation result is pre-defined, use option `valid: true/false` in keyword definition to simplify both generated code (no error handling in case of `valid: true`) and your keyword functions (no need to return any validation result). + +The concerns you have to be aware of when extending JSON Schema standard with custom keywords are the portability and understanding of your schemas. You will have to support these custom keywords on other platforms and to properly document these keywords so that everybody can understand them in your schemas. + +You can define custom keywords with [addKeyword](#api-addkeyword) method. Keywords are defined on the `ajv` instance level - new instances will not have previously defined keywords. + +Ajv allows defining keywords with: +- validation function +- compilation function +- macro function +- inline compilation function that should return code (as string) that will be inlined in the currently compiled schema. + +Example. `range` and `exclusiveRange` keywords using compiled schema: + +```javascript +ajv.addKeyword('range', { + type: 'number', + compile: function (sch, parentSchema) { + var min = sch[0]; + var max = sch[1]; + + return parentSchema.exclusiveRange === true + ? function (data) { return data > min && data < max; } + : function (data) { return data >= min && data <= max; } + } +}); + +var schema = { "range": [2, 4], "exclusiveRange": true }; +var validate = ajv.compile(schema); +console.log(validate(2.01)); // true +console.log(validate(3.99)); // true +console.log(validate(2)); // false +console.log(validate(4)); // false +``` + +Several custom keywords (typeof, instanceof, range and propertyNames) are defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - they can be used for your schemas and as a starting point for your own custom keywords. + +See [Defining custom keywords](https://github.com/ajv-validator/ajv/blob/master/CUSTOM.md) for more details. + + +## Asynchronous schema compilation + +During asynchronous compilation remote references are loaded using supplied function. See `compileAsync` [method](#api-compileAsync) and `loadSchema` [option](#options). + +Example: + +```javascript +var ajv = new Ajv({ loadSchema: loadSchema }); + +ajv.compileAsync(schema).then(function (validate) { + var valid = validate(data); + // ... +}); + +function loadSchema(uri) { + return request.json(uri).then(function (res) { + if (res.statusCode >= 400) + throw new Error('Loading error: ' + res.statusCode); + return res.body; + }); +} +``` + +__Please note__: [Option](#options) `missingRefs` should NOT be set to `"ignore"` or `"fail"` for asynchronous compilation to work. + + +## Asynchronous validation + +Example in Node.js REPL: https://tonicdev.com/esp/ajv-asynchronous-validation + +You can define custom formats and keywords that perform validation asynchronously by accessing database or some other service. You should add `async: true` in the keyword or format definition (see [addFormat](#api-addformat), [addKeyword](#api-addkeyword) and [Defining custom keywords](#defining-custom-keywords)). + +If your schema uses asynchronous formats/keywords or refers to some schema that contains them it should have `"$async": true` keyword so that Ajv can compile it correctly. If asynchronous format/keyword or reference to asynchronous schema is used in the schema without `$async` keyword Ajv will throw an exception during schema compilation. + +__Please note__: all asynchronous subschemas that are referenced from the current or other schemas should have `"$async": true` keyword as well, otherwise the schema compilation will fail. + +Validation function for an asynchronous custom format/keyword should return a promise that resolves with `true` or `false` (or rejects with `new Ajv.ValidationError(errors)` if you want to return custom errors from the keyword function). + +Ajv compiles asynchronous schemas to [es7 async functions](http://tc39.github.io/ecmascript-asyncawait/) that can optionally be transpiled with [nodent](https://github.com/MatAtBread/nodent). Async functions are supported in Node.js 7+ and all modern browsers. You can also supply any other transpiler as a function via `processCode` option. See [Options](#options). + +The compiled validation function has `$async: true` property (if the schema is asynchronous), so you can differentiate these functions if you are using both synchronous and asynchronous schemas. + +Validation result will be a promise that resolves with validated data or rejects with an exception `Ajv.ValidationError` that contains the array of validation errors in `errors` property. + + +Example: + +```javascript +var ajv = new Ajv; +// require('ajv-async')(ajv); + +ajv.addKeyword('idExists', { + async: true, + type: 'number', + validate: checkIdExists +}); + + +function checkIdExists(schema, data) { + return knex(schema.table) + .select('id') + .where('id', data) + .then(function (rows) { + return !!rows.length; // true if record is found + }); +} + +var schema = { + "$async": true, + "properties": { + "userId": { + "type": "integer", + "idExists": { "table": "users" } + }, + "postId": { + "type": "integer", + "idExists": { "table": "posts" } + } + } +}; + +var validate = ajv.compile(schema); + +validate({ userId: 1, postId: 19 }) +.then(function (data) { + console.log('Data is valid', data); // { userId: 1, postId: 19 } +}) +.catch(function (err) { + if (!(err instanceof Ajv.ValidationError)) throw err; + // data is invalid + console.log('Validation errors:', err.errors); +}); +``` + +### Using transpilers with asynchronous validation functions. + +[ajv-async](https://github.com/ajv-validator/ajv-async) uses [nodent](https://github.com/MatAtBread/nodent) to transpile async functions. To use another transpiler you should separately install it (or load its bundle in the browser). + + +#### Using nodent + +```javascript +var ajv = new Ajv; +require('ajv-async')(ajv); +// in the browser if you want to load ajv-async bundle separately you can: +// window.ajvAsync(ajv); +var validate = ajv.compile(schema); // transpiled es7 async function +validate(data).then(successFunc).catch(errorFunc); +``` + + +#### Using other transpilers + +```javascript +var ajv = new Ajv({ processCode: transpileFunc }); +var validate = ajv.compile(schema); // transpiled es7 async function +validate(data).then(successFunc).catch(errorFunc); +``` + +See [Options](#options). + + +## Security considerations + +JSON Schema, if properly used, can replace data sanitisation. It doesn't replace other API security considerations. It also introduces additional security aspects to consider. + + +##### Security contact + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues. + + +##### Untrusted schemas + +Ajv treats JSON schemas as trusted as your application code. This security model is based on the most common use case, when the schemas are static and bundled together with the application. + +If your schemas are received from untrusted sources (or generated from untrusted data) there are several scenarios you need to prevent: +- compiling schemas can cause stack overflow (if they are too deep) +- compiling schemas can be slow (e.g. [#557](https://github.com/ajv-validator/ajv/issues/557)) +- validating certain data can be slow + +It is difficult to predict all the scenarios, but at the very least it may help to limit the size of untrusted schemas (e.g. limit JSON string length) and also the maximum schema object depth (that can be high for relatively small JSON strings). You also may want to mitigate slow regular expressions in `pattern` and `patternProperties` keywords. + +Regardless the measures you take, using untrusted schemas increases security risks. + + +##### Circular references in JavaScript objects + +Ajv does not support schemas and validated data that have circular references in objects. See [issue #802](https://github.com/ajv-validator/ajv/issues/802). + +An attempt to compile such schemas or validate such data would cause stack overflow (or will not complete in case of asynchronous validation). Depending on the parser you use, untrusted data can lead to circular references. + + +##### Security risks of trusted schemas + +Some keywords in JSON Schemas can lead to very slow validation for certain data. These keywords include (but may be not limited to): + +- `pattern` and `format` for large strings - in some cases using `maxLength` can help mitigate it, but certain regular expressions can lead to exponential validation time even with relatively short strings (see [ReDoS attack](#redos-attack)). +- `patternProperties` for large property names - use `propertyNames` to mitigate, but some regular expressions can have exponential evaluation time as well. +- `uniqueItems` for large non-scalar arrays - use `maxItems` to mitigate + +__Please note__: The suggestions above to prevent slow validation would only work if you do NOT use `allErrors: true` in production code (using it would continue validation after validation errors). + +You can validate your JSON schemas against [this meta-schema](https://github.com/ajv-validator/ajv/blob/master/lib/refs/json-schema-secure.json) to check that these recommendations are followed: + +```javascript +const isSchemaSecure = ajv.compile(require('ajv/lib/refs/json-schema-secure.json')); + +const schema1 = {format: 'email'}; +isSchemaSecure(schema1); // false + +const schema2 = {format: 'email', maxLength: MAX_LENGTH}; +isSchemaSecure(schema2); // true +``` + +__Please note__: following all these recommendation is not a guarantee that validation of untrusted data is safe - it can still lead to some undesirable results. + + +##### Content Security Policies (CSP) +See [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp) + + +## ReDoS attack + +Certain regular expressions can lead to the exponential evaluation time even with relatively short strings. + +Please assess the regular expressions you use in the schemas on their vulnerability to this attack - see [safe-regex](https://github.com/substack/safe-regex), for example. + +__Please note__: some formats that Ajv implements use [regular expressions](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js) that can be vulnerable to ReDoS attack, so if you use Ajv to validate data from untrusted sources __it is strongly recommended__ to consider the following: + +- making assessment of "format" implementations in Ajv. +- using `format: 'fast'` option that simplifies some of the regular expressions (although it does not guarantee that they are safe). +- replacing format implementations provided by Ajv with your own implementations of "format" keyword that either uses different regular expressions or another approach to format validation. Please see [addFormat](#api-addformat) method. +- disabling format validation by ignoring "format" keyword with option `format: false` + +Whatever mitigation you choose, please assume all formats provided by Ajv as potentially unsafe and make your own assessment of their suitability for your validation scenarios. + + +## Filtering data + +With [option `removeAdditional`](#options) (added by [andyscott](https://github.com/andyscott)) you can filter data during the validation. + +This option modifies original data. + +Example: + +```javascript +var ajv = new Ajv({ removeAdditional: true }); +var schema = { + "additionalProperties": false, + "properties": { + "foo": { "type": "number" }, + "bar": { + "additionalProperties": { "type": "number" }, + "properties": { + "baz": { "type": "string" } + } + } + } +} + +var data = { + "foo": 0, + "additional1": 1, // will be removed; `additionalProperties` == false + "bar": { + "baz": "abc", + "additional2": 2 // will NOT be removed; `additionalProperties` != false + }, +} + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // { "foo": 0, "bar": { "baz": "abc", "additional2": 2 } +``` + +If `removeAdditional` option in the example above were `"all"` then both `additional1` and `additional2` properties would have been removed. + +If the option were `"failing"` then property `additional1` would have been removed regardless of its value and property `additional2` would have been removed only if its value were failing the schema in the inner `additionalProperties` (so in the example above it would have stayed because it passes the schema, but any non-number would have been removed). + +__Please note__: If you use `removeAdditional` option with `additionalProperties` keyword inside `anyOf`/`oneOf` keywords your validation can fail with this schema, for example: + +```json +{ + "type": "object", + "oneOf": [ + { + "properties": { + "foo": { "type": "string" } + }, + "required": [ "foo" ], + "additionalProperties": false + }, + { + "properties": { + "bar": { "type": "integer" } + }, + "required": [ "bar" ], + "additionalProperties": false + } + ] +} +``` + +The intention of the schema above is to allow objects with either the string property "foo" or the integer property "bar", but not with both and not with any other properties. + +With the option `removeAdditional: true` the validation will pass for the object `{ "foo": "abc"}` but will fail for the object `{"bar": 1}`. It happens because while the first subschema in `oneOf` is validated, the property `bar` is removed because it is an additional property according to the standard (because it is not included in `properties` keyword in the same schema). + +While this behaviour is unexpected (issues [#129](https://github.com/ajv-validator/ajv/issues/129), [#134](https://github.com/ajv-validator/ajv/issues/134)), it is correct. To have the expected behaviour (both objects are allowed and additional properties are removed) the schema has to be refactored in this way: + +```json +{ + "type": "object", + "properties": { + "foo": { "type": "string" }, + "bar": { "type": "integer" } + }, + "additionalProperties": false, + "oneOf": [ + { "required": [ "foo" ] }, + { "required": [ "bar" ] } + ] +} +``` + +The schema above is also more efficient - it will compile into a faster function. + + +## Assigning defaults + +With [option `useDefaults`](#options) Ajv will assign values from `default` keyword in the schemas of `properties` and `items` (when it is the array of schemas) to the missing properties and items. + +With the option value `"empty"` properties and items equal to `null` or `""` (empty string) will be considered missing and assigned defaults. + +This option modifies original data. + +__Please note__: the default value is inserted in the generated validation code as a literal, so the value inserted in the data will be the deep clone of the default in the schema. + + +Example 1 (`default` in `properties`): + +```javascript +var ajv = new Ajv({ useDefaults: true }); +var schema = { + "type": "object", + "properties": { + "foo": { "type": "number" }, + "bar": { "type": "string", "default": "baz" } + }, + "required": [ "foo", "bar" ] +}; + +var data = { "foo": 1 }; + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // { "foo": 1, "bar": "baz" } +``` + +Example 2 (`default` in `items`): + +```javascript +var schema = { + "type": "array", + "items": [ + { "type": "number" }, + { "type": "string", "default": "foo" } + ] +} + +var data = [ 1 ]; + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // [ 1, "foo" ] +``` + +`default` keywords in other cases are ignored: + +- not in `properties` or `items` subschemas +- in schemas inside `anyOf`, `oneOf` and `not` (see [#42](https://github.com/ajv-validator/ajv/issues/42)) +- in `if` subschema of `switch` keyword +- in schemas generated by custom macro keywords + +The [`strictDefaults` option](#options) customizes Ajv's behavior for the defaults that Ajv ignores (`true` raises an error, and `"log"` outputs a warning). + + +## Coercing data types + +When you are validating user inputs all your data properties are usually strings. The option `coerceTypes` allows you to have your data types coerced to the types specified in your schema `type` keywords, both to pass the validation and to use the correctly typed data afterwards. + +This option modifies original data. + +__Please note__: if you pass a scalar value to the validating function its type will be coerced and it will pass the validation, but the value of the variable you pass won't be updated because scalars are passed by value. + + +Example 1: + +```javascript +var ajv = new Ajv({ coerceTypes: true }); +var schema = { + "type": "object", + "properties": { + "foo": { "type": "number" }, + "bar": { "type": "boolean" } + }, + "required": [ "foo", "bar" ] +}; + +var data = { "foo": "1", "bar": "false" }; + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // { "foo": 1, "bar": false } +``` + +Example 2 (array coercions): + +```javascript +var ajv = new Ajv({ coerceTypes: 'array' }); +var schema = { + "properties": { + "foo": { "type": "array", "items": { "type": "number" } }, + "bar": { "type": "boolean" } + } +}; + +var data = { "foo": "1", "bar": ["false"] }; + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // { "foo": [1], "bar": false } +``` + +The coercion rules, as you can see from the example, are different from JavaScript both to validate user input as expected and to have the coercion reversible (to correctly validate cases where different types are defined in subschemas of "anyOf" and other compound keywords). + +See [Coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md) for details. + + +## API + +##### new Ajv(Object options) -> Object + +Create Ajv instance. + + +##### .compile(Object schema) -> Function<Object data> + +Generate validating function and cache the compiled schema for future use. + +Validating function returns a boolean value. This function has properties `errors` and `schema`. Errors encountered during the last validation are assigned to `errors` property (it is assigned `null` if there was no errors). `schema` property contains the reference to the original schema. + +The schema passed to this method will be validated against meta-schema unless `validateSchema` option is false. If schema is invalid, an error will be thrown. See [options](#options). + + +##### .compileAsync(Object schema [, Boolean meta] [, Function callback]) -> Promise + +Asynchronous version of `compile` method that loads missing remote schemas using asynchronous function in `options.loadSchema`. This function returns a Promise that resolves to a validation function. An optional callback passed to `compileAsync` will be called with 2 parameters: error (or null) and validating function. The returned promise will reject (and the callback will be called with an error) when: + +- missing schema can't be loaded (`loadSchema` returns a Promise that rejects). +- a schema containing a missing reference is loaded, but the reference cannot be resolved. +- schema (or some loaded/referenced schema) is invalid. + +The function compiles schema and loads the first missing schema (or meta-schema) until all missing schemas are loaded. + +You can asynchronously compile meta-schema by passing `true` as the second parameter. + +See example in [Asynchronous compilation](#asynchronous-schema-compilation). + + +##### .validate(Object schema|String key|String ref, data) -> Boolean + +Validate data using passed schema (it will be compiled and cached). + +Instead of the schema you can use the key that was previously passed to `addSchema`, the schema id if it was present in the schema or any previously resolved reference. + +Validation errors will be available in the `errors` property of Ajv instance (`null` if there were no errors). + +__Please note__: every time this method is called the errors are overwritten so you need to copy them to another variable if you want to use them later. + +If the schema is asynchronous (has `$async` keyword on the top level) this method returns a Promise. See [Asynchronous validation](#asynchronous-validation). + + +##### .addSchema(Array<Object>|Object schema [, String key]) -> Ajv + +Add schema(s) to validator instance. This method does not compile schemas (but it still validates them). Because of that dependencies can be added in any order and circular dependencies are supported. It also prevents unnecessary compilation of schemas that are containers for other schemas but not used as a whole. + +Array of schemas can be passed (schemas should have ids), the second parameter will be ignored. + +Key can be passed that can be used to reference the schema and will be used as the schema id if there is no id inside the schema. If the key is not passed, the schema id will be used as the key. + + +Once the schema is added, it (and all the references inside it) can be referenced in other schemas and used to validate data. + +Although `addSchema` does not compile schemas, explicit compilation is not required - the schema will be compiled when it is used first time. + +By default the schema is validated against meta-schema before it is added, and if the schema does not pass validation the exception is thrown. This behaviour is controlled by `validateSchema` option. + +__Please note__: Ajv uses the [method chaining syntax](https://en.wikipedia.org/wiki/Method_chaining) for all methods with the prefix `add*` and `remove*`. +This allows you to do nice things like the following. + +```javascript +var validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri); +``` + +##### .addMetaSchema(Array<Object>|Object schema [, String key]) -> Ajv + +Adds meta schema(s) that can be used to validate other schemas. That function should be used instead of `addSchema` because there may be instance options that would compile a meta schema incorrectly (at the moment it is `removeAdditional` option). + +There is no need to explicitly add draft-07 meta schema (http://json-schema.org/draft-07/schema) - it is added by default, unless option `meta` is set to `false`. You only need to use it if you have a changed meta-schema that you want to use to validate your schemas. See `validateSchema`. + + +##### .validateSchema(Object schema) -> Boolean + +Validates schema. This method should be used to validate schemas rather than `validate` due to the inconsistency of `uri` format in JSON Schema standard. + +By default this method is called automatically when the schema is added, so you rarely need to use it directly. + +If schema doesn't have `$schema` property, it is validated against draft 6 meta-schema (option `meta` should not be false). + +If schema has `$schema` property, then the schema with this id (that should be previously added) is used to validate passed schema. + +Errors will be available at `ajv.errors`. + + +##### .getSchema(String key) -> Function<Object data> + +Retrieve compiled schema previously added with `addSchema` by the key passed to `addSchema` or by its full reference (id). The returned validating function has `schema` property with the reference to the original schema. + + +##### .removeSchema([Object schema|String key|String ref|RegExp pattern]) -> Ajv + +Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references. + +Schema can be removed using: +- key passed to `addSchema` +- it's full reference (id) +- RegExp that should match schema id or key (meta-schemas won't be removed) +- actual schema object that will be stable-stringified to remove schema from cache + +If no parameter is passed all schemas but meta-schemas will be removed and the cache will be cleared. + + +##### .addFormat(String name, String|RegExp|Function|Object format) -> Ajv + +Add custom format to validate strings or numbers. It can also be used to replace pre-defined formats for Ajv instance. + +Strings are converted to RegExp. + +Function should return validation result as `true` or `false`. + +If object is passed it should have properties `validate`, `compare` and `async`: + +- _validate_: a string, RegExp or a function as described above. +- _compare_: an optional comparison function that accepts two strings and compares them according to the format meaning. This function is used with keywords `formatMaximum`/`formatMinimum` (defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package). It should return `1` if the first value is bigger than the second value, `-1` if it is smaller and `0` if it is equal. +- _async_: an optional `true` value if `validate` is an asynchronous function; in this case it should return a promise that resolves with a value `true` or `false`. +- _type_: an optional type of data that the format applies to. It can be `"string"` (default) or `"number"` (see https://github.com/ajv-validator/ajv/issues/291#issuecomment-259923858). If the type of data is different, the validation will pass. + +Custom formats can be also added via `formats` option. + + +##### .addKeyword(String keyword, Object definition) -> Ajv + +Add custom validation keyword to Ajv instance. + +Keyword should be different from all standard JSON Schema keywords and different from previously defined keywords. There is no way to redefine keywords or to remove keyword definition from the instance. + +Keyword must start with a letter, `_` or `$`, and may continue with letters, numbers, `_`, `$`, or `-`. +It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions. + +Example Keywords: +- `"xyz-example"`: valid, and uses prefix for the xyz project to avoid name collisions. +- `"example"`: valid, but not recommended as it could collide with future versions of JSON Schema etc. +- `"3-example"`: invalid as numbers are not allowed to be the first character in a keyword + +Keyword definition is an object with the following properties: + +- _type_: optional string or array of strings with data type(s) that the keyword applies to. If not present, the keyword will apply to all types. +- _validate_: validating function +- _compile_: compiling function +- _macro_: macro function +- _inline_: compiling function that returns code (as string) +- _schema_: an optional `false` value used with "validate" keyword to not pass schema +- _metaSchema_: an optional meta-schema for keyword schema +- _dependencies_: an optional list of properties that must be present in the parent schema - it will be checked during schema compilation +- _modifying_: `true` MUST be passed if keyword modifies data +- _statements_: `true` can be passed in case inline keyword generates statements (as opposed to expression) +- _valid_: pass `true`/`false` to pre-define validation result, the result returned from validation function will be ignored. This option cannot be used with macro keywords. +- _$data_: an optional `true` value to support [$data reference](#data-reference) as the value of custom keyword. The reference will be resolved at validation time. If the keyword has meta-schema it would be extended to allow $data and it will be used to validate the resolved value. Supporting $data reference requires that keyword has validating function (as the only option or in addition to compile, macro or inline function). +- _async_: an optional `true` value if the validation function is asynchronous (whether it is compiled or passed in _validate_ property); in this case it should return a promise that resolves with a value `true` or `false`. This option is ignored in case of "macro" and "inline" keywords. +- _errors_: an optional boolean or string `"full"` indicating whether keyword returns errors. If this property is not set Ajv will determine if the errors were set in case of failed validation. + +_compile_, _macro_ and _inline_ are mutually exclusive, only one should be used at a time. _validate_ can be used separately or in addition to them to support $data reference. + +__Please note__: If the keyword is validating data type that is different from the type(s) in its definition, the validation function will not be called (and expanded macro will not be used), so there is no need to check for data type inside validation function or inside schema returned by macro function (unless you want to enforce a specific type and for some reason do not want to use a separate `type` keyword for that). In the same way as standard keywords work, if the keyword does not apply to the data type being validated, the validation of this keyword will succeed. + +See [Defining custom keywords](#defining-custom-keywords) for more details. + + +##### .getKeyword(String keyword) -> Object|Boolean + +Returns custom keyword definition, `true` for pre-defined keywords and `false` if the keyword is unknown. + + +##### .removeKeyword(String keyword) -> Ajv + +Removes custom or pre-defined keyword so you can redefine them. + +While this method can be used to extend pre-defined keywords, it can also be used to completely change their meaning - it may lead to unexpected results. + +__Please note__: schemas compiled before the keyword is removed will continue to work without changes. To recompile schemas use `removeSchema` method and compile them again. + + +##### .errorsText([Array<Object> errors [, Object options]]) -> String + +Returns the text with all errors in a String. + +Options can have properties `separator` (string used to separate errors, ", " by default) and `dataVar` (the variable name that dataPaths are prefixed with, "data" by default). + + +## Options + +Defaults: + +```javascript +{ + // validation and reporting options: + $data: false, + allErrors: false, + verbose: false, + $comment: false, // NEW in Ajv version 6.0 + jsonPointers: false, + uniqueItems: true, + unicode: true, + nullable: false, + format: 'fast', + formats: {}, + unknownFormats: true, + schemas: {}, + logger: undefined, + // referenced schema options: + schemaId: '$id', + missingRefs: true, + extendRefs: 'ignore', // recommended 'fail' + loadSchema: undefined, // function(uri: string): Promise {} + // options to modify validated data: + removeAdditional: false, + useDefaults: false, + coerceTypes: false, + // strict mode options + strictDefaults: false, + strictKeywords: false, + strictNumbers: false, + // asynchronous validation options: + transpile: undefined, // requires ajv-async package + // advanced options: + meta: true, + validateSchema: true, + addUsedSchema: true, + inlineRefs: true, + passContext: false, + loopRequired: Infinity, + ownProperties: false, + multipleOfPrecision: false, + errorDataPath: 'object', // deprecated + messages: true, + sourceCode: false, + processCode: undefined, // function (str: string, schema: object): string {} + cache: new Cache, + serialize: undefined, + regExp: undefined // custom RegExp engine +} +``` + +##### Validation and reporting options + +- _$data_: support [$data references](#data-reference). Draft 6 meta-schema that is added by default will be extended to allow them. If you want to use another meta-schema you need to use $dataMetaSchema method to add support for $data reference. See [API](#api). +- _allErrors_: check all rules collecting all errors. Default is to return after the first error. +- _verbose_: include the reference to the part of the schema (`schema` and `parentSchema`) and validated data in errors (false by default). +- _$comment_ (NEW in Ajv version 6.0): log or pass the value of `$comment` keyword to a function. Option values: + - `false` (default): ignore $comment keyword. + - `true`: log the keyword value to console. + - function: pass the keyword value, its schema path and root schema to the specified function +- _jsonPointers_: set `dataPath` property of errors using [JSON Pointers](https://tools.ietf.org/html/rfc6901) instead of JavaScript property access notation. +- _uniqueItems_: validate `uniqueItems` keyword (true by default). +- _unicode_: calculate correct length of strings with unicode pairs (true by default). Pass `false` to use `.length` of strings that is faster, but gives "incorrect" lengths of strings with unicode pairs - each unicode pair is counted as two characters. +- _nullable_: support keyword "nullable" from [Open API 3 specification](https://swagger.io/docs/specification/data-models/data-types/). +- _format_: formats validation mode. Option values: + - `"fast"` (default) - simplified and fast validation (see [Formats](#formats) for details of which formats are available and affected by this option). + - `"full"` - more restrictive and slow validation. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode. + - `false` - ignore all format keywords. +- _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method. +- _keywords_: an object with custom keywords. Keys and values will be passed to `addKeyword` method. +- _unknownFormats_: handling of unknown formats. Option values: + - `true` (default) - if an unknown format is encountered the exception is thrown during schema compilation. If `format` keyword value is [$data reference](#data-reference) and it is unknown the validation will fail. + - `[String]` - an array of unknown format names that will be ignored. This option can be used to allow usage of third party schemas with format(s) for which you don't have definitions, but still fail if another unknown format is used. If `format` keyword value is [$data reference](#data-reference) and it is not in this array the validation will fail. + - `"ignore"` - to log warning during schema compilation and always pass validation (the default behaviour in versions before 5.0.0). This option is not recommended, as it allows to mistype format name and it won't be validated without any error message. This behaviour is required by JSON Schema specification. +- _schemas_: an array or object of schemas that will be added to the instance. In case you pass the array the schemas must have IDs in them. When the object is passed the method `addSchema(value, key)` will be called for each schema in this object. +- _logger_: sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. See [Error logging](#error-logging). Option values: + - custom logger - it should have methods `log`, `warn` and `error`. If any of these methods is missing an exception will be thrown. + - `false` - logging is disabled. + + +##### Referenced schema options + +- _schemaId_: this option defines which keywords are used as schema URI. Option value: + - `"$id"` (default) - only use `$id` keyword as schema URI (as specified in JSON Schema draft-06/07), ignore `id` keyword (if it is present a warning will be logged). + - `"id"` - only use `id` keyword as schema URI (as specified in JSON Schema draft-04), ignore `$id` keyword (if it is present a warning will be logged). + - `"auto"` - use both `$id` and `id` keywords as schema URI. If both are present (in the same schema object) and different the exception will be thrown during schema compilation. +- _missingRefs_: handling of missing referenced schemas. Option values: + - `true` (default) - if the reference cannot be resolved during compilation the exception is thrown. The thrown error has properties `missingRef` (with hash fragment) and `missingSchema` (without it). Both properties are resolved relative to the current base id (usually schema id, unless it was substituted). + - `"ignore"` - to log error during compilation and always pass validation. + - `"fail"` - to log error and successfully compile schema but fail validation if this rule is checked. +- _extendRefs_: validation of other keywords when `$ref` is present in the schema. Option values: + - `"ignore"` (default) - when `$ref` is used other keywords are ignored (as per [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-3) standard). A warning will be logged during the schema compilation. + - `"fail"` (recommended) - if other validation keywords are used together with `$ref` the exception will be thrown when the schema is compiled. This option is recommended to make sure schema has no keywords that are ignored, which can be confusing. + - `true` - validate all keywords in the schemas with `$ref` (the default behaviour in versions before 5.0.0). +- _loadSchema_: asynchronous function that will be used to load remote schemas when `compileAsync` [method](#api-compileAsync) is used and some reference is missing (option `missingRefs` should NOT be 'fail' or 'ignore'). This function should accept remote schema uri as a parameter and return a Promise that resolves to a schema. See example in [Asynchronous compilation](#asynchronous-schema-compilation). + + +##### Options to modify validated data + +- _removeAdditional_: remove additional properties - see example in [Filtering data](#filtering-data). This option is not used if schema is added with `addMetaSchema` method. Option values: + - `false` (default) - not to remove additional properties + - `"all"` - all additional properties are removed, regardless of `additionalProperties` keyword in schema (and no validation is made for them). + - `true` - only additional properties with `additionalProperties` keyword equal to `false` are removed. + - `"failing"` - additional properties that fail schema validation will be removed (where `additionalProperties` keyword is `false` or schema). +- _useDefaults_: replace missing or undefined properties and items with the values from corresponding `default` keywords. Default behaviour is to ignore `default` keywords. This option is not used if schema is added with `addMetaSchema` method. See examples in [Assigning defaults](#assigning-defaults). Option values: + - `false` (default) - do not use defaults + - `true` - insert defaults by value (object literal is used). + - `"empty"` - in addition to missing or undefined, use defaults for properties and items that are equal to `null` or `""` (an empty string). + - `"shared"` (deprecated) - insert defaults by reference. If the default is an object, it will be shared by all instances of validated data. If you modify the inserted default in the validated data, it will be modified in the schema as well. +- _coerceTypes_: change data type of data to match `type` keyword. See the example in [Coercing data types](#coercing-data-types) and [coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md). Option values: + - `false` (default) - no type coercion. + - `true` - coerce scalar data types. + - `"array"` - in addition to coercions between scalar types, coerce scalar data to an array with one element and vice versa (as required by the schema). + + +##### Strict mode options + +- _strictDefaults_: report ignored `default` keywords in schemas. Option values: + - `false` (default) - ignored defaults are not reported + - `true` - if an ignored default is present, throw an error + - `"log"` - if an ignored default is present, log warning +- _strictKeywords_: report unknown keywords in schemas. Option values: + - `false` (default) - unknown keywords are not reported + - `true` - if an unknown keyword is present, throw an error + - `"log"` - if an unknown keyword is present, log warning +- _strictNumbers_: validate numbers strictly, failing validation for NaN and Infinity. Option values: + - `false` (default) - NaN or Infinity will pass validation for numeric types + - `true` - NaN or Infinity will not pass validation for numeric types + +##### Asynchronous validation options + +- _transpile_: Requires [ajv-async](https://github.com/ajv-validator/ajv-async) package. It determines whether Ajv transpiles compiled asynchronous validation function. Option values: + - `undefined` (default) - transpile with [nodent](https://github.com/MatAtBread/nodent) if async functions are not supported. + - `true` - always transpile with nodent. + - `false` - do not transpile; if async functions are not supported an exception will be thrown. + + +##### Advanced options + +- _meta_: add [meta-schema](http://json-schema.org/documentation.html) so it can be used by other schemas (true by default). If an object is passed, it will be used as the default meta-schema for schemas that have no `$schema` keyword. This default meta-schema MUST have `$schema` keyword. +- _validateSchema_: validate added/compiled schemas against meta-schema (true by default). `$schema` property in the schema can be http://json-schema.org/draft-07/schema or absent (draft-07 meta-schema will be used) or can be a reference to the schema previously added with `addMetaSchema` method. Option values: + - `true` (default) - if the validation fails, throw the exception. + - `"log"` - if the validation fails, log error. + - `false` - skip schema validation. +- _addUsedSchema_: by default methods `compile` and `validate` add schemas to the instance if they have `$id` (or `id`) property that doesn't start with "#". If `$id` is present and it is not unique the exception will be thrown. Set this option to `false` to skip adding schemas to the instance and the `$id` uniqueness check when these methods are used. This option does not affect `addSchema` method. +- _inlineRefs_: Affects compilation of referenced schemas. Option values: + - `true` (default) - the referenced schemas that don't have refs in them are inlined, regardless of their size - that substantially improves performance at the cost of the bigger size of compiled schema functions. + - `false` - to not inline referenced schemas (they will be compiled as separate functions). + - integer number - to limit the maximum number of keywords of the schema that will be inlined. +- _passContext_: pass validation context to custom keyword functions. If this option is `true` and you pass some context to the compiled validation function with `validate.call(context, data)`, the `context` will be available as `this` in your custom keywords. By default `this` is Ajv instance. +- _loopRequired_: by default `required` keyword is compiled into a single expression (or a sequence of statements in `allErrors` mode). In case of a very large number of properties in this keyword it may result in a very big validation function. Pass integer to set the number of properties above which `required` keyword will be validated in a loop - smaller validation function size but also worse performance. +- _ownProperties_: by default Ajv iterates over all enumerable object properties; when this option is `true` only own enumerable object properties (i.e. found directly on the object rather than on its prototype) are iterated. Contributed by @mbroadst. +- _multipleOfPrecision_: by default `multipleOf` keyword is validated by comparing the result of division with parseInt() of that result. It works for dividers that are bigger than 1. For small dividers such as 0.01 the result of the division is usually not integer (even when it should be integer, see issue [#84](https://github.com/ajv-validator/ajv/issues/84)). If you need to use fractional dividers set this option to some positive integer N to have `multipleOf` validated using this formula: `Math.abs(Math.round(division) - division) < 1e-N` (it is slower but allows for float arithmetics deviations). +- _errorDataPath_ (deprecated): set `dataPath` to point to 'object' (default) or to 'property' when validating keywords `required`, `additionalProperties` and `dependencies`. +- _messages_: Include human-readable messages in errors. `true` by default. `false` can be passed when custom messages are used (e.g. with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n)). +- _sourceCode_: add `sourceCode` property to validating function (for debugging; this code can be different from the result of toString call). +- _processCode_: an optional function to process generated code before it is passed to Function constructor. It can be used to either beautify (the validating function is generated without line-breaks) or to transpile code. Starting from version 5.0.0 this option replaced options: + - `beautify` that formatted the generated function using [js-beautify](https://github.com/beautify-web/js-beautify). If you want to beautify the generated code pass a function calling `require('js-beautify').js_beautify` as `processCode: code => js_beautify(code)`. + - `transpile` that transpiled asynchronous validation function. You can still use `transpile` option with [ajv-async](https://github.com/ajv-validator/ajv-async) package. See [Asynchronous validation](#asynchronous-validation) for more information. +- _cache_: an optional instance of cache to store compiled schemas using stable-stringified schema as a key. For example, set-associative cache [sacjs](https://github.com/epoberezkin/sacjs) can be used. If not passed then a simple hash is used which is good enough for the common use case (a limited number of statically defined schemas). Cache should have methods `put(key, value)`, `get(key)`, `del(key)` and `clear()`. +- _serialize_: an optional function to serialize schema to cache key. Pass `false` to use schema itself as a key (e.g., if WeakMap used as a cache). By default [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used. +- _regExp_: an optional function to create RegExp objects. This allows using a custom RegExp engine (e.g., [RE2](https://github.com/uhop/node-re2)) to mitigate ReDoS attacks. The function must have the signature `(pattern: string) => RegExpLike` where `RegExpLike` is an object with a `test(string) => boolean` method. Example with RE2: + ```javascript + var ajv = new Ajv({regExp: require('re2')}); + ``` + By default (`undefined`), native `RegExp` constructor is used. + + +## Validation errors + +In case of validation failure, Ajv assigns the array of errors to `errors` property of validation function (or to `errors` property of Ajv instance when `validate` or `validateSchema` methods were called). In case of [asynchronous validation](#asynchronous-validation), the returned promise is rejected with exception `Ajv.ValidationError` that has `errors` property. + + +### Error objects + +Each error is an object with the following properties: + +- _keyword_: validation keyword. +- _dataPath_: the path to the part of the data that was validated. By default `dataPath` uses JavaScript property access notation (e.g., `".prop[1].subProp"`). When the option `jsonPointers` is true (see [Options](#options)) `dataPath` will be set using JSON pointer standard (e.g., `"/prop/1/subProp"`). +- _schemaPath_: the path (JSON-pointer as a URI fragment) to the schema of the keyword that failed validation. +- _params_: the object with the additional information about error that can be used to create custom error messages (e.g., using [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package). See below for parameters set by all keywords. +- _message_: the standard error message (can be excluded with option `messages` set to false). +- _schema_: the schema of the keyword (added with `verbose` option). +- _parentSchema_: the schema containing the keyword (added with `verbose` option) +- _data_: the data validated by the keyword (added with `verbose` option). + +__Please note__: `propertyNames` keyword schema validation errors have an additional property `propertyName`, `dataPath` points to the object. After schema validation for each property name, if it is invalid an additional error is added with the property `keyword` equal to `"propertyNames"`. + + +### Error parameters + +Properties of `params` object in errors depend on the keyword that failed validation. + +- `maxItems`, `minItems`, `maxLength`, `minLength`, `maxProperties`, `minProperties` - property `limit` (number, the schema of the keyword). +- `additionalItems` - property `limit` (the maximum number of allowed items in case when `items` keyword is an array of schemas and `additionalItems` is false). +- `additionalProperties` - property `additionalProperty` (the property not used in `properties` and `patternProperties` keywords). +- `dependencies` - properties: + - `property` (dependent property), + - `missingProperty` (required missing dependency - only the first one is reported currently) + - `deps` (required dependencies, comma separated list as a string), + - `depsCount` (the number of required dependencies). +- `format` - property `format` (the schema of the keyword). +- `maximum`, `minimum` - properties: + - `limit` (number, the schema of the keyword), + - `exclusive` (boolean, the schema of `exclusiveMaximum` or `exclusiveMinimum`), + - `comparison` (string, comparison operation to compare the data to the limit, with the data on the left and the limit on the right; can be "<", "<=", ">", ">=") +- `multipleOf` - property `multipleOf` (the schema of the keyword) +- `pattern` - property `pattern` (the schema of the keyword) +- `required` - property `missingProperty` (required property that is missing). +- `propertyNames` - property `propertyName` (an invalid property name). +- `patternRequired` (in ajv-keywords) - property `missingPattern` (required pattern that did not match any property). +- `type` - property `type` (required type(s), a string, can be a comma-separated list) +- `uniqueItems` - properties `i` and `j` (indices of duplicate items). +- `const` - property `allowedValue` pointing to the value (the schema of the keyword). +- `enum` - property `allowedValues` pointing to the array of values (the schema of the keyword). +- `$ref` - property `ref` with the referenced schema URI. +- `oneOf` - property `passingSchemas` (array of indices of passing schemas, null if no schema passes). +- custom keywords (in case keyword definition doesn't create errors) - property `keyword` (the keyword name). + + +### Error logging + +Using the `logger` option when initiallizing Ajv will allow you to define custom logging. Here you can build upon the exisiting logging. The use of other logging packages is supported as long as the package or its associated wrapper exposes the required methods. If any of the required methods are missing an exception will be thrown. +- **Required Methods**: `log`, `warn`, `error` + +```javascript +var otherLogger = new OtherLogger(); +var ajv = new Ajv({ + logger: { + log: console.log.bind(console), + warn: function warn() { + otherLogger.logWarn.apply(otherLogger, arguments); + }, + error: function error() { + otherLogger.logError.apply(otherLogger, arguments); + console.error.apply(console, arguments); + } + } +}); +``` + + +## Plugins + +Ajv can be extended with plugins that add custom keywords, formats or functions to process generated code. When such plugin is published as npm package it is recommended that it follows these conventions: + +- it exports a function +- this function accepts ajv instance as the first parameter and returns the same instance to allow chaining +- this function can accept an optional configuration as the second parameter + +If you have published a useful plugin please submit a PR to add it to the next section. + + +## Related packages + +- [ajv-async](https://github.com/ajv-validator/ajv-async) - plugin to configure async validation mode +- [ajv-bsontype](https://github.com/BoLaMN/ajv-bsontype) - plugin to validate mongodb's bsonType formats +- [ajv-cli](https://github.com/jessedc/ajv-cli) - command line interface +- [ajv-errors](https://github.com/ajv-validator/ajv-errors) - plugin for custom error messages +- [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) - internationalised error messages +- [ajv-istanbul](https://github.com/ajv-validator/ajv-istanbul) - plugin to instrument generated validation code to measure test coverage of your schemas +- [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) - plugin with custom validation keywords (select, typeof, etc.) +- [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) - plugin with keywords $merge and $patch +- [ajv-pack](https://github.com/ajv-validator/ajv-pack) - produces a compact module exporting validation functions +- [ajv-formats-draft2019](https://github.com/luzlab/ajv-formats-draft2019) - format validators for draft2019 that aren't already included in ajv (ie. `idn-hostname`, `idn-email`, `iri`, `iri-reference` and `duration`). + +## Some packages using Ajv + +- [webpack](https://github.com/webpack/webpack) - a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser +- [jsonscript-js](https://github.com/JSONScript/jsonscript-js) - the interpreter for [JSONScript](http://www.jsonscript.org) - scripted processing of existing endpoints and services +- [osprey-method-handler](https://github.com/mulesoft-labs/osprey-method-handler) - Express middleware for validating requests and responses based on a RAML method object, used in [osprey](https://github.com/mulesoft/osprey) - validating API proxy generated from a RAML definition +- [har-validator](https://github.com/ahmadnassri/har-validator) - HTTP Archive (HAR) validator +- [jsoneditor](https://github.com/josdejong/jsoneditor) - a web-based tool to view, edit, format, and validate JSON http://jsoneditoronline.org +- [JSON Schema Lint](https://github.com/nickcmaynard/jsonschemalint) - a web tool to validate JSON/YAML document against a single JSON Schema http://jsonschemalint.com +- [objection](https://github.com/vincit/objection.js) - SQL-friendly ORM for Node.js +- [table](https://github.com/gajus/table) - formats data into a string table +- [ripple-lib](https://github.com/ripple/ripple-lib) - a JavaScript API for interacting with [Ripple](https://ripple.com) in Node.js and the browser +- [restbase](https://github.com/wikimedia/restbase) - distributed storage with REST API & dispatcher for backend services built to provide a low-latency & high-throughput API for Wikipedia / Wikimedia content +- [hippie-swagger](https://github.com/CacheControl/hippie-swagger) - [Hippie](https://github.com/vesln/hippie) wrapper that provides end to end API testing with swagger validation +- [react-form-controlled](https://github.com/seeden/react-form-controlled) - React controlled form components with validation +- [rabbitmq-schema](https://github.com/tjmehta/rabbitmq-schema) - a schema definition module for RabbitMQ graphs and messages +- [@query/schema](https://www.npmjs.com/package/@query/schema) - stream filtering with a URI-safe query syntax parsing to JSON Schema +- [chai-ajv-json-schema](https://github.com/peon374/chai-ajv-json-schema) - chai plugin to us JSON Schema with expect in mocha tests +- [grunt-jsonschema-ajv](https://github.com/SignpostMarv/grunt-jsonschema-ajv) - Grunt plugin for validating files against JSON Schema +- [extract-text-webpack-plugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) - extract text from bundle into a file +- [electron-builder](https://github.com/electron-userland/electron-builder) - a solution to package and build a ready for distribution Electron app +- [addons-linter](https://github.com/mozilla/addons-linter) - Mozilla Add-ons Linter +- [gh-pages-generator](https://github.com/epoberezkin/gh-pages-generator) - multi-page site generator converting markdown files to GitHub pages +- [ESLint](https://github.com/eslint/eslint) - the pluggable linting utility for JavaScript and JSX +- [Spectral](https://github.com/stoplightio/spectral) - the customizable linting utility for JSON/YAML, OpenAPI, AsyncAPI, and JSON Schema + + +## Tests + +``` +npm install +git submodule update --init +npm test +``` + +## Contributing + +All validation functions are generated using doT templates in [dot](https://github.com/ajv-validator/ajv/tree/master/lib/dot) folder. Templates are precompiled so doT is not a run-time dependency. + +`npm run build` - compiles templates to [dotjs](https://github.com/ajv-validator/ajv/tree/master/lib/dotjs) folder. + +`npm run watch` - automatically compiles templates when files in dot folder change + +Please see [Contributing guidelines](https://github.com/ajv-validator/ajv/blob/master/CONTRIBUTING.md) + + +## Changes history + +See https://github.com/ajv-validator/ajv/releases + +__Please note__: [Changes in version 7.0.0-beta](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0-beta.0) + +[Version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0). + +## Code of conduct + +Please review and follow the [Code of conduct](https://github.com/ajv-validator/ajv/blob/master/CODE_OF_CONDUCT.md). + +Please report any unacceptable behaviour to ajv.validator@gmail.com - it will be reviewed by the project team. + + +## Open-source software support + +Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers. + + +## License + +[MIT](https://github.com/ajv-validator/ajv/blob/master/LICENSE) diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/dist/ajv.bundle.js b/tools/ui/node_modules/eslint/node_modules/ajv/dist/ajv.bundle.js new file mode 100644 index 0000000000000000000000000000000000000000..3243c9fc49b2ec58c90e7a8d250b69197ed771cc --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/dist/ajv.bundle.js @@ -0,0 +1,7201 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Ajv = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; +// For the source: https://gist.github.com/dperini/729294 +// For test cases: https://mathiasbynens.be/demo/url-regex +// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983. +// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; +var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i; +var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; +var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; +var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; +var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; + + +module.exports = formats; + +function formats(mode) { + mode = mode == 'full' ? 'full' : 'fast'; + return util.copy(formats[mode]); +} + + +formats.fast = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, + 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + 'uri-reference': /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + 'uri-template': URITEMPLATE, + url: URL, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation') + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, + hostname: HOSTNAME, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: UUID, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; + + +formats.full = { + date: date, + time: time, + 'date-time': date_time, + uri: uri, + 'uri-reference': URIREF, + 'uri-template': URITEMPLATE, + url: URL, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: HOSTNAME, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + uuid: UUID, + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; + + +function isLeapYear(year) { + // https://tools.ietf.org/html/rfc3339#appendix-C + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} + + +function date(str) { + // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 + var matches = str.match(DATE); + if (!matches) return false; + + var year = +matches[1]; + var month = +matches[2]; + var day = +matches[3]; + + return month >= 1 && month <= 12 && day >= 1 && + day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); +} + + +function time(str, full) { + var matches = str.match(TIME); + if (!matches) return false; + + var hour = matches[1]; + var minute = matches[2]; + var second = matches[3]; + var timeZone = matches[5]; + return ((hour <= 23 && minute <= 59 && second <= 59) || + (hour == 23 && minute == 59 && second == 60)) && + (!full || timeZone); +} + + +var DATE_TIME_SEPARATOR = /t|\s/i; +function date_time(str) { + // http://tools.ietf.org/html/rfc3339#section-5.6 + var dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); +} + + +var NOT_URI_FRAGMENT = /\/|:/; +function uri(str) { + // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." + return NOT_URI_FRAGMENT.test(str) && URI.test(str); +} + + +var Z_ANCHOR = /[^\\]\\Z/; +function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str); + return true; + } catch(e) { + return false; + } +} + +},{"./util":10}],5:[function(require,module,exports){ +'use strict'; + +var resolve = require('./resolve') + , util = require('./util') + , errorClasses = require('./error_classes') + , stableStringify = require('fast-json-stable-stringify'); + +var validateGenerator = require('../dotjs/validate'); + +/** + * Functions below are used inside compiled validations function + */ + +var ucs2length = util.ucs2length; +var equal = require('fast-deep-equal'); + +// this error is thrown by async schemas to return validation errors via exception +var ValidationError = errorClasses.Validation; + +module.exports = compile; + + +/** + * Compiles schema to validation function + * @this Ajv + * @param {Object} schema schema object + * @param {Object} root object with information about the root schema for this schema + * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution + * @param {String} baseId base ID for IDs in the schema + * @return {Function} validation function + */ +function compile(schema, root, localRefs, baseId) { + /* jshint validthis: true, evil: true */ + /* eslint no-shadow: 0 */ + var self = this + , opts = this._opts + , refVal = [ undefined ] + , refs = {} + , patterns = [] + , patternsHash = {} + , defaults = [] + , defaultsHash = {} + , customRules = []; + + function patternCode(i, patterns) { + var regExpCode = opts.regExp ? 'regExp' : 'new RegExp'; + return 'var pattern' + i + ' = ' + regExpCode + '(' + util.toQuotedString(patterns[i]) + ');'; + } + + root = root || { schema: schema, refVal: refVal, refs: refs }; + + var c = checkCompiling.call(this, schema, root, baseId); + var compilation = this._compilations[c.index]; + if (c.compiling) return (compilation.callValidate = callValidate); + + var formats = this._formats; + var RULES = this.RULES; + + try { + var v = localCompile(schema, root, localRefs, baseId); + compilation.validate = v; + var cv = compilation.callValidate; + if (cv) { + cv.schema = v.schema; + cv.errors = null; + cv.refs = v.refs; + cv.refVal = v.refVal; + cv.root = v.root; + cv.$async = v.$async; + if (opts.sourceCode) cv.source = v.source; + } + return v; + } finally { + endCompiling.call(this, schema, root, baseId); + } + + /* @this {*} - custom context, see passContext option */ + function callValidate() { + /* jshint validthis: true */ + var validate = compilation.validate; + var result = validate.apply(this, arguments); + callValidate.errors = validate.errors; + return result; + } + + function localCompile(_schema, _root, localRefs, baseId) { + var isRoot = !_root || (_root && _root.schema == _schema); + if (_root.schema != root.schema) + return compile.call(self, _schema, _root, localRefs, baseId); + + var $async = _schema.$async === true; + + var sourceCode = validateGenerator({ + isTop: true, + schema: _schema, + isRoot: isRoot, + baseId: baseId, + root: _root, + schemaPath: '', + errSchemaPath: '#', + errorPath: '""', + MissingRefError: errorClasses.MissingRef, + RULES: RULES, + validate: validateGenerator, + util: util, + resolve: resolve, + resolveRef: resolveRef, + usePattern: usePattern, + useDefault: useDefault, + useCustomRule: useCustomRule, + opts: opts, + formats: formats, + logger: self.logger, + self: self + }); + + sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + + sourceCode; + + if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema); + // console.log('\n\n\n *** \n', JSON.stringify(sourceCode)); + var validate; + try { + var makeValidate = new Function( + 'self', + 'RULES', + 'formats', + 'root', + 'refVal', + 'defaults', + 'customRules', + 'equal', + 'ucs2length', + 'ValidationError', + 'regExp', + sourceCode + ); + + validate = makeValidate( + self, + RULES, + formats, + root, + refVal, + defaults, + customRules, + equal, + ucs2length, + ValidationError, + opts.regExp + ); + + refVal[0] = validate; + } catch(e) { + self.logger.error('Error compiling schema, function code:', sourceCode); + throw e; + } + + validate.schema = _schema; + validate.errors = null; + validate.refs = refs; + validate.refVal = refVal; + validate.root = isRoot ? validate : _root; + if ($async) validate.$async = true; + if (opts.sourceCode === true) { + validate.source = { + code: sourceCode, + patterns: patterns, + defaults: defaults + }; + } + + return validate; + } + + function resolveRef(baseId, ref, isRoot) { + ref = resolve.url(baseId, ref); + var refIndex = refs[ref]; + var _refVal, refCode; + if (refIndex !== undefined) { + _refVal = refVal[refIndex]; + refCode = 'refVal[' + refIndex + ']'; + return resolvedRef(_refVal, refCode); + } + if (!isRoot && root.refs) { + var rootRefId = root.refs[ref]; + if (rootRefId !== undefined) { + _refVal = root.refVal[rootRefId]; + refCode = addLocalRef(ref, _refVal); + return resolvedRef(_refVal, refCode); + } + } + + refCode = addLocalRef(ref); + var v = resolve.call(self, localCompile, root, ref); + if (v === undefined) { + var localSchema = localRefs && localRefs[ref]; + if (localSchema) { + v = resolve.inlineRef(localSchema, opts.inlineRefs) + ? localSchema + : compile.call(self, localSchema, root, localRefs, baseId); + } + } + + if (v === undefined) { + removeLocalRef(ref); + } else { + replaceLocalRef(ref, v); + return resolvedRef(v, refCode); + } + } + + function addLocalRef(ref, v) { + var refId = refVal.length; + refVal[refId] = v; + refs[ref] = refId; + return 'refVal' + refId; + } + + function removeLocalRef(ref) { + delete refs[ref]; + } + + function replaceLocalRef(ref, v) { + var refId = refs[ref]; + refVal[refId] = v; + } + + function resolvedRef(refVal, code) { + return typeof refVal == 'object' || typeof refVal == 'boolean' + ? { code: code, schema: refVal, inline: true } + : { code: code, $async: refVal && !!refVal.$async }; + } + + function usePattern(regexStr) { + var index = patternsHash[regexStr]; + if (index === undefined) { + index = patternsHash[regexStr] = patterns.length; + patterns[index] = regexStr; + } + return 'pattern' + index; + } + + function useDefault(value) { + switch (typeof value) { + case 'boolean': + case 'number': + return '' + value; + case 'string': + return util.toQuotedString(value); + case 'object': + if (value === null) return 'null'; + var valueStr = stableStringify(value); + var index = defaultsHash[valueStr]; + if (index === undefined) { + index = defaultsHash[valueStr] = defaults.length; + defaults[index] = value; + } + return 'default' + index; + } + } + + function useCustomRule(rule, schema, parentSchema, it) { + if (self._opts.validateSchema !== false) { + var deps = rule.definition.dependencies; + if (deps && !deps.every(function(keyword) { + return Object.prototype.hasOwnProperty.call(parentSchema, keyword); + })) + throw new Error('parent schema must have all required keywords: ' + deps.join(',')); + + var validateSchema = rule.definition.validateSchema; + if (validateSchema) { + var valid = validateSchema(schema); + if (!valid) { + var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); + if (self._opts.validateSchema == 'log') self.logger.error(message); + else throw new Error(message); + } + } + } + + var compile = rule.definition.compile + , inline = rule.definition.inline + , macro = rule.definition.macro; + + var validate; + if (compile) { + validate = compile.call(self, schema, parentSchema, it); + } else if (macro) { + validate = macro.call(self, schema, parentSchema, it); + if (opts.validateSchema !== false) self.validateSchema(validate, true); + } else if (inline) { + validate = inline.call(self, it, rule.keyword, schema, parentSchema); + } else { + validate = rule.definition.validate; + if (!validate) return; + } + + if (validate === undefined) + throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); + + var index = customRules.length; + customRules[index] = validate; + + return { + code: 'customRule' + index, + validate: validate + }; + } +} + + +/** + * Checks if the schema is currently compiled + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) + */ +function checkCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var index = compIndex.call(this, schema, root, baseId); + if (index >= 0) return { index: index, compiling: true }; + index = this._compilations.length; + this._compilations[index] = { + schema: schema, + root: root, + baseId: baseId + }; + return { index: index, compiling: false }; +} + + +/** + * Removes the schema from the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + */ +function endCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var i = compIndex.call(this, schema, root, baseId); + if (i >= 0) this._compilations.splice(i, 1); +} + + +/** + * Index of schema compilation in the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Integer} compilation index + */ +function compIndex(schema, root, baseId) { + /* jshint validthis: true */ + for (var i=0; i= 0xD800 && value <= 0xDBFF && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos); + if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate + } + } + return length; +}; + +},{}],10:[function(require,module,exports){ +'use strict'; + + +module.exports = { + copy: copy, + checkDataType: checkDataType, + checkDataTypes: checkDataTypes, + coerceToTypes: coerceToTypes, + toHash: toHash, + getProperty: getProperty, + escapeQuotes: escapeQuotes, + equal: require('fast-deep-equal'), + ucs2length: require('./ucs2length'), + varOccurences: varOccurences, + varReplace: varReplace, + schemaHasRules: schemaHasRules, + schemaHasRulesExcept: schemaHasRulesExcept, + schemaUnknownRules: schemaUnknownRules, + toQuotedString: toQuotedString, + getPathExpr: getPathExpr, + getPath: getPath, + getData: getData, + unescapeFragment: unescapeFragment, + unescapeJsonPointer: unescapeJsonPointer, + escapeFragment: escapeFragment, + escapeJsonPointer: escapeJsonPointer +}; + + +function copy(o, to) { + to = to || {}; + for (var key in o) to[key] = o[key]; + return to; +} + + +function checkDataType(dataType, data, strictNumbers, negate) { + var EQUAL = negate ? ' !== ' : ' === ' + , AND = negate ? ' || ' : ' && ' + , OK = negate ? '!' : '' + , NOT = negate ? '' : '!'; + switch (dataType) { + case 'null': return data + EQUAL + 'null'; + case 'array': return OK + 'Array.isArray(' + data + ')'; + case 'object': return '(' + OK + data + AND + + 'typeof ' + data + EQUAL + '"object"' + AND + + NOT + 'Array.isArray(' + data + '))'; + case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND + + NOT + '(' + data + ' % 1)' + + AND + data + EQUAL + data + + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; + case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' + + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; + default: return 'typeof ' + data + EQUAL + '"' + dataType + '"'; + } +} + + +function checkDataTypes(dataTypes, data, strictNumbers) { + switch (dataTypes.length) { + case 1: return checkDataType(dataTypes[0], data, strictNumbers, true); + default: + var code = ''; + var types = toHash(dataTypes); + if (types.array && types.object) { + code = types.null ? '(': '(!' + data + ' || '; + code += 'typeof ' + data + ' !== "object")'; + delete types.null; + delete types.array; + delete types.object; + } + if (types.number) delete types.integer; + for (var t in types) + code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true); + + return code; + } +} + + +var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); +function coerceToTypes(optionCoerceTypes, dataTypes) { + if (Array.isArray(dataTypes)) { + var types = []; + for (var i=0; i= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); + return paths[lvl - up]; + } + + if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); + data = 'data' + ((lvl - up) || ''); + if (!jsonPointer) return data; + } + + var expr = data; + var segments = jsonPointer.split('/'); + for (var i=0; i', + $notOp = $isMax ? '>' : '<', + $errorKeyword = undefined; + if (!($isData || typeof $schema == 'number' || $schema === undefined)) { + throw new Error($keyword + ' must be number'); + } + if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) { + throw new Error($exclusiveKeyword + ' must be number or boolean'); + } + if ($isDataExcl) { + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), + $exclusive = 'exclusive' + $lvl, + $exclType = 'exclType' + $lvl, + $exclIsNumber = 'exclIsNumber' + $lvl, + $opExpr = 'op' + $lvl, + $opStr = '\' + ' + $opExpr + ' + \''; + out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; + $schemaValueExcl = 'schemaExcl' + $lvl; + out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { '; + var $errorKeyword = $exclusiveKeyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; '; + if ($schema === undefined) { + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaValueExcl; + $isData = $isDataExcl; + } + } else { + var $exclIsNumber = typeof $schemaExcl == 'number', + $opStr = $op; + if ($exclIsNumber && $isData) { + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { '; + } else { + if ($exclIsNumber && $schema === undefined) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaExcl; + $notOp += '='; + } else { + if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); + if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $notOp += '='; + } else { + $exclusive = false; + $opStr += '='; + } + } + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { '; + } + } + $errorKeyword = $errorKeyword || $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be ' + ($opStr) + ' '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schemaValue) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],14:[function(require,module,exports){ +'use strict'; +module.exports = function generate__limitItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxItems' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxItems') { + out += 'more'; + } else { + out += 'fewer'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],15:[function(require,module,exports){ +'use strict'; +module.exports = function generate__limitLength(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxLength' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + if (it.opts.unicode === false) { + out += ' ' + ($data) + '.length '; + } else { + out += ' ucs2length(' + ($data) + ') '; + } + out += ' ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be '; + if ($keyword == 'maxLength') { + out += 'longer'; + } else { + out += 'shorter'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' characters\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],16:[function(require,module,exports){ +'use strict'; +module.exports = function generate__limitProperties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxProperties' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxProperties') { + out += 'more'; + } else { + out += 'fewer'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' properties\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],17:[function(require,module,exports){ +'use strict'; +module.exports = function generate_allOf(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $allSchemasEmpty = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $allSchemasEmpty = false; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if ($breakOnError) { + if ($allSchemasEmpty) { + out += ' if (true) { '; + } else { + out += ' ' + ($closingBraces.slice(0, -1)) + ' '; + } + } + return out; +} + +},{}],18:[function(require,module,exports){ +'use strict'; +module.exports = function generate_anyOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $noEmptySchema = $schema.every(function($sch) { + return (it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)); + }); + if ($noEmptySchema) { + var $currentBaseId = $it.baseId; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { '; + $closingBraces += '}'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should match some schema in anyOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} + +},{}],19:[function(require,module,exports){ +'use strict'; +module.exports = function generate_comment(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $comment = it.util.toQuotedString($schema); + if (it.opts.$comment === true) { + out += ' console.log(' + ($comment) + ');'; + } else if (typeof it.opts.$comment == 'function') { + out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);'; + } + return out; +} + +},{}],20:[function(require,module,exports){ +'use strict'; +module.exports = function generate_const(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!$isData) { + out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to constant\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],21:[function(require,module,exports){ +'use strict'; +module.exports = function generate_contains(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId, + $nonEmptySchema = (it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all)); + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($nonEmptySchema) { + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (' + ($nextValid) + ') break; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {'; + } else { + out += ' if (' + ($data) + '.length == 0) {'; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should contain a valid item\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + if ($nonEmptySchema) { + out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + } + if (it.opts.allErrors) { + out += ' } '; + } + return out; +} + +},{}],22:[function(require,module,exports){ +'use strict'; +module.exports = function generate_custom(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $rule = this, + $definition = 'definition' + $lvl, + $rDef = $rule.definition, + $closingBraces = ''; + var $compile, $inline, $macro, $ruleValidate, $validateCode; + if ($isData && $rDef.$data) { + $validateCode = 'keywordValidate' + $lvl; + var $validateSchema = $rDef.validateSchema; + out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;'; + } else { + $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); + if (!$ruleValidate) return; + $schemaValue = 'validate.schema' + $schemaPath; + $validateCode = $ruleValidate.code; + $compile = $rDef.compile; + $inline = $rDef.inline; + $macro = $rDef.macro; + } + var $ruleErrs = $validateCode + '.errors', + $i = 'i' + $lvl, + $ruleErr = 'ruleErr' + $lvl, + $asyncKeyword = $rDef.async; + if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); + if (!($inline || $macro)) { + out += '' + ($ruleErrs) + ' = null;'; + } + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($isData && $rDef.$data) { + $closingBraces += '}'; + out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { '; + if ($validateSchema) { + $closingBraces += '}'; + out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { '; + } + } + if ($inline) { + if ($rDef.statements) { + out += ' ' + ($ruleValidate.validate) + ' '; + } else { + out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; '; + } + } else if ($macro) { + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $ruleValidate.validate; + $it.schemaPath = ''; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($code); + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + out += ' ' + ($validateCode) + '.call( '; + if (it.opts.passContext) { + out += 'this'; + } else { + out += 'self'; + } + if ($compile || $rDef.schema === false) { + out += ' , ' + ($data) + ' '; + } else { + out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' '; + } + out += ' , (dataPath || \'\')'; + if (it.errorPath != '""') { + out += ' + ' + (it.errorPath); + } + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) '; + var def_callRuleValidate = out; + out = $$outStack.pop(); + if ($rDef.errors === false) { + out += ' ' + ($valid) + ' = '; + if ($asyncKeyword) { + out += 'await '; + } + out += '' + (def_callRuleValidate) + '; '; + } else { + if ($asyncKeyword) { + $ruleErrs = 'customErrors' + $lvl; + out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } '; + } else { + out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; '; + } + } + } + if ($rDef.modifying) { + out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; + } + out += '' + ($closingBraces); + if ($rDef.valid) { + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + out += ' if ( '; + if ($rDef.valid === undefined) { + out += ' !'; + if ($macro) { + out += '' + ($nextValid); + } else { + out += '' + ($valid); + } + } else { + out += ' ' + (!$rDef.valid) + ' '; + } + out += ') { '; + $errorKeyword = $rule.keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + var def_customError = out; + out = $$outStack.pop(); + if ($inline) { + if ($rDef.errors) { + if ($rDef.errors != 'full') { + out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + ' 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; + } + out += ') { '; + $it.schema = $sch; + $it.schemaPath = $schemaPath + it.util.getProperty($property); + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property); + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} + +},{}],24:[function(require,module,exports){ +'use strict'; +module.exports = function generate_enum(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $i = 'i' + $lvl, + $vSchema = 'schema' + $lvl; + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ';'; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }'; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to one of the allowed values\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],25:[function(require,module,exports){ +'use strict'; +module.exports = function generate_format(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + if (it.opts.format === false) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $unknownFormats = it.opts.unknownFormats, + $allowUnknown = Array.isArray($unknownFormats); + if ($isData) { + var $format = 'format' + $lvl, + $isObject = 'isObject' + $lvl, + $formatType = 'formatType' + $lvl; + out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { '; + if (it.async) { + out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; '; + } + out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' ('; + if ($unknownFormats != 'ignore') { + out += ' (' + ($schemaValue) + ' && !' + ($format) + ' '; + if ($allowUnknown) { + out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 '; + } + out += ') || '; + } + out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? '; + if (it.async) { + out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) '; + } else { + out += ' ' + ($format) + '(' + ($data) + ') '; + } + out += ' : ' + ($format) + '.test(' + ($data) + '))))) {'; + } else { + var $format = it.formats[$schema]; + if (!$format) { + if ($unknownFormats == 'ignore') { + it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } else { + throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); + } + } + var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate; + var $formatType = $isObject && $format.type || 'string'; + if ($isObject) { + var $async = $format.async === true; + $format = $format.validate; + } + if ($formatType != $ruleType) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + if ($async) { + if (!it.async) throw new Error('async format in sync schema'); + var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; + out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { '; + } else { + out += ' if (! '; + var $formatRef = 'formats' + it.util.getProperty($schema); + if ($isObject) $formatRef += '.validate'; + if (typeof $format == 'function') { + out += ' ' + ($formatRef) + '(' + ($data) + ') '; + } else { + out += ' ' + ($formatRef) + '.test(' + ($data) + ') '; + } + out += ') { '; + } + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match format "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],26:[function(require,module,exports){ +'use strict'; +module.exports = function generate_if(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + var $thenSch = it.schema['then'], + $elseSch = it.schema['else'], + $thenPresent = $thenSch !== undefined && (it.opts.strictKeywords ? (typeof $thenSch == 'object' && Object.keys($thenSch).length > 0) || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)), + $elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? (typeof $elseSch == 'object' && Object.keys($elseSch).length > 0) || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)), + $currentBaseId = $it.baseId; + if ($thenPresent || $elsePresent) { + var $ifClause; + $it.createErrors = false; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + $it.createErrors = true; + out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + if ($thenPresent) { + out += ' if (' + ($nextValid) + ') { '; + $it.schema = it.schema['then']; + $it.schemaPath = it.schemaPath + '.then'; + $it.errSchemaPath = it.errSchemaPath + '/then'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + ($ifClause) + ' = \'then\'; '; + } else { + $ifClause = '\'then\''; + } + out += ' } '; + if ($elsePresent) { + out += ' else { '; + } + } else { + out += ' if (!' + ($nextValid) + ') { '; + } + if ($elsePresent) { + $it.schema = it.schema['else']; + $it.schemaPath = it.schemaPath + '.else'; + $it.errSchemaPath = it.errSchemaPath + '/else'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + ($ifClause) + ' = \'else\'; '; + } else { + $ifClause = '\'else\''; + } + out += ' } '; + } + out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} + +},{}],27:[function(require,module,exports){ +'use strict'; + +//all requires must be explicit because browserify won't work with dynamic requires +module.exports = { + '$ref': require('./ref'), + allOf: require('./allOf'), + anyOf: require('./anyOf'), + '$comment': require('./comment'), + const: require('./const'), + contains: require('./contains'), + dependencies: require('./dependencies'), + 'enum': require('./enum'), + format: require('./format'), + 'if': require('./if'), + items: require('./items'), + maximum: require('./_limit'), + minimum: require('./_limit'), + maxItems: require('./_limitItems'), + minItems: require('./_limitItems'), + maxLength: require('./_limitLength'), + minLength: require('./_limitLength'), + maxProperties: require('./_limitProperties'), + minProperties: require('./_limitProperties'), + multipleOf: require('./multipleOf'), + not: require('./not'), + oneOf: require('./oneOf'), + pattern: require('./pattern'), + properties: require('./properties'), + propertyNames: require('./propertyNames'), + required: require('./required'), + uniqueItems: require('./uniqueItems'), + validate: require('./validate') +}; + +},{"./_limit":13,"./_limitItems":14,"./_limitLength":15,"./_limitProperties":16,"./allOf":17,"./anyOf":18,"./comment":19,"./const":20,"./contains":21,"./dependencies":23,"./enum":24,"./format":25,"./if":26,"./items":28,"./multipleOf":29,"./not":30,"./oneOf":31,"./pattern":32,"./properties":33,"./propertyNames":34,"./ref":35,"./required":36,"./uniqueItems":37,"./validate":38}],28:[function(require,module,exports){ +'use strict'; +module.exports = function generate_items(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId; + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if (Array.isArray($schema)) { + var $additionalItems = it.schema.additionalItems; + if ($additionalItems === false) { + out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { '; + var $passData = $data + '[' + $i + ']'; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); + $it.dataPathArr[$dataNxt] = $i; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? (typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0) || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) { + $it.schema = $additionalItems; + $it.schemaPath = it.schemaPath + '.additionalItems'; + $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } else if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' }'; + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} + +},{}],29:[function(require,module,exports){ +'use strict'; +module.exports = function generate_multipleOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + out += 'var division' + ($lvl) + ';if ('; + if ($isData) { + out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || '; + } + out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', '; + if (it.opts.multipleOfPrecision) { + out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' '; + } else { + out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') '; + } + out += ' ) '; + if ($isData) { + out += ' ) '; + } + out += ' ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be multiple of '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schemaValue) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],30:[function(require,module,exports){ +'use strict'; +module.exports = function generate_not(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.createErrors = false; + var $allErrorsOption; + if ($it.opts.allErrors) { + $allErrorsOption = $it.opts.allErrors; + $it.opts.allErrors = false; + } + out += ' ' + (it.validate($it)) + ' '; + $it.createErrors = true; + if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (' + ($nextValid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + out += ' var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if ($breakOnError) { + out += ' if (false) { '; + } + } + return out; +} + +},{}],31:[function(require,module,exports){ +'use strict'; +module.exports = function generate_oneOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $prevValid = 'prevValid' + $lvl, + $passingSchemas = 'passingSchemas' + $lvl; + out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } else { + out += ' var ' + ($nextValid) + ' = true; '; + } + if ($i) { + out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { '; + $closingBraces += '}'; + } + out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match exactly one schema in oneOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }'; + if (it.opts.allErrors) { + out += ' } '; + } + return out; +} + +},{}],32:[function(require,module,exports){ +'use strict'; +module.exports = function generate_pattern(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $regExpCode = it.opts.regExp ? 'regExp' : 'new RegExp'; + if ($isData) { + out += ' var ' + ($valid) + ' = true; try { ' + ($valid) + ' = ' + ($regExpCode) + '(' + ($schemaValue) + ').test(' + ($data) + '); } catch(e) { ' + ($valid) + ' = false; } if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' !' + ($valid) + ') {'; + } else { + var $regexp = it.usePattern($schema); + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' !' + ($regexp) + '.test(' + ($data) + ') ) {'; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match pattern "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],33:[function(require,module,exports){ +'use strict'; +module.exports = function generate_properties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl; + var $schemaKeys = Object.keys($schema || {}).filter(notProto), + $pProperties = it.schema.patternProperties || {}, + $pPropertyKeys = Object.keys($pProperties).filter(notProto), + $aProperties = it.schema.additionalProperties, + $someProperties = $schemaKeys.length || $pPropertyKeys.length, + $noAdditional = $aProperties === false, + $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length, + $removeAdditional = it.opts.removeAdditional, + $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + var $required = it.schema.required; + if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) { + var $requiredHash = it.util.toHash($required); + } + + function notProto(p) { + return p !== '__proto__'; + } + out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined;'; + } + if ($checkAdditional) { + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + if ($someProperties) { + out += ' var isAdditional' + ($lvl) + ' = !(false '; + if ($schemaKeys.length) { + if ($schemaKeys.length > 8) { + out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') '; + } else { + var arr1 = $schemaKeys; + if (arr1) { + var $propertyKey, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $propertyKey = arr1[i1 += 1]; + out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' '; + } + } + } + } + if ($pPropertyKeys.length) { + var arr2 = $pPropertyKeys; + if (arr2) { + var $pProperty, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $pProperty = arr2[$i += 1]; + out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') '; + } + } + } + out += ' ); if (isAdditional' + ($lvl) + ') { '; + } + if ($removeAdditional == 'all') { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + var $currentErrorPath = it.errorPath; + var $additionalProperty = '\' + ' + $key + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + } + if ($noAdditional) { + if ($removeAdditional) { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + out += ' ' + ($nextValid) + ' = false; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalProperties'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is an invalid additional property'; + } else { + out += 'should NOT have additional properties'; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + out += ' break; '; + } + } + } else if ($additionalIsSchema) { + if ($removeAdditional == 'failing') { + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + } else { + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + } + } + it.errorPath = $currentErrorPath; + } + if ($someProperties) { + out += ' } '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + var $useDefaults = it.opts.useDefaults && !it.compositeRule; + if ($schemaKeys.length) { + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + var $prop = it.util.getProperty($propertyKey), + $passData = $data + $prop, + $hasDefault = $useDefaults && $sch.default !== undefined; + $it.schema = $sch; + $it.schemaPath = $schemaPath + $prop; + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); + $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); + $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + $code = it.util.varReplace($code, $nextData, $passData); + var $useData = $passData; + } else { + var $useData = $nextData; + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; '; + } + if ($hasDefault) { + out += ' ' + ($code) + ' '; + } else { + if ($requiredHash && $requiredHash[$propertyKey]) { + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { ' + ($nextValid) + ' = false; '; + var $currentErrorPath = it.errorPath, + $currErrSchemaPath = $errSchemaPath, + $missingProperty = it.util.escapeQuotes($propertyKey); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + $errSchemaPath = it.errSchemaPath + '/required'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + it.errorPath = $currentErrorPath; + out += ' } else { '; + } else { + if ($breakOnError) { + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { ' + ($nextValid) + ' = true; } else { '; + } else { + out += ' if (' + ($useData) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ' ) { '; + } + } + out += ' ' + ($code) + ' } '; + } + } + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if ($pPropertyKeys.length) { + var arr4 = $pPropertyKeys; + if (arr4) { + var $pProperty, i4 = -1, + l4 = arr4.length - 1; + while (i4 < l4) { + $pProperty = arr4[i4 += 1]; + var $sch = $pProperties[$pProperty]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); + $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty); + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else ' + ($nextValid) + ' = true; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} + +},{}],34:[function(require,module,exports){ +'use strict'; +module.exports = function generate_propertyNames(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + out += 'var ' + ($errs) + ' = errors;'; + if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $i = 'i' + $lvl, + $invalidName = '\' + ' + $key + ' + \'', + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined; '; + } + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + out += ' var startErrs' + ($lvl) + ' = errors; '; + var $passData = $key; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + ' 0) || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) { + $required[$required.length] = $property; + } + } + } + } else { + var $required = $schema; + } + } + if ($isData || $required.length) { + var $currentErrorPath = it.errorPath, + $loopRequired = $isData || $required.length >= it.opts.loopRequired, + $ownProperties = it.opts.ownProperties; + if ($breakOnError) { + out += ' var missing' + ($lvl) + '; '; + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + out += ' var ' + ($valid) + ' = true; '; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; + } + out += '; if (!' + ($valid) + ') break; } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } else { + out += ' if ( '; + var arr2 = $required; + if (arr2) { + var $propertyKey, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $propertyKey = arr2[$i += 1]; + if ($i) { + out += ' || '; + } + var $prop = it.util.getProperty($propertyKey), + $useData = $data + $prop; + out += ' ( ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; + } + } + out += ') { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } + } else { + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + if ($isData) { + out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { '; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; + if ($isData) { + out += ' } '; + } + } else { + var arr3 = $required; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $prop = it.util.getProperty($propertyKey), + $missingProperty = it.util.escapeQuotes($propertyKey), + $useData = $data + $prop; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } + } + } + } + it.errorPath = $currentErrorPath; + } else if ($breakOnError) { + out += ' if (true) {'; + } + return out; +} + +},{}],37:[function(require,module,exports){ +'use strict'; +module.exports = function generate_uniqueItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (($schema || $isData) && it.opts.uniqueItems !== false) { + if ($isData) { + out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { '; + } + out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { '; + var $itemType = it.schema.items && it.schema.items.type, + $typeIsArray = Array.isArray($itemType); + if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) { + out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } '; + } else { + out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; '; + var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); + out += ' if (' + (it.util[$method]($itemType, 'item', it.opts.strictNumbers, true)) + ') continue; '; + if ($typeIsArray) { + out += ' if (typeof item == \'string\') item = \'"\' + item; '; + } + out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } '; + } + out += ' } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} + +},{}],38:[function(require,module,exports){ +'use strict'; +module.exports = function generate_validate(it, $keyword, $ruleType) { + var out = ''; + var $async = it.schema.$async === true, + $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'), + $id = it.self._getId(it.schema); + if (it.opts.strictKeywords) { + var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords); + if ($unknownKwd) { + var $keywordsMsg = 'unknown keyword: ' + $unknownKwd; + if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg); + else throw new Error($keywordsMsg); + } + } + if (it.isTop) { + out += ' var validate = '; + if ($async) { + it.async = true; + out += 'async '; + } + out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; '; + if ($id && (it.opts.sourceCode || it.opts.processCode)) { + out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' '; + } + } + if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) { + var $keyword = 'false schema'; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + if (it.schema === false) { + if (it.isTop) { + $breakOnError = true; + } else { + out += ' var ' + ($valid) + ' = false; '; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'boolean schema is false\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } else { + if (it.isTop) { + if ($async) { + out += ' return data; '; + } else { + out += ' validate.errors = null; return true; '; + } + } else { + out += ' var ' + ($valid) + ' = true; '; + } + } + if (it.isTop) { + out += ' }; return validate; '; + } + return out; + } + if (it.isTop) { + var $top = it.isTop, + $lvl = it.level = 0, + $dataLvl = it.dataLevel = 0, + $data = 'data'; + it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); + it.baseId = it.baseId || it.rootId; + delete it.isTop; + it.dataPathArr = [""]; + if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored in the schema root'; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + out += ' var vErrors = null; '; + out += ' var errors = 0; '; + out += ' if (rootData === undefined) rootData = data; '; + } else { + var $lvl = it.level, + $dataLvl = it.dataLevel, + $data = 'data' + ($dataLvl || ''); + if ($id) it.baseId = it.resolve.url(it.baseId, $id); + if ($async && !it.async) throw new Error('async schema in sync schema'); + out += ' var errs_' + ($lvl) + ' = errors;'; + } + var $valid = 'valid' + $lvl, + $breakOnError = !it.opts.allErrors, + $closingBraces1 = '', + $closingBraces2 = ''; + var $errorKeyword; + var $typeSchema = it.schema.type, + $typeIsArray = Array.isArray($typeSchema); + if ($typeSchema && it.opts.nullable && it.schema.nullable === true) { + if ($typeIsArray) { + if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null'); + } else if ($typeSchema != 'null') { + $typeSchema = [$typeSchema, 'null']; + $typeIsArray = true; + } + } + if ($typeIsArray && $typeSchema.length == 1) { + $typeSchema = $typeSchema[0]; + $typeIsArray = false; + } + if (it.schema.$ref && $refKeywords) { + if (it.opts.extendRefs == 'fail') { + throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); + } else if (it.opts.extendRefs !== true) { + $refKeywords = false; + it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); + } + } + if (it.schema.$comment && it.opts.$comment) { + out += ' ' + (it.RULES.all.$comment.code(it, '$comment')); + } + if ($typeSchema) { + if (it.opts.coerceTypes) { + var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); + } + var $rulesGroup = it.RULES.types[$typeSchema]; + if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) { + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type', + $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; + out += ' if (' + (it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true)) + ') { '; + if ($coerceToTypes) { + var $dataType = 'dataType' + $lvl, + $coerced = 'coerced' + $lvl; + out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; var ' + ($coerced) + ' = undefined; '; + if (it.opts.coerceTypes == 'array') { + out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ') && ' + ($data) + '.length == 1) { ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; if (' + (it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)) + ') ' + ($coerced) + ' = ' + ($data) + '; } '; + } + out += ' if (' + ($coerced) + ' !== undefined) ; '; + var arr1 = $coerceToTypes; + if (arr1) { + var $type, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $type = arr1[$i += 1]; + if ($type == 'string') { + out += ' else if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; '; + } else if ($type == 'number' || $type == 'integer') { + out += ' else if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' '; + if ($type == 'integer') { + out += ' && !(' + ($data) + ' % 1)'; + } + out += ')) ' + ($coerced) + ' = +' + ($data) + '; '; + } else if ($type == 'boolean') { + out += ' else if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; '; + } else if ($type == 'null') { + out += ' else if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; '; + } else if (it.opts.coerceTypes == 'array' && $type == 'array') { + out += ' else if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; '; + } + } + } + out += ' else { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } if (' + ($coerced) + ' !== undefined) { '; + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' ' + ($data) + ' = ' + ($coerced) + '; '; + if (!$dataLvl) { + out += 'if (' + ($parentData) + ' !== undefined)'; + } + out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } '; + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } + out += ' } '; + } + } + if (it.schema.$ref && !$refKeywords) { + out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' '; + if ($breakOnError) { + out += ' } if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } else { + var arr2 = it.RULES; + if (arr2) { + var $rulesGroup, i2 = -1, + l2 = arr2.length - 1; + while (i2 < l2) { + $rulesGroup = arr2[i2 += 1]; + if ($shouldUseGroup($rulesGroup)) { + if ($rulesGroup.type) { + out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers)) + ') { '; + } + if (it.opts.useDefaults) { + if ($rulesGroup.type == 'object' && it.schema.properties) { + var $schema = it.schema.properties, + $schemaKeys = Object.keys($schema); + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ($sch.default !== undefined) { + var $passData = $data + it.util.getProperty($propertyKey); + if (it.compositeRule) { + if (it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored for: ' + $passData; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + } else { + out += ' if (' + ($passData) + ' === undefined '; + if (it.opts.useDefaults == 'empty') { + out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; + } + out += ' ) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } + } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) { + var arr4 = it.schema.items; + if (arr4) { + var $sch, $i = -1, + l4 = arr4.length - 1; + while ($i < l4) { + $sch = arr4[$i += 1]; + if ($sch.default !== undefined) { + var $passData = $data + '[' + $i + ']'; + if (it.compositeRule) { + if (it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored for: ' + $passData; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + } else { + out += ' if (' + ($passData) + ' === undefined '; + if (it.opts.useDefaults == 'empty') { + out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; + } + out += ' ) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } + } + } + var arr5 = $rulesGroup.rules; + if (arr5) { + var $rule, i5 = -1, + l5 = arr5.length - 1; + while (i5 < l5) { + $rule = arr5[i5 += 1]; + if ($shouldUseRule($rule)) { + var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); + if ($code) { + out += ' ' + ($code) + ' '; + if ($breakOnError) { + $closingBraces1 += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces1) + ' '; + $closingBraces1 = ''; + } + if ($rulesGroup.type) { + out += ' } '; + if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { + out += ' else { '; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + } + } + if ($breakOnError) { + out += ' if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces2) + ' '; + } + if ($top) { + if ($async) { + out += ' if (errors === 0) return data; '; + out += ' else throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; '; + out += ' return errors === 0; '; + } + out += ' }; return validate;'; + } else { + out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';'; + } + + function $shouldUseGroup($rulesGroup) { + var rules = $rulesGroup.rules; + for (var i = 0; i < rules.length; i++) + if ($shouldUseRule(rules[i])) return true; + } + + function $shouldUseRule($rule) { + return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule)); + } + + function $ruleImplementsSomeKeyword($rule) { + var impl = $rule.implements; + for (var i = 0; i < impl.length; i++) + if (it.schema[impl[i]] !== undefined) return true; + } + return out; +} + +},{}],39:[function(require,module,exports){ +'use strict'; + +var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i; +var customRuleCode = require('./dotjs/custom'); +var definitionSchema = require('./definition_schema'); + +module.exports = { + add: addKeyword, + get: getKeyword, + remove: removeKeyword, + validate: validateKeyword +}; + + +/** + * Define custom keyword + * @this Ajv + * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords). + * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. + * @return {Ajv} this for method chaining + */ +function addKeyword(keyword, definition) { + /* jshint validthis: true */ + /* eslint no-shadow: 0 */ + var RULES = this.RULES; + if (RULES.keywords[keyword]) + throw new Error('Keyword ' + keyword + ' is already defined'); + + if (!IDENTIFIER.test(keyword)) + throw new Error('Keyword ' + keyword + ' is not a valid identifier'); + + if (definition) { + this.validateKeyword(definition, true); + + var dataType = definition.type; + if (Array.isArray(dataType)) { + for (var i=0; i 1) { + sets[0] = sets[0].slice(0, -1); + var xl = sets.length - 1; + for (var x = 1; x < xl; ++x) { + sets[x] = sets[x].slice(1, -1); + } + sets[xl] = sets[xl].slice(1); + return sets.join(''); + } else { + return sets[0]; + } +} +function subexp(str) { + return "(?:" + str + ")"; +} +function typeOf(o) { + return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase(); +} +function toUpperCase(str) { + return str.toUpperCase(); +} +function toArray(obj) { + return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : []; +} +function assign(target, source) { + var obj = target; + if (source) { + for (var key in source) { + obj[key] = source[key]; + } + } + return obj; +} + +function buildExps(isIRI) { + var ALPHA$$ = "[A-Za-z]", + CR$ = "[\\x0D]", + DIGIT$$ = "[0-9]", + DQUOTE$$ = "[\\x22]", + HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"), + //case-insensitive + LF$$ = "[\\x0A]", + SP$$ = "[\\x20]", + PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)), + //expanded + GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", + SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", + RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), + UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", + //subset, excludes bidi control characters + IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", + //subset + UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$), + SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"), + USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"), + DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$), + DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), + //relaxed parsing rules + IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), + H16$ = subexp(HEXDIG$$ + "{1,4}"), + LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), + IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), + // 6( h16 ":" ) ls32 + IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), + // "::" 5( h16 ":" ) ls32 + IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), + //[ h16 ] "::" 4( h16 ":" ) ls32 + IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), + //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), + //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), + //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), + //[ *4( h16 ":" ) h16 ] "::" ls32 + IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), + //[ *5( h16 ":" ) h16 ] "::" h16 + IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), + //[ *6( h16 ":" ) h16 ] "::" + IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), + ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"), + //RFC 6874 + IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$), + //RFC 6874 + IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$), + //RFC 6874, with relaxed parsing rules + IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"), + IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"), + //RFC 6874 + REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"), + HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$), + PORT$ = subexp(DIGIT$$ + "*"), + AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"), + PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")), + SEGMENT$ = subexp(PCHAR$ + "*"), + SEGMENT_NZ$ = subexp(PCHAR$ + "+"), + SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"), + PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"), + PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"), + //simplified + PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), + //simplified + PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), + //simplified + PATH_EMPTY$ = "(?!" + PCHAR$ + ")", + PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), + QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"), + FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"), + HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), + URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), + RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$), + RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), + URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$), + ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"), + GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$", + SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$"; + return { + NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"), + NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"), + NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"), + ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"), + UNRESERVED: new RegExp(UNRESERVED$$, "g"), + OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"), + PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"), + IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"), + IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules + }; +} +var URI_PROTOCOL = buildExps(false); + +var IRI_PROTOCOL = buildExps(true); + +var slicedToArray = function () { + function sliceIterator(arr, i) { + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"]) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; + } + + return function (arr, i) { + if (Array.isArray(arr)) { + return arr; + } else if (Symbol.iterator in Object(arr)) { + return sliceIterator(arr, i); + } else { + throw new TypeError("Invalid attempt to destructure non-iterable instance"); + } + }; +}(); + + + + + + + + + + + + + +var toConsumableArray = function (arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } else { + return Array.from(arr); + } +}; + +/** Highest positive signed 32-bit float value */ + +var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +var base = 36; +var tMin = 1; +var tMax = 26; +var skew = 38; +var damp = 700; +var initialBias = 72; +var initialN = 128; // 0x80 +var delimiter = '-'; // '\x2D' + +/** Regular expressions */ +var regexPunycode = /^xn--/; +var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars +var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +var errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +var baseMinusTMin = base - tMin; +var floor = Math.floor; +var stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error$1(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, fn) { + var result = []; + var length = array.length; + while (length--) { + result[length] = fn(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ +function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + var output = []; + var counter = 0; + var length = string.length; + while (counter < length) { + var value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + var extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { + // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +var ucs2encode = function ucs2encode(array) { + return String.fromCodePoint.apply(String, toConsumableArray(array)); +}; + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +var basicToDigit = function basicToDigit(codePoint) { + if (codePoint - 0x30 < 0x0A) { + return codePoint - 0x16; + } + if (codePoint - 0x41 < 0x1A) { + return codePoint - 0x41; + } + if (codePoint - 0x61 < 0x1A) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +var digitToBasic = function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +var adapt = function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +var decode = function decode(input) { + // Don't use UCS-2. + var output = []; + var inputLength = input.length; + var i = 0; + var n = initialN; + var bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + var basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (var j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error$1('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{ + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + var oldi = i; + for (var w = 1, k = base;; /* no condition */k += base) { + + if (index >= inputLength) { + error$1('invalid-input'); + } + + var digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error$1('overflow'); + } + + i += digit * w; + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + + if (digit < t) { + break; + } + + var baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error$1('overflow'); + } + + w *= baseMinusT; + } + + var out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error$1('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + } + + return String.fromCodePoint.apply(String, output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +var encode = function encode(input) { + var output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + var inputLength = input.length; + + // Initialize the state. + var n = initialN; + var delta = 0; + var bias = initialBias; + + // Handle the basic code points. + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _currentValue2 = _step.value; + + if (_currentValue2 < 0x80) { + output.push(stringFromCharCode(_currentValue2)); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var basicLength = output.length; + var handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + var m = maxInt; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var currentValue = _step2.value; + + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + var handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error$1('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _currentValue = _step3.value; + + if (_currentValue < n && ++delta > maxInt) { + error$1('overflow'); + } + if (_currentValue == n) { + // Represent delta as a generalized variable-length integer. + var q = delta; + for (var k = base;; /* no condition */k += base) { + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (q < t) { + break; + } + var qMinusT = q - t; + var baseMinusT = base - t; + output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + ++delta; + ++n; + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +var toUnicode = function toUnicode(input) { + return mapDomain(input, function (string) { + return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +var toASCII = function toASCII(input) { + return mapDomain(input, function (string) { + return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +var punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.1.0', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +/** + * URI.js + * + * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript. + * @author Gary Court + * @see http://github.com/garycourt/uri-js + */ +/** + * Copyright 2011 Gary Court. 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 GARY COURT ``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 GARY COURT 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of Gary Court. + */ +var SCHEMES = {}; +function pctEncChar(chr) { + var c = chr.charCodeAt(0); + var e = void 0; + if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase(); + return e; +} +function pctDecChars(str) { + var newStr = ""; + var i = 0; + var il = str.length; + while (i < il) { + var c = parseInt(str.substr(i + 1, 2), 16); + if (c < 128) { + newStr += String.fromCharCode(c); + i += 3; + } else if (c >= 194 && c < 224) { + if (il - i >= 6) { + var c2 = parseInt(str.substr(i + 4, 2), 16); + newStr += String.fromCharCode((c & 31) << 6 | c2 & 63); + } else { + newStr += str.substr(i, 6); + } + i += 6; + } else if (c >= 224) { + if (il - i >= 9) { + var _c = parseInt(str.substr(i + 4, 2), 16); + var c3 = parseInt(str.substr(i + 7, 2), 16); + newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63); + } else { + newStr += str.substr(i, 9); + } + i += 9; + } else { + newStr += str.substr(i, 3); + i += 3; + } + } + return newStr; +} +function _normalizeComponentEncoding(components, protocol) { + function decodeUnreserved(str) { + var decStr = pctDecChars(str); + return !decStr.match(protocol.UNRESERVED) ? str : decStr; + } + if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, ""); + if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + return components; +} + +function _stripLeadingZeros(str) { + return str.replace(/^0*(.*)/, "$1") || "0"; +} +function _normalizeIPv4(host, protocol) { + var matches = host.match(protocol.IPV4ADDRESS) || []; + + var _matches = slicedToArray(matches, 2), + address = _matches[1]; + + if (address) { + return address.split(".").map(_stripLeadingZeros).join("."); + } else { + return host; + } +} +function _normalizeIPv6(host, protocol) { + var matches = host.match(protocol.IPV6ADDRESS) || []; + + var _matches2 = slicedToArray(matches, 3), + address = _matches2[1], + zone = _matches2[2]; + + if (address) { + var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(), + _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), + last = _address$toLowerCase$2[0], + first = _address$toLowerCase$2[1]; + + var firstFields = first ? first.split(":").map(_stripLeadingZeros) : []; + var lastFields = last.split(":").map(_stripLeadingZeros); + var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]); + var fieldCount = isLastFieldIPv4Address ? 7 : 8; + var lastFieldsStart = lastFields.length - fieldCount; + var fields = Array(fieldCount); + for (var x = 0; x < fieldCount; ++x) { + fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || ''; + } + if (isLastFieldIPv4Address) { + fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol); + } + var allZeroFields = fields.reduce(function (acc, field, index) { + if (!field || field === "0") { + var lastLongest = acc[acc.length - 1]; + if (lastLongest && lastLongest.index + lastLongest.length === index) { + lastLongest.length++; + } else { + acc.push({ index: index, length: 1 }); + } + } + return acc; + }, []); + var longestZeroFields = allZeroFields.sort(function (a, b) { + return b.length - a.length; + })[0]; + var newHost = void 0; + if (longestZeroFields && longestZeroFields.length > 1) { + var newFirst = fields.slice(0, longestZeroFields.index); + var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length); + newHost = newFirst.join(":") + "::" + newLast.join(":"); + } else { + newHost = fields.join(":"); + } + if (zone) { + newHost += "%" + zone; + } + return newHost; + } else { + return host; + } +} +var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i; +var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined; +function parse(uriString) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var components = {}; + var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; + if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString; + var matches = uriString.match(URI_PARSE); + if (matches) { + if (NO_MATCH_IS_UNDEFINED) { + //store each component + components.scheme = matches[1]; + components.userinfo = matches[3]; + components.host = matches[4]; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = matches[7]; + components.fragment = matches[8]; + //fix port number + if (isNaN(components.port)) { + components.port = matches[5]; + } + } else { + //IE FIX for improper RegExp matching + //store each component + components.scheme = matches[1] || undefined; + components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined; + components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined; + components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined; + //fix port number + if (isNaN(components.port)) { + components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined; + } + } + if (components.host) { + //normalize IP hosts + components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol); + } + //determine reference type + if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) { + components.reference = "same-document"; + } else if (components.scheme === undefined) { + components.reference = "relative"; + } else if (components.fragment === undefined) { + components.reference = "absolute"; + } else { + components.reference = "uri"; + } + //check for reference errors + if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) { + components.error = components.error || "URI is not a " + options.reference + " reference."; + } + //find scheme handler + var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //check if scheme can't handle IRIs + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + //if host component is a domain name + if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) { + //convert Unicode IDN -> ASCII IDN + try { + components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()); + } catch (e) { + components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e; + } + } + //convert IRI -> URI + _normalizeComponentEncoding(components, URI_PROTOCOL); + } else { + //normalize encodings + _normalizeComponentEncoding(components, protocol); + } + //perform scheme specific parsing + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(components, options); + } + } else { + components.error = components.error || "URI can not be parsed."; + } + return components; +} + +function _recomposeAuthority(components, options) { + var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; + var uriTokens = []; + if (components.userinfo !== undefined) { + uriTokens.push(components.userinfo); + uriTokens.push("@"); + } + if (components.host !== undefined) { + //normalize IP hosts, add brackets and escape zone separator for IPv6 + uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) { + return "[" + $1 + ($2 ? "%25" + $2 : "") + "]"; + })); + } + if (typeof components.port === "number" || typeof components.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(components.port)); + } + return uriTokens.length ? uriTokens.join("") : undefined; +} + +var RDS1 = /^\.\.?\//; +var RDS2 = /^\/\.(\/|$)/; +var RDS3 = /^\/\.\.(\/|$)/; +var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/; +function removeDotSegments(input) { + var output = []; + while (input.length) { + if (input.match(RDS1)) { + input = input.replace(RDS1, ""); + } else if (input.match(RDS2)) { + input = input.replace(RDS2, "/"); + } else if (input.match(RDS3)) { + input = input.replace(RDS3, "/"); + output.pop(); + } else if (input === "." || input === "..") { + input = ""; + } else { + var im = input.match(RDS5); + if (im) { + var s = im[0]; + input = input.slice(s.length); + output.push(s); + } else { + throw new Error("Unexpected dot segment condition"); + } + } + } + return output.join(""); +} + +function serialize(components) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL; + var uriTokens = []; + //find scheme handler + var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //perform scheme specific serialization + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options); + if (components.host) { + //if host component is an IPv6 address + if (protocol.IPV6ADDRESS.test(components.host)) {} + //TODO: normalize IPv6 address as per RFC 5952 + + //if host component is a domain name + else if (options.domainHost || schemeHandler && schemeHandler.domainHost) { + //convert IDN via punycode + try { + components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host); + } catch (e) { + components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + } + } + //normalize encoding + _normalizeComponentEncoding(components, protocol); + if (options.reference !== "suffix" && components.scheme) { + uriTokens.push(components.scheme); + uriTokens.push(":"); + } + var authority = _recomposeAuthority(components, options); + if (authority !== undefined) { + if (options.reference !== "suffix") { + uriTokens.push("//"); + } + uriTokens.push(authority); + if (components.path && components.path.charAt(0) !== "/") { + uriTokens.push("/"); + } + } + if (components.path !== undefined) { + var s = components.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s = removeDotSegments(s); + } + if (authority === undefined) { + s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//" + } + uriTokens.push(s); + } + if (components.query !== undefined) { + uriTokens.push("?"); + uriTokens.push(components.query); + } + if (components.fragment !== undefined) { + uriTokens.push("#"); + uriTokens.push(components.fragment); + } + return uriTokens.join(""); //merge tokens into a string +} + +function resolveComponents(base, relative) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var skipNormalization = arguments[3]; + + var target = {}; + if (!skipNormalization) { + base = parse(serialize(base, options), options); //normalize base components + relative = parse(serialize(relative, options), options); //normalize relative components + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== undefined) { + target.query = relative.query; + } else { + target.query = base.query; + } + } else { + if (relative.path.charAt(0) === "/") { + target.path = removeDotSegments(relative.path); + } else { + if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { + target.path = "/" + relative.path; + } else if (!base.path) { + target.path = relative.path; + } else { + target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + } + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + //target.authority = base.authority; + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; +} + +function resolve(baseURI, relativeURI, options) { + var schemelessOptions = assign({ scheme: 'null' }, options); + return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions); +} + +function normalize(uri, options) { + if (typeof uri === "string") { + uri = serialize(parse(uri, options), options); + } else if (typeOf(uri) === "object") { + uri = parse(serialize(uri, options), options); + } + return uri; +} + +function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = serialize(parse(uriA, options), options); + } else if (typeOf(uriA) === "object") { + uriA = serialize(uriA, options); + } + if (typeof uriB === "string") { + uriB = serialize(parse(uriB, options), options); + } else if (typeOf(uriB) === "object") { + uriB = serialize(uriB, options); + } + return uriA === uriB; +} + +function escapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar); +} + +function unescapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars); +} + +var handler = { + scheme: "http", + domainHost: true, + parse: function parse(components, options) { + //report missing host + if (!components.host) { + components.error = components.error || "HTTP URIs must have a host."; + } + return components; + }, + serialize: function serialize(components, options) { + var secure = String(components.scheme).toLowerCase() === "https"; + //normalize the default port + if (components.port === (secure ? 443 : 80) || components.port === "") { + components.port = undefined; + } + //normalize the empty path + if (!components.path) { + components.path = "/"; + } + //NOTE: We do not parse query strings for HTTP URIs + //as WWW Form Url Encoded query strings are part of the HTML4+ spec, + //and not the HTTP spec. + return components; + } +}; + +var handler$1 = { + scheme: "https", + domainHost: handler.domainHost, + parse: handler.parse, + serialize: handler.serialize +}; + +function isSecure(wsComponents) { + return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss"; +} +//RFC 6455 +var handler$2 = { + scheme: "ws", + domainHost: true, + parse: function parse(components, options) { + var wsComponents = components; + //indicate if the secure flag is set + wsComponents.secure = isSecure(wsComponents); + //construct resouce name + wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : ''); + wsComponents.path = undefined; + wsComponents.query = undefined; + return wsComponents; + }, + serialize: function serialize(wsComponents, options) { + //normalize the default port + if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") { + wsComponents.port = undefined; + } + //ensure scheme matches secure flag + if (typeof wsComponents.secure === 'boolean') { + wsComponents.scheme = wsComponents.secure ? 'wss' : 'ws'; + wsComponents.secure = undefined; + } + //reconstruct path from resource name + if (wsComponents.resourceName) { + var _wsComponents$resourc = wsComponents.resourceName.split('?'), + _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), + path = _wsComponents$resourc2[0], + query = _wsComponents$resourc2[1]; + + wsComponents.path = path && path !== '/' ? path : undefined; + wsComponents.query = query; + wsComponents.resourceName = undefined; + } + //forbid fragment component + wsComponents.fragment = undefined; + return wsComponents; + } +}; + +var handler$3 = { + scheme: "wss", + domainHost: handler$2.domainHost, + parse: handler$2.parse, + serialize: handler$2.serialize +}; + +var O = {}; +var isIRI = true; +//RFC 3986 +var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]"; +var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive +var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded +//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; = +//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127) +//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext +//const VCHAR$$ = "[\\x21-\\x7E]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext +//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+"); +//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$); +//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"'); +var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]"; +var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]"; +var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]"); +var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"; +var UNRESERVED = new RegExp(UNRESERVED$$, "g"); +var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g"); +var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g"); +var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g"); +var NOT_HFVALUE = NOT_HFNAME; +function decodeUnreserved(str) { + var decStr = pctDecChars(str); + return !decStr.match(UNRESERVED) ? str : decStr; +} +var handler$4 = { + scheme: "mailto", + parse: function parse$$1(components, options) { + var mailtoComponents = components; + var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : []; + mailtoComponents.path = undefined; + if (mailtoComponents.query) { + var unknownHeaders = false; + var headers = {}; + var hfields = mailtoComponents.query.split("&"); + for (var x = 0, xl = hfields.length; x < xl; ++x) { + var hfield = hfields[x].split("="); + switch (hfield[0]) { + case "to": + var toAddrs = hfield[1].split(","); + for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) { + to.push(toAddrs[_x]); + } + break; + case "subject": + mailtoComponents.subject = unescapeComponent(hfield[1], options); + break; + case "body": + mailtoComponents.body = unescapeComponent(hfield[1], options); + break; + default: + unknownHeaders = true; + headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options); + break; + } + } + if (unknownHeaders) mailtoComponents.headers = headers; + } + mailtoComponents.query = undefined; + for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) { + var addr = to[_x2].split("@"); + addr[0] = unescapeComponent(addr[0]); + if (!options.unicodeSupport) { + //convert Unicode IDN -> ASCII IDN + try { + addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase()); + } catch (e) { + mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e; + } + } else { + addr[1] = unescapeComponent(addr[1], options).toLowerCase(); + } + to[_x2] = addr.join("@"); + } + return mailtoComponents; + }, + serialize: function serialize$$1(mailtoComponents, options) { + var components = mailtoComponents; + var to = toArray(mailtoComponents.to); + if (to) { + for (var x = 0, xl = to.length; x < xl; ++x) { + var toAddr = String(to[x]); + var atIdx = toAddr.lastIndexOf("@"); + var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar); + var domain = toAddr.slice(atIdx + 1); + //convert IDN via punycode + try { + domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain); + } catch (e) { + components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + to[x] = localPart + "@" + domain; + } + components.path = to.join(","); + } + var headers = mailtoComponents.headers = mailtoComponents.headers || {}; + if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject; + if (mailtoComponents.body) headers["body"] = mailtoComponents.body; + var fields = []; + for (var name in headers) { + if (headers[name] !== O[name]) { + fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)); + } + } + if (fields.length) { + components.query = fields.join("&"); + } + return components; + } +}; + +var URN_PARSE = /^([^\:]+)\:(.*)/; +//RFC 2141 +var handler$5 = { + scheme: "urn", + parse: function parse$$1(components, options) { + var matches = components.path && components.path.match(URN_PARSE); + var urnComponents = components; + if (matches) { + var scheme = options.scheme || urnComponents.scheme || "urn"; + var nid = matches[1].toLowerCase(); + var nss = matches[2]; + var urnScheme = scheme + ":" + (options.nid || nid); + var schemeHandler = SCHEMES[urnScheme]; + urnComponents.nid = nid; + urnComponents.nss = nss; + urnComponents.path = undefined; + if (schemeHandler) { + urnComponents = schemeHandler.parse(urnComponents, options); + } + } else { + urnComponents.error = urnComponents.error || "URN can not be parsed."; + } + return urnComponents; + }, + serialize: function serialize$$1(urnComponents, options) { + var scheme = options.scheme || urnComponents.scheme || "urn"; + var nid = urnComponents.nid; + var urnScheme = scheme + ":" + (options.nid || nid); + var schemeHandler = SCHEMES[urnScheme]; + if (schemeHandler) { + urnComponents = schemeHandler.serialize(urnComponents, options); + } + var uriComponents = urnComponents; + var nss = urnComponents.nss; + uriComponents.path = (nid || options.nid) + ":" + nss; + return uriComponents; + } +}; + +var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/; +//RFC 4122 +var handler$6 = { + scheme: "urn:uuid", + parse: function parse(urnComponents, options) { + var uuidComponents = urnComponents; + uuidComponents.uuid = uuidComponents.nss; + uuidComponents.nss = undefined; + if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) { + uuidComponents.error = uuidComponents.error || "UUID is not valid."; + } + return uuidComponents; + }, + serialize: function serialize(uuidComponents, options) { + var urnComponents = uuidComponents; + //normalize UUID + urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); + return urnComponents; + } +}; + +SCHEMES[handler.scheme] = handler; +SCHEMES[handler$1.scheme] = handler$1; +SCHEMES[handler$2.scheme] = handler$2; +SCHEMES[handler$3.scheme] = handler$3; +SCHEMES[handler$4.scheme] = handler$4; +SCHEMES[handler$5.scheme] = handler$5; +SCHEMES[handler$6.scheme] = handler$6; + +exports.SCHEMES = SCHEMES; +exports.pctEncChar = pctEncChar; +exports.pctDecChars = pctDecChars; +exports.parse = parse; +exports.removeDotSegments = removeDotSegments; +exports.serialize = serialize; +exports.resolveComponents = resolveComponents; +exports.resolve = resolve; +exports.normalize = normalize; +exports.equal = equal; +exports.escapeComponent = escapeComponent; +exports.unescapeComponent = unescapeComponent; + +Object.defineProperty(exports, '__esModule', { value: true }); + +}))); + + +},{}],"ajv":[function(require,module,exports){ +'use strict'; + +var compileSchema = require('./compile') + , resolve = require('./compile/resolve') + , Cache = require('./cache') + , SchemaObject = require('./compile/schema_obj') + , stableStringify = require('fast-json-stable-stringify') + , formats = require('./compile/formats') + , rules = require('./compile/rules') + , $dataMetaSchema = require('./data') + , util = require('./compile/util'); + +module.exports = Ajv; + +Ajv.prototype.validate = validate; +Ajv.prototype.compile = compile; +Ajv.prototype.addSchema = addSchema; +Ajv.prototype.addMetaSchema = addMetaSchema; +Ajv.prototype.validateSchema = validateSchema; +Ajv.prototype.getSchema = getSchema; +Ajv.prototype.removeSchema = removeSchema; +Ajv.prototype.addFormat = addFormat; +Ajv.prototype.errorsText = errorsText; + +Ajv.prototype._addSchema = _addSchema; +Ajv.prototype._compile = _compile; + +Ajv.prototype.compileAsync = require('./compile/async'); +var customKeyword = require('./keyword'); +Ajv.prototype.addKeyword = customKeyword.add; +Ajv.prototype.getKeyword = customKeyword.get; +Ajv.prototype.removeKeyword = customKeyword.remove; +Ajv.prototype.validateKeyword = customKeyword.validate; + +var errorClasses = require('./compile/error_classes'); +Ajv.ValidationError = errorClasses.Validation; +Ajv.MissingRefError = errorClasses.MissingRef; +Ajv.$dataMetaSchema = $dataMetaSchema; + +var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; + +var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ]; +var META_SUPPORT_DATA = ['/properties']; + +/** + * Creates validator instance. + * Usage: `Ajv(opts)` + * @param {Object} opts optional options + * @return {Object} ajv instance + */ +function Ajv(opts) { + if (!(this instanceof Ajv)) return new Ajv(opts); + opts = this._opts = util.copy(opts) || {}; + setLogger(this); + this._schemas = {}; + this._refs = {}; + this._fragments = {}; + this._formats = formats(opts.format); + + this._cache = opts.cache || new Cache; + this._loadingSchemas = {}; + this._compilations = []; + this.RULES = rules(); + this._getId = chooseGetId(opts); + + opts.loopRequired = opts.loopRequired || Infinity; + if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; + if (opts.serialize === undefined) opts.serialize = stableStringify; + this._metaOpts = getMetaSchemaOptions(this); + + if (opts.formats) addInitialFormats(this); + if (opts.keywords) addInitialKeywords(this); + addDefaultMetaSchema(this); + if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta); + if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}}); + addInitialSchemas(this); +} + + + +/** + * Validate data using schema + * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize. + * @this Ajv + * @param {String|Object} schemaKeyRef key, ref or schema object + * @param {Any} data to be validated + * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). + */ +function validate(schemaKeyRef, data) { + var v; + if (typeof schemaKeyRef == 'string') { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); + } else { + var schemaObj = this._addSchema(schemaKeyRef); + v = schemaObj.validate || this._compile(schemaObj); + } + + var valid = v(data); + if (v.$async !== true) this.errors = v.errors; + return valid; +} + + +/** + * Create validating function for passed schema. + * @this Ajv + * @param {Object} schema schema object + * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. + * @return {Function} validating function + */ +function compile(schema, _meta) { + var schemaObj = this._addSchema(schema, undefined, _meta); + return schemaObj.validate || this._compile(schemaObj); +} + + +/** + * Adds schema to the instance. + * @this Ajv + * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. + * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. + * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + * @return {Ajv} this for method chaining + */ +function addSchema(schema, key, _skipValidation, _meta) { + if (Array.isArray(schema)){ + for (var i=0; i} errors optional array of validation errors, if not passed errors from the instance are used. + * @param {Object} options optional options with properties `separator` and `dataVar`. + * @return {String} human readable string with all errors descriptions + */ +function errorsText(errors, options) { + errors = errors || this.errors; + if (!errors) return 'No errors'; + options = options || {}; + var separator = options.separator === undefined ? ', ' : options.separator; + var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; + + var text = ''; + for (var i=0; i{"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self,e())})(function(){return function a(s,o,i){function n(r,e){if(!o[r]){if(!s[r]){var t="function"==typeof require&&require;if(!e&&t)return t(r,!0);if(l)return l(r,!0);throw(e=new Error("Cannot find module '"+r+"'")).code="MODULE_NOT_FOUND",e}t=o[r]={exports:{}},s[r][0].call(t.exports,function(e){return n(s[r][1][e]||e)},t,t.exports,a,s,o,i)}return o[r].exports}for(var l="function"==typeof require&&require,e=0;e%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,c=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,u=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,h=/^(?:\/(?:[^~/]|~0|~1)*)*$/,d=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,p=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function f(e){return a.copy(f[e="full"==e?"full":"fast"])}function m(e){var r,t,e=e.match(s);return!!e&&(t=+e[3],1<=(r=+e[2]))&&r<=12&&1<=t&&t<=(2!=r||(t=+e[1])%4!=0||t%100==0&&t%400!=0?o[r]:29)}function v(e,r){var t,a,s,e=e.match(i);return!!e&&(a=e[2],s=e[3],(t=e[1])<=23&&a<=59&&s<=59||23==t&&59==a&&60==s)&&(!r||e[5])}(r.exports=f).fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":l,url:c,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,hostname:e,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:E,uuid:u,"json-pointer":h,"json-pointer-uri-fragment":d,"relative-json-pointer":p},f.full={date:m,time:v,"date-time":function(e){e=e.split(y);return 2==e.length&&m(e[0])&&v(e[1],!0)},uri:function(e){return g.test(e)&&n.test(e)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":l,url:c,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:e,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:E,uuid:u,"json-pointer":h,"json-pointer-uri-fragment":d,"relative-json-pointer":p};var y=/t|\s/i;var g=/\/|:/;var P=/[^\\]\\Z/;function E(e){if(P.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}}},{"./util":10}],5:[function(e,r,t){var $=e("./resolve"),j=e("./util"),D=e("./error_classes"),O=e("fast-json-stable-stringify"),I=e("../dotjs/validate"),A=j.ucs2length,k=e("fast-deep-equal"),C=D.Validation;function L(e,i,n,r){var l=this,c=this._opts,u=[void 0],h={},d=[],t={},p=[],a={},f=[];function m(e,r){return"var pattern"+e+" = "+(c.regExp?"regExp":"new RegExp")+"("+j.toQuotedString(r[e])+");"}i=i||{schema:e,refVal:u,refs:h};var s=function(e,r,t){var a=N.call(this,e,r,t);return 0<=a?{index:a,compiling:!0}:(this._compilations[a=this._compilations.length]={schema:e,root:r,baseId:t},{index:a,compiling:!1})}.call(this,e,i,r),o=this._compilations[s.index];if(s.compiling)return o.callValidate=E;var v=this._formats,y=this.RULES;try{var g=w(e,i,n,r),P=(o.validate=g,o.callValidate);return P&&(P.schema=g.schema,P.errors=null,P.refs=g.refs,P.refVal=g.refVal,P.root=g.root,P.$async=g.$async,c.sourceCode)&&(P.source=g.source),g}finally{!function(e,r,t){e=N.call(this,e,r,t);0<=e&&this._compilations.splice(e,1)}.call(this,e,i,r)}function E(){var e=o.validate,r=e.apply(this,arguments);return E.errors=e.errors,r}function w(e,r,t,a){var s=!r||r.schema==e;if(r.schema!=i.schema)return L.call(l,e,r,t,a);t=!0===e.$async,a=I({isTop:!0,schema:e,isRoot:s,baseId:a,root:r,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:D.MissingRef,RULES:y,validate:I,util:j,resolve:$,resolveRef:b,usePattern:F,useDefault:x,useCustomRule:R,opts:c,formats:v,logger:l.logger,self:l}),a=Q(u,q)+Q(d,m)+Q(p,z)+Q(f,T)+a;c.processCode&&(a=c.processCode(a,e));try{var o=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError","regExp",a)(l,y,v,i,u,p,f,k,A,C,c.regExp);u[0]=o}catch(e){throw l.logger.error("Error compiling schema, function code:",a),e}return o.schema=e,o.errors=null,o.refs=h,o.refVal=u,o.root=s?o:r,t&&(o.$async=!0),!0===c.sourceCode&&(o.source={code:a,patterns:d,defaults:p}),o}function b(e,r,t){r=$.url(e,r);var a=h[r];if(void 0!==a)return _(s=u[a],o="refVal["+a+"]");if(!t&&i.refs){a=i.refs[r];if(void 0!==a)return _(s=i.refVal[a],o=S(r,s))}var s,o=S(r),t=$.call(l,w,i,r);if(void 0!==(t=void 0===t&&(a=n&&n[r])?$.inlineRef(a,c.inlineRefs)?a:L.call(l,a,i,n,e):t))return s=t,u[h[r]]=s,_(t,o);delete h[r]}function S(e,r){var t=u.length;return u[t]=r,"refVal"+(h[e]=t)}function _(e,r){return"object"==typeof e||"boolean"==typeof e?{code:r,schema:e,inline:!0}:{code:r,$async:e&&!!e.$async}}function F(e){var r=t[e];return void 0===r&&(r=t[e]=d.length,d[r]=e),"pattern"+r}function x(e){switch(typeof e){case"boolean":case"number":return""+e;case"string":return j.toQuotedString(e);case"object":var r,t;return null===e?"null":(r=O(e),void 0===(t=a[r])&&(t=a[r]=p.length,p[t]=e),"default"+t)}}function R(e,r,t,a){if(!1!==l._opts.validateSchema){var s=e.definition.dependencies;if(s&&!s.every(function(e){return Object.prototype.hasOwnProperty.call(t,e)}))throw new Error("parent schema must have all required keywords: "+s.join(","));s=e.definition.validateSchema;if(s)if(!s(r)){s="keyword schema is invalid: "+l.errorsText(s.errors);if("log"!=l._opts.validateSchema)throw new Error(s);l.logger.error(s)}}var o,s=e.definition.compile,i=e.definition.inline,n=e.definition.macro;if(s)o=s.call(l,r,t,a);else if(n)o=n.call(l,r,t,a),!1!==c.validateSchema&&l.validateSchema(o,!0);else if(i)o=i.call(l,a,e.keyword,r,t);else if(!(o=e.definition.validate))return;if(void 0===o)throw new Error('custom keyword "'+e.keyword+'"failed to compile');s=f.length;return{code:"customRule"+s,validate:f[s]=o}}}function N(e,r,t){for(var a=0;a",S=g?">":"<",_=void 0;if(!v&&"number"!=typeof h&&void 0!==h)throw new Error(r+" must be number");if(!w&&void 0!==E&&"number"!=typeof E&&"boolean"!=typeof E)throw new Error(P+" must be number or boolean");w?(u=e.util.getData(E.$data,u,e.dataPathArr),o="exclIsNumber"+c,i="' + "+(n="op"+c)+" + '",_=P,(F=F||[]).push(l=l+(" var schemaExcl"+c+" = "+u+"; ")+(" var "+(a="exclusive"+c)+"; var "+(s="exclType"+c)+" = typeof "+(u="schemaExcl"+c)+"; if ("+s+" != 'boolean' && "+s+" != 'undefined' && "+s+" != 'number') { ")),l="",!1!==e.createErrors?(l+=" { keyword: '"+(_||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: {} ",!1!==e.opts.messages&&(l+=" , message: '"+P+" should be boolean' "),e.opts.verbose&&(l+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),l+=" } "):l+=" {} ",x=l,l=(l=F.pop())+(!e.compositeRule&&f?e.async?" throw new ValidationError(["+x+"]); ":" validate.errors = ["+x+"]; return false; ":" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+" } else if ( ",v&&(l+=" ("+y+" !== undefined && typeof "+y+" != 'number') || "),l+=" "+s+" == 'number' ? ( ("+a+" = "+y+" === undefined || "+u+" "+b+"= "+y+") ? "+m+" "+S+"= "+u+" : "+m+" "+S+" "+y+" ) : ( ("+a+" = "+u+" === true) ? "+m+" "+S+"= "+y+" : "+m+" "+S+" "+y+" ) || "+m+" !== "+m+") { var op"+c+" = "+a+" ? '"+b+"' : '"+b+"='; ",void 0===h&&(p=e.errSchemaPath+"/"+(_=P),y=u,v=w)):(i=b,(o="number"==typeof E)&&v?(n="'"+i+"'",l+=" if ( ",v&&(l+=" ("+y+" !== undefined && typeof "+y+" != 'number') || "),l+=" ( "+y+" === undefined || "+E+" "+b+"= "+y+" ? "+m+" "+S+"= "+E+" : "+m+" "+S+" "+y+" ) || "+m+" !== "+m+") { "):(o&&void 0===h?(a=!0,p=e.errSchemaPath+"/"+(_=P),y=E,S+="="):(o&&(y=Math[g?"min":"max"](E,h)),E===(!o||y)?(a=!0,p=e.errSchemaPath+"/"+(_=P),S+="="):(a=!1,i+="=")),n="'"+i+"'",l+=" if ( ",v&&(l+=" ("+y+" !== undefined && typeof "+y+" != 'number') || "),l+=" "+m+" "+S+" "+y+" || "+m+" !== "+m+") { ")),_=_||r;(F=F||[]).push(l),l="",!1!==e.createErrors?(l+=" { keyword: '"+(_||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { comparison: "+n+", limit: "+y+", exclusive: "+a+" } ",!1!==e.opts.messages&&(l=l+" , message: 'should be "+i+" "+(v?"' + "+y:y+"'")),e.opts.verbose&&(l=(l+=" , schema: ")+(v?"validate.schema"+d:""+h)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),l+=" } "):l+=" {} ";var F,x=l;return l=(l=F.pop())+(!e.compositeRule&&f?e.async?" throw new ValidationError(["+x+"]); ":" validate.errors = ["+x+"]; return false; ":" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+" } ",f&&(l+=" else { "),l}},{}],14:[function(e,r,t){r.exports=function(e,r,t){var a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(i||""),d=e.opts.$data&&n&&n.$data,i=d?(s+=" var schema"+o+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ","schema"+o):n;if(d||"number"==typeof n)return s+="if ( ",d&&(s+=" ("+i+" !== undefined && typeof "+i+" != 'number') || "),(o=[]).push(s+=" "+h+".length "+("maxItems"==(a=r)?">":"<")+" "+i+") { "),s="",!1!==e.createErrors?(s+=" { keyword: '"+(a||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+i+" } ",!1!==e.opts.messages&&(s=(s=(s+=" , message: 'should NOT have ")+("maxItems"==r?"more":"fewer")+" than ")+(d?"' + "+i+" + '":""+n)+" items' "),e.opts.verbose&&(s=(s+=" , schema: ")+(d?"validate.schema"+l:""+n)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),s+=" } "):s+=" {} ",a=s,s=(s=o.pop())+(!e.compositeRule&&u?e.async?" throw new ValidationError(["+a+"]); ":" validate.errors = ["+a+"]; return false; ":" var err = "+a+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+"} ",u&&(s+=" else { "),s;throw new Error(r+" must be number")}},{}],15:[function(e,r,t){r.exports=function(e,r,t){var a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(i||""),d=e.opts.$data&&n&&n.$data,i=d?(s+=" var schema"+o+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ","schema"+o):n;if(d||"number"==typeof n)return s+="if ( ",d&&(s+=" ("+i+" !== undefined && typeof "+i+" != 'number') || "),(o=[]).push(s=s+(!1===e.opts.unicode?" "+h+".length ":" ucs2length("+h+") ")+(" "+("maxLength"==(a=r)?">":"<")+" "+i+") { ")),s="",!1!==e.createErrors?(s+=" { keyword: '"+(a||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+i+" } ",!1!==e.opts.messages&&(s=(s=(s+=" , message: 'should NOT be ")+("maxLength"==r?"longer":"shorter")+" than ")+(d?"' + "+i+" + '":""+n)+" characters' "),e.opts.verbose&&(s=(s+=" , schema: ")+(d?"validate.schema"+l:""+n)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),s+=" } "):s+=" {} ",a=s,s=(s=o.pop())+(!e.compositeRule&&u?e.async?" throw new ValidationError(["+a+"]); ":" validate.errors = ["+a+"]; return false; ":" var err = "+a+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+"} ",u&&(s+=" else { "),s;throw new Error(r+" must be number")}},{}],16:[function(e,r,t){r.exports=function(e,r,t){var a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(i||""),d=e.opts.$data&&n&&n.$data,i=d?(s+=" var schema"+o+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ","schema"+o):n;if(d||"number"==typeof n)return s+="if ( ",d&&(s+=" ("+i+" !== undefined && typeof "+i+" != 'number') || "),(o=[]).push(s+=" Object.keys("+h+").length "+("maxProperties"==(a=r)?">":"<")+" "+i+") { "),s="",!1!==e.createErrors?(s+=" { keyword: '"+(a||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+i+" } ",!1!==e.opts.messages&&(s=(s=(s+=" , message: 'should NOT have ")+("maxProperties"==r?"more":"fewer")+" than ")+(d?"' + "+i+" + '":""+n)+" properties' "),e.opts.verbose&&(s=(s+=" , schema: ")+(d?"validate.schema"+l:""+n)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),s+=" } "):s+=" {} ",a=s,s=(s=o.pop())+(!e.compositeRule&&u?e.async?" throw new ValidationError(["+a+"]); ":" validate.errors = ["+a+"]; return false; ":" var err = "+a+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+"} ",u&&(s+=" else { "),s;throw new Error(r+" must be number")}},{}],17:[function(e,r,t){r.exports=function(e,r,t){var a=" ",s=e.schema[r],o=e.schemaPath+e.util.getProperty(r),i=e.errSchemaPath+"/"+r,n=!e.opts.allErrors,l=e.util.copy(e),c="",u=(l.level++,"valid"+l.level),h=l.baseId,d=!0,p=s;if(p)for(var f,m=-1,v=p.length-1;m "+w+") { ",S=u+"["+w+"]",h.schema=F,h.schemaPath=n+"["+w+"]",h.errSchemaPath=l+"/"+w,h.errorPath=e.util.getPathExpr(e.errorPath,w,e.opts.jsonPointers,!0),h.dataPathArr[f]=w,_=e.validate(h),h.baseId=v,e.util.varOccurences(_,m)<2?a+=" "+e.util.varReplace(_,m,S)+" ":a+=" var "+m+" = "+S+"; "+_+" ",a+=" } ",c)&&(a+=" if ("+p+") { ",d+="}")}"object"==typeof P&&(e.opts.strictKeywords?"object"==typeof P&&0 "+i.length+") { for (var "+s+" = "+i.length+"; "+s+" < "+u+".length; "+s+"++) { ",h.errorPath=e.util.getPathExpr(e.errorPath,s,e.opts.jsonPointers,!0),S=u+"["+s+"]",h.dataPathArr[f]=s,_=e.validate(h),h.baseId=v,e.util.varOccurences(_,m)<2?a+=" "+e.util.varReplace(_,m,S)+" ":a+=" var "+m+" = "+S+"; "+_+" ",c&&(a+=" if (!"+p+") break; "),a+=" } } ",c)&&(a+=" if ("+p+") { ",d+="}")}else(e.opts.strictKeywords?"object"==typeof i&&0 1e-"+e.opts.multipleOfPrecision+" ":" division"+s+" !== parseInt(division"+s+") ")+" ) ",h&&(a+=" ) ");r=[],r.push(a+=" ) { "),a="",!1!==e.createErrors?(a+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { multipleOf: "+o+" } ",!1!==e.opts.messages&&(a=a+" , message: 'should be multiple of "+(h?"' + "+o:o+"'")),e.opts.verbose&&(a=(a+=" , schema: ")+(h?"validate.schema"+n:""+i)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",s=a;return a=(a=r.pop())+(!e.compositeRule&&c?e.async?" throw new ValidationError(["+s+"]); ":" validate.errors = ["+s+"]; return false; ":" var err = "+s+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+"} ",c&&(a+=" else { "),a}},{}],30:[function(e,r,t){r.exports=function(e,r,t){var a,s,o=" ",i=e.level,n=e.dataLevel,l=e.schema[r],c=e.schemaPath+e.util.getProperty(r),r=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,n="data"+(n||""),i="errs__"+i,h=e.util.copy(e),d=(h.level++,"valid"+h.level);return(e.opts.strictKeywords?"object"==typeof l&&0 1) { ",o=e.schema.items&&e.schema.items.type,i=Array.isArray(o),!o||"object"==o||"array"==o||i&&(0<=o.indexOf("object")||0<=o.indexOf("array"))?s+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+u+"[i], "+u+"[j])) { "+h+" = false; break outer; } } } ":(s=(s+=" var itemIndices = {}, item; for (;i--;) { var item = "+u+"[i]; ")+" if ("+e.util["checkDataType"+(i?"s":"")](o,"item",e.opts.strictNumbers,!0)+") continue; ",i&&(s+=" if (typeof item == 'string') item = '\"' + item; "),s+=" if (typeof itemIndices[item] == 'number') { "+h+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "),s+=" } ",d&&(s+=" } "),(a=a||[]).push(s+=" if (!"+h+") { "),s="",!1!==e.createErrors?(s+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(r)+" , params: { i: i, j: j } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(s=(s+=" , schema: ")+(d?"validate.schema"+l:""+n)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ",o=s,s=(s=a.pop())+(!e.compositeRule&&c?e.async?" throw new ValidationError(["+o+"]); ":" validate.errors = ["+o+"]; return false; ":" var err = "+o+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+" } ",c&&(s+=" else { ")):c&&(s+=" if (true) { "),s}},{}],38:[function(e,r,t){r.exports=function(a,e,L){var r="",t=!0===a.schema.$async,s=a.util.schemaHasRulesExcept(a.schema,a.RULES.all,"$ref"),o=a.self._getId(a.schema);if(a.opts.strictKeywords){var i=a.util.schemaUnknownRules(a.schema,a.RULES.keywords);if(i){i="unknown keyword: "+i;if("log"!==a.opts.strictKeywords)throw new Error(i);a.logger.warn(i)}}if(a.isTop&&(r+=" var validate = ",t&&(a.async=!0,r+="async "),r+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",o)&&(a.opts.sourceCode||a.opts.processCode)&&(r+=" /*# sourceURL="+o+" */ "),"boolean"==typeof a.schema||!s&&!a.schema.$ref)l=a.level,c=a.dataLevel,j=a.schema[e="false schema"],E=a.schemaPath+a.util.getProperty(e),w=a.errSchemaPath+"/"+e,p=!a.opts.allErrors,u="data"+(c||""),d="valid"+l,!1===a.schema?(a.isTop?p=!0:r+=" var "+d+" = false; ",(k=k||[]).push(r),r="",!1!==a.createErrors?(r+=" { keyword: 'false schema' , dataPath: (dataPath || '') + "+a.errorPath+" , schemaPath: "+a.util.toQuotedString(w)+" , params: {} ",!1!==a.opts.messages&&(r+=" , message: 'boolean schema is false' "),a.opts.verbose&&(r+=" , schema: false , parentSchema: validate.schema"+a.schemaPath+" , data: "+u+" "),r+=" } "):r+=" {} ",R=r,r=k.pop(),r+=!a.compositeRule&&p?a.async?" throw new ValidationError(["+R+"]); ":" validate.errors = ["+R+"]; return false; ":" var err = "+R+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "):r+=a.isTop?t?" return data; ":" validate.errors = null; return true; ":" var "+d+" = true; ",a.isTop&&(r+=" }; return validate; ");else{if(a.isTop){var n=a.isTop,l=a.level=0,c=a.dataLevel=0,u="data";if(a.rootId=a.resolve.fullPath(a.self._getId(a.root.schema)),a.baseId=a.baseId||a.rootId,delete a.isTop,a.dataPathArr=[""],void 0!==a.schema.default&&a.opts.useDefaults&&a.opts.strictDefaults){var h="default is ignored in the schema root";if("log"!==a.opts.strictDefaults)throw new Error(h);a.logger.warn(h)}r=(r+=" var vErrors = null; ")+" var errors = 0; "+" if (rootData === undefined) rootData = data; "}else{l=a.level,u="data"+((c=a.dataLevel)||"");if(o&&(a.baseId=a.resolve.url(a.baseId,o)),t&&!a.async)throw new Error("async schema in sync schema");r+=" var errs_"+l+" = errors;"}var d="valid"+l,p=!a.opts.allErrors,f="",m="",v=a.schema.type,y=Array.isArray(v);if(v&&a.opts.nullable&&!0===a.schema.nullable&&(y?-1==v.indexOf("null")&&(v=v.concat("null")):"null"!=v&&(v=[v,"null"],y=!0)),y&&1==v.length&&(v=v[0],y=!1),a.schema.$ref&&s){if("fail"==a.opts.extendRefs)throw new Error('$ref: validation keywords used in schema at path "'+a.errSchemaPath+'" (see option extendRefs)');!0!==a.opts.extendRefs&&(s=!1,a.logger.warn('$ref: keywords ignored in schema at path "'+a.errSchemaPath+'"'))}if(a.schema.$comment&&a.opts.$comment&&(r+=" "+a.RULES.all.$comment.code(a,"$comment")),v){a.opts.coerceTypes&&(g=a.util.coerceToTypes(a.opts.coerceTypes,v));var g,P=a.RULES.types[v];if(g||y||!0===P||P&&!B(P)){var E=a.schemaPath+".type",w=a.errSchemaPath+"/type",E=a.schemaPath+".type",w=a.errSchemaPath+"/type";if(r+=" if ("+a.util[y?"checkDataTypes":"checkDataType"](v,u,a.opts.strictNumbers,!0)+") { ",g){var b="dataType"+l,S="coerced"+l,_=(r+=" var "+b+" = typeof "+u+"; var "+S+" = undefined; ","array"==a.opts.coerceTypes&&(r+=" if ("+b+" == 'object' && Array.isArray("+u+") && "+u+".length == 1) { "+u+" = "+u+"[0]; "+b+" = typeof "+u+"; if ("+a.util.checkDataType(a.schema.type,u,a.opts.strictNumbers)+") "+S+" = "+u+"; } "),r+=" if ("+S+" !== undefined) ; ",g);if(_)for(var F,x=-1,N=_.length-1;x{for(var r=e.implements,t=0;t= 0x80 (not a basic code point)","invalid-input":"Invalid input"},s=I-1,k=Math.floor,C=String.fromCharCode;function L(e){throw new RangeError(Q[e])}function t(e,r){var t=e.split("@"),a="",t=(1{for(var t=[],a=e.length;a--;)t[a]=r(e[a]);return t})(t,r).join(".")}function V(e){for(var r=[],t=0,a=e.length;t>1,e+=k(e/r);s*A>>1k((O-a)/u))&&L("overflow"),a+=d*u,h<=o?1:o+A<=h?A:h-o);if(dk(O/d)&&L("overflow"),u*=d}var f=r.length+1,o=z(a-c,f,0==c);k(a/f)>O-s&&L("overflow"),s+=k(a/f),a%=f,r.splice(a++,0,s)}return String.fromCodePoint.apply(String,r)}function H(e){var r=[],t=(e=V(e)).length,a=128,s=0,o=72,i=!0,n=!1,l=void 0;try{for(var c,u=e[Symbol.iterator]();!(i=(c=u.next()).done);i=!0){var h=c.value;h<128&&r.push(C(h))}}catch(e){n=!0,l=e}finally{try{!i&&u.return&&u.return()}finally{if(n)throw l}}var d=r.length,p=d;for(d&&r.push("-");pk((O-s)/w)&&L("overflow"),s+=(f-a)*w,a=f,!0),v=!1,y=void 0;try{for(var S,_=e[Symbol.iterator]();!(b=(S=_.next()).done);b=!0){var F=S.value;if(FO&&L("overflow"),F==a){for(var x=s,R=I;;R+=I){var $=R<=o?1:o+A<=R?A:R-o;if(x<$)break;var j=x-$,D=I-$;r.push(C(N($+j%D,0))),x=k(j/D)}r.push(C(N(x,0))),o=z(s,w,p==d),s=0,++p}}}catch(e){v=!0,y=e}finally{try{!b&&_.return&&_.return()}finally{if(v)throw y}}++s,++a}return r.join("")}var v=function(e){return t(e,function(e){return q.test(e)?"xn--"+H(e):e})},M=function(e){return t(e,function(e){return D.test(e)?U(e.slice(4).toLowerCase()):e})},c={};function f(e){e=e.charCodeAt(0);return e<16?"%0"+e.toString(16).toUpperCase():e<128?"%"+e.toString(16).toUpperCase():e<2048?"%"+(e>>6|192).toString(16).toUpperCase()+"%"+(63&e|128).toString(16).toUpperCase():"%"+(e>>12|224).toString(16).toUpperCase()+"%"+(e>>6&63|128).toString(16).toUpperCase()+"%"+(63&e|128).toString(16).toUpperCase()}function u(e){for(var r="",t=0,a=e.length;tA-Z\\x5E-\\x7E]",'[\\"\\\\]'),se=new RegExp(_,"g"),x=new RegExp("(?:(?:%[EFef][0-9A-Fa-f]%[0-9A-Fa-f][0-9A-Fa-f]%[0-9A-Fa-f][0-9A-Fa-f])|(?:%[89A-Fa-f][0-9A-Fa-f]%[0-9A-Fa-f][0-9A-Fa-f])|(?:%[0-9A-Fa-f][0-9A-Fa-f]))","g"),oe=new RegExp(g("[^]","[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]","[\\.]",'[\\"]',F),"g"),ie=new RegExp(g("[^]",_,"[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"),"g"),ne=ie;function R(e){var r=u(e);return r.match(se)?r:e}var F={scheme:"mailto",parse:function(e,r){var t=e,a=t.to=t.path?t.path.split(","):[];if(t.path=void 0,t.query){for(var s=!1,o={},i=t.query.split("&"),n=0,l=i.length;n{var t=e;if(r)for(var a in r)t[a]=r[a];return t})({scheme:"null"},t),i(X(o(e,t),o(r,t),t,!0),t)},e.normalize=function(e,r){return"string"==typeof e?e=i(o(e,r),r):"object"===a(e)&&(e=o(i(e,r),r)),e},e.equal=function(e,r,t){return"string"==typeof e?e=i(o(e,t),t):"object"===a(e)&&(e=i(e,t)),"string"==typeof r?r=i(o(r,t),t):"object"===a(r)&&(r=i(r,t)),e===r},e.escapeComponent=function(e,r){return e&&e.toString().replace((r&&r.iri?l:n).ESCAPE,f)},e.unescapeComponent=w,Object.defineProperty(e,"__esModule",{value:!0})}("object"==typeof t&&void 0!==r?t:a.URI=a.URI||{})},{}],ajv:[function(h,e,r){var i=h("./compile"),l=h("./compile/resolve"),d=h("./cache"),c=h("./compile/schema_obj"),p=h("fast-json-stable-stringify"),f=h("./compile/formats"),m=h("./compile/rules"),v=h("./data"),y=h("./compile/util"),e=((e.exports=w).prototype.validate=function(e,r){var t;if("string"==typeof e){if(!(t=this.getSchema(e)))throw new Error('no schema with key or ref "'+e+'"')}else{e=this._addSchema(e);t=e.validate||this._compile(e)}e=t(r);!0!==t.$async&&(this.errors=t.errors);return e},w.prototype.compile=function(e,r){e=this._addSchema(e,void 0,r);return e.validate||this._compile(e)},w.prototype.addSchema=function(e,r,t,a){if(Array.isArray(e))for(var s=0;s{var r=e._opts.meta;return e._opts.defaultMeta="object"==typeof r?e._getId(r)||r:e.getSchema(g)?g:void 0,e._opts.defaultMeta})(this)))return this.logger.warn("meta-schema not available"),!(this.errors=null);t=this.validate(t,e);if(!t&&r){e="schema is invalid: "+this.errorsText();if("log"!=this._opts.validateSchema)throw new Error(e);this.logger.error(e)}return t},w.prototype.getSchema=function(e){var r=t(this,e);switch(typeof r){case"object":return r.validate||this._compile(r);case"string":return this.getSchema(r);case"undefined":return((e,r)=>{var t,a,s,o=l.schema.call(e,{schema:{}},r);if(o)return s=i.call(e,t=o.schema,a=o.root,void 0,o=o.baseId),e._fragments[r]=new c({ref:r,fragment:!0,schema:t,root:a,baseId:o,validate:s}),s})(this,e)}},w.prototype.removeSchema=function(e){if(e instanceof RegExp)a(this,this._schemas,e),a(this,this._refs,e);else switch(typeof e){case"undefined":return a(this,this._schemas),a(this,this._refs),this._cache.clear(),this;case"string":var r=t(this,e);return r&&this._cache.del(r.cacheKey),delete this._schemas[e],delete this._refs[e],this;case"object":r=this._opts.serialize,r=r?r(e):e,r=(this._cache.del(r),this._getId(e));r&&(r=l.normalizeId(r),delete this._schemas[r],delete this._refs[r])}return this},w.prototype.addFormat=function(e,r){"string"==typeof r&&(r=new RegExp(r));return this._formats[e]=r,this},w.prototype.errorsText=function(e,r){if(!(e=e||this.errors))return"No errors";for(var t=void 0===(r=r||{}).separator?", ":r.separator,a=void 0===r.dataVar?"data":r.dataVar,s="",o=0;o{switch(e.schemaId){case"auto":return _;case"id":return b;default:return S}})(e),e.loopRequired=e.loopRequired||1/0,"property"==e.errorDataPath&&(e._errorDataPathProperty=!0),void 0===e.serialize&&(e.serialize=p),this._metaOpts=(e=>{for(var r=y.copy(e._opts),t=0;t); + + message: string; + errors: Array; + ajv: true; + validation: true; + } + + class MissingRefError extends Error { + constructor(baseId: string, ref: string, message?: string); + static message: (baseId: string, ref: string) => string; + + message: string; + missingRef: string; + missingSchema: string; + } +} + +declare namespace ajv { + type ValidationError = AjvErrors.ValidationError; + + type MissingRefError = AjvErrors.MissingRefError; + + interface Ajv { + /** + * Validate data using schema + * Schema will be compiled and cached (using serialized JSON as key, [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize by default). + * @param {string|object|Boolean} schemaKeyRef key, ref or schema object + * @param {Any} data to be validated + * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). + */ + validate(schemaKeyRef: object | string | boolean, data: any): boolean | PromiseLike; + /** + * Create validating function for passed schema. + * @param {object|Boolean} schema schema object + * @return {Function} validating function + */ + compile(schema: object | boolean): ValidateFunction; + /** + * Creates validating function for passed schema with asynchronous loading of missing schemas. + * `loadSchema` option should be a function that accepts schema uri and node-style callback. + * @this Ajv + * @param {object|Boolean} schema schema object + * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped + * @param {Function} callback optional node-style callback, it is always called with 2 parameters: error (or null) and validating function. + * @return {PromiseLike} validating function + */ + compileAsync(schema: object | boolean, meta?: Boolean, callback?: (err: Error, validate: ValidateFunction) => any): PromiseLike; + /** + * Adds schema to the instance. + * @param {object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. + * @param {string} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + * @return {Ajv} this for method chaining + */ + addSchema(schema: Array | object, key?: string): Ajv; + /** + * Add schema that will be used to validate other schemas + * options in META_IGNORE_OPTIONS are alway set to false + * @param {object} schema schema object + * @param {string} key optional schema key + * @return {Ajv} this for method chaining + */ + addMetaSchema(schema: object, key?: string): Ajv; + /** + * Validate schema + * @param {object|Boolean} schema schema to validate + * @return {Boolean} true if schema is valid + */ + validateSchema(schema: object | boolean): boolean; + /** + * Get compiled schema from the instance by `key` or `ref`. + * @param {string} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id). + * @return {Function} schema validating function (with property `schema`). Returns undefined if keyRef can't be resolved to an existing schema. + */ + getSchema(keyRef: string): ValidateFunction | undefined; + /** + * Remove cached schema(s). + * If no parameter is passed all schemas but meta-schemas are removed. + * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + * Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + * @param {string|object|RegExp|Boolean} schemaKeyRef key, ref, pattern to match key/ref or schema object + * @return {Ajv} this for method chaining + */ + removeSchema(schemaKeyRef?: object | string | RegExp | boolean): Ajv; + /** + * Add custom format + * @param {string} name format name + * @param {string|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid) + * @return {Ajv} this for method chaining + */ + addFormat(name: string, format: FormatValidator | FormatDefinition): Ajv; + /** + * Define custom keyword + * @this Ajv + * @param {string} keyword custom keyword, should be a valid identifier, should be different from all standard, custom and macro keywords. + * @param {object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. + * @return {Ajv} this for method chaining + */ + addKeyword(keyword: string, definition: KeywordDefinition): Ajv; + /** + * Get keyword definition + * @this Ajv + * @param {string} keyword pre-defined or custom keyword. + * @return {object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise. + */ + getKeyword(keyword: string): object | boolean; + /** + * Remove keyword + * @this Ajv + * @param {string} keyword pre-defined or custom keyword. + * @return {Ajv} this for method chaining + */ + removeKeyword(keyword: string): Ajv; + /** + * Validate keyword + * @this Ajv + * @param {object} definition keyword definition object + * @param {boolean} throwError true to throw exception if definition is invalid + * @return {boolean} validation result + */ + validateKeyword(definition: KeywordDefinition, throwError: boolean): boolean; + /** + * Convert array of error message objects to string + * @param {Array} errors optional array of validation errors, if not passed errors from the instance are used. + * @param {object} options optional options with properties `separator` and `dataVar`. + * @return {string} human readable string with all errors descriptions + */ + errorsText(errors?: Array | null, options?: ErrorsTextOptions): string; + errors?: Array | null; + _opts: Options; + } + + interface CustomLogger { + log(...args: any[]): any; + warn(...args: any[]): any; + error(...args: any[]): any; + } + + interface ValidateFunction { + ( + data: any, + dataPath?: string, + parentData?: object | Array, + parentDataProperty?: string | number, + rootData?: object | Array + ): boolean | PromiseLike; + schema?: object | boolean; + errors?: null | Array; + refs?: object; + refVal?: Array; + root?: ValidateFunction | object; + $async?: true; + source?: object; + } + + interface Options { + $data?: boolean; + allErrors?: boolean; + verbose?: boolean; + jsonPointers?: boolean; + uniqueItems?: boolean; + unicode?: boolean; + format?: false | string; + formats?: object; + keywords?: object; + unknownFormats?: true | string[] | 'ignore'; + schemas?: Array | object; + schemaId?: '$id' | 'id' | 'auto'; + missingRefs?: true | 'ignore' | 'fail'; + extendRefs?: true | 'ignore' | 'fail'; + loadSchema?: (uri: string, cb?: (err: Error, schema: object) => void) => PromiseLike; + removeAdditional?: boolean | 'all' | 'failing'; + useDefaults?: boolean | 'empty' | 'shared'; + coerceTypes?: boolean | 'array'; + strictDefaults?: boolean | 'log'; + strictKeywords?: boolean | 'log'; + strictNumbers?: boolean; + async?: boolean | string; + transpile?: string | ((code: string) => string); + meta?: boolean | object; + validateSchema?: boolean | 'log'; + addUsedSchema?: boolean; + inlineRefs?: boolean | number; + passContext?: boolean; + loopRequired?: number; + ownProperties?: boolean; + multipleOfPrecision?: boolean | number; + errorDataPath?: string, + messages?: boolean; + sourceCode?: boolean; + processCode?: (code: string, schema: object) => string; + cache?: object; + logger?: CustomLogger | false; + nullable?: boolean; + serialize?: ((schema: object | boolean) => any) | false; + regExp?: (pattern: string) => RegExpLike; + } + + interface RegExpLike { + test: (s: string) => boolean; + } + + type FormatValidator = string | RegExp | ((data: string) => boolean | PromiseLike); + type NumberFormatValidator = ((data: number) => boolean | PromiseLike); + + interface NumberFormatDefinition { + type: "number", + validate: NumberFormatValidator; + compare?: (data1: number, data2: number) => number; + async?: boolean; + } + + interface StringFormatDefinition { + type?: "string", + validate: FormatValidator; + compare?: (data1: string, data2: string) => number; + async?: boolean; + } + + type FormatDefinition = NumberFormatDefinition | StringFormatDefinition; + + interface KeywordDefinition { + type?: string | Array; + async?: boolean; + $data?: boolean; + errors?: boolean | string; + metaSchema?: object; + // schema: false makes validate not to expect schema (ValidateFunction) + schema?: boolean; + statements?: boolean; + dependencies?: Array; + modifying?: boolean; + valid?: boolean; + // one and only one of the following properties should be present + validate?: SchemaValidateFunction | ValidateFunction; + compile?: (schema: any, parentSchema: object, it: CompilationContext) => ValidateFunction; + macro?: (schema: any, parentSchema: object, it: CompilationContext) => object | boolean; + inline?: (it: CompilationContext, keyword: string, schema: any, parentSchema: object) => string; + } + + interface CompilationContext { + level: number; + dataLevel: number; + dataPathArr: string[]; + schema: any; + schemaPath: string; + baseId: string; + async: boolean; + opts: Options; + formats: { + [index: string]: FormatDefinition | undefined; + }; + keywords: { + [index: string]: KeywordDefinition | undefined; + }; + compositeRule: boolean; + validate: (schema: object) => boolean; + util: { + copy(obj: any, target?: any): any; + toHash(source: string[]): { [index: string]: true | undefined }; + equal(obj: any, target: any): boolean; + getProperty(str: string): string; + schemaHasRules(schema: object, rules: any): string; + escapeQuotes(str: string): string; + toQuotedString(str: string): string; + getData(jsonPointer: string, dataLevel: number, paths: string[]): string; + escapeJsonPointer(str: string): string; + unescapeJsonPointer(str: string): string; + escapeFragment(str: string): string; + unescapeFragment(str: string): string; + }; + self: Ajv; + } + + interface SchemaValidateFunction { + ( + schema: any, + data: any, + parentSchema?: object, + dataPath?: string, + parentData?: object | Array, + parentDataProperty?: string | number, + rootData?: object | Array + ): boolean | PromiseLike; + errors?: Array; + } + + interface ErrorsTextOptions { + separator?: string; + dataVar?: string; + } + + interface ErrorObject { + keyword: string; + dataPath: string; + schemaPath: string; + params: ErrorParameters; + // Added to validation errors of propertyNames keyword schema + propertyName?: string; + // Excluded if messages set to false. + message?: string; + // These are added with the `verbose` option. + schema?: any; + parentSchema?: object; + data?: any; + } + + type ErrorParameters = RefParams | LimitParams | AdditionalPropertiesParams | + DependenciesParams | FormatParams | ComparisonParams | + MultipleOfParams | PatternParams | RequiredParams | + TypeParams | UniqueItemsParams | CustomParams | + PatternRequiredParams | PropertyNamesParams | + IfParams | SwitchParams | NoParams | EnumParams; + + interface RefParams { + ref: string; + } + + interface LimitParams { + limit: number; + } + + interface AdditionalPropertiesParams { + additionalProperty: string; + } + + interface DependenciesParams { + property: string; + missingProperty: string; + depsCount: number; + deps: string; + } + + interface FormatParams { + format: string + } + + interface ComparisonParams { + comparison: string; + limit: number | string; + exclusive: boolean; + } + + interface MultipleOfParams { + multipleOf: number; + } + + interface PatternParams { + pattern: string; + } + + interface RequiredParams { + missingProperty: string; + } + + interface TypeParams { + type: string; + } + + interface UniqueItemsParams { + i: number; + j: number; + } + + interface CustomParams { + keyword: string; + } + + interface PatternRequiredParams { + missingPattern: string; + } + + interface PropertyNamesParams { + propertyName: string; + } + + interface IfParams { + failingKeyword: string; + } + + interface SwitchParams { + caseIndex: number; + } + + interface NoParams { } + + interface EnumParams { + allowedValues: Array; + } +} + +export = ajv; diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/ajv.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/ajv.js new file mode 100644 index 0000000000000000000000000000000000000000..06a45b650b3ac57561a53155e5a91827c0a74b18 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/ajv.js @@ -0,0 +1,506 @@ +'use strict'; + +var compileSchema = require('./compile') + , resolve = require('./compile/resolve') + , Cache = require('./cache') + , SchemaObject = require('./compile/schema_obj') + , stableStringify = require('fast-json-stable-stringify') + , formats = require('./compile/formats') + , rules = require('./compile/rules') + , $dataMetaSchema = require('./data') + , util = require('./compile/util'); + +module.exports = Ajv; + +Ajv.prototype.validate = validate; +Ajv.prototype.compile = compile; +Ajv.prototype.addSchema = addSchema; +Ajv.prototype.addMetaSchema = addMetaSchema; +Ajv.prototype.validateSchema = validateSchema; +Ajv.prototype.getSchema = getSchema; +Ajv.prototype.removeSchema = removeSchema; +Ajv.prototype.addFormat = addFormat; +Ajv.prototype.errorsText = errorsText; + +Ajv.prototype._addSchema = _addSchema; +Ajv.prototype._compile = _compile; + +Ajv.prototype.compileAsync = require('./compile/async'); +var customKeyword = require('./keyword'); +Ajv.prototype.addKeyword = customKeyword.add; +Ajv.prototype.getKeyword = customKeyword.get; +Ajv.prototype.removeKeyword = customKeyword.remove; +Ajv.prototype.validateKeyword = customKeyword.validate; + +var errorClasses = require('./compile/error_classes'); +Ajv.ValidationError = errorClasses.Validation; +Ajv.MissingRefError = errorClasses.MissingRef; +Ajv.$dataMetaSchema = $dataMetaSchema; + +var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; + +var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ]; +var META_SUPPORT_DATA = ['/properties']; + +/** + * Creates validator instance. + * Usage: `Ajv(opts)` + * @param {Object} opts optional options + * @return {Object} ajv instance + */ +function Ajv(opts) { + if (!(this instanceof Ajv)) return new Ajv(opts); + opts = this._opts = util.copy(opts) || {}; + setLogger(this); + this._schemas = {}; + this._refs = {}; + this._fragments = {}; + this._formats = formats(opts.format); + + this._cache = opts.cache || new Cache; + this._loadingSchemas = {}; + this._compilations = []; + this.RULES = rules(); + this._getId = chooseGetId(opts); + + opts.loopRequired = opts.loopRequired || Infinity; + if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; + if (opts.serialize === undefined) opts.serialize = stableStringify; + this._metaOpts = getMetaSchemaOptions(this); + + if (opts.formats) addInitialFormats(this); + if (opts.keywords) addInitialKeywords(this); + addDefaultMetaSchema(this); + if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta); + if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}}); + addInitialSchemas(this); +} + + + +/** + * Validate data using schema + * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize. + * @this Ajv + * @param {String|Object} schemaKeyRef key, ref or schema object + * @param {Any} data to be validated + * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). + */ +function validate(schemaKeyRef, data) { + var v; + if (typeof schemaKeyRef == 'string') { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); + } else { + var schemaObj = this._addSchema(schemaKeyRef); + v = schemaObj.validate || this._compile(schemaObj); + } + + var valid = v(data); + if (v.$async !== true) this.errors = v.errors; + return valid; +} + + +/** + * Create validating function for passed schema. + * @this Ajv + * @param {Object} schema schema object + * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. + * @return {Function} validating function + */ +function compile(schema, _meta) { + var schemaObj = this._addSchema(schema, undefined, _meta); + return schemaObj.validate || this._compile(schemaObj); +} + + +/** + * Adds schema to the instance. + * @this Ajv + * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. + * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. + * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + * @return {Ajv} this for method chaining + */ +function addSchema(schema, key, _skipValidation, _meta) { + if (Array.isArray(schema)){ + for (var i=0; i} errors optional array of validation errors, if not passed errors from the instance are used. + * @param {Object} options optional options with properties `separator` and `dataVar`. + * @return {String} human readable string with all errors descriptions + */ +function errorsText(errors, options) { + errors = errors || this.errors; + if (!errors) return 'No errors'; + options = options || {}; + var separator = options.separator === undefined ? ', ' : options.separator; + var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; + + var text = ''; + for (var i=0; i%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; +// For the source: https://gist.github.com/dperini/729294 +// For test cases: https://mathiasbynens.be/demo/url-regex +// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983. +// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; +var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i; +var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; +var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; +var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; +var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; + + +module.exports = formats; + +function formats(mode) { + mode = mode == 'full' ? 'full' : 'fast'; + return util.copy(formats[mode], Object.create(null)); +} + + +formats.fast = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, + 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + 'uri-reference': /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + 'uri-template': URITEMPLATE, + url: URL, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation') + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, + hostname: HOSTNAME, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: UUID, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; + + +formats.full = { + date: date, + time: time, + 'date-time': date_time, + uri: uri, + 'uri-reference': URIREF, + 'uri-template': URITEMPLATE, + url: URL, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: HOSTNAME, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + uuid: UUID, + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; + + +function isLeapYear(year) { + // https://tools.ietf.org/html/rfc3339#appendix-C + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} + + +function date(str) { + // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 + var matches = str.match(DATE); + if (!matches) return false; + + var year = +matches[1]; + var month = +matches[2]; + var day = +matches[3]; + + return month >= 1 && month <= 12 && day >= 1 && + day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); +} + + +function time(str, full) { + var matches = str.match(TIME); + if (!matches) return false; + + var hour = matches[1]; + var minute = matches[2]; + var second = matches[3]; + var timeZone = matches[5]; + return ((hour <= 23 && minute <= 59 && second <= 59) || + (hour == 23 && minute == 59 && second == 60)) && + (!full || timeZone); +} + + +var DATE_TIME_SEPARATOR = /t|\s/i; +function date_time(str) { + // http://tools.ietf.org/html/rfc3339#section-5.6 + var dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); +} + + +var NOT_URI_FRAGMENT = /\/|:/; +function uri(str) { + // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." + return NOT_URI_FRAGMENT.test(str) && URI.test(str); +} + + +var Z_ANCHOR = /[^\\]\\Z/; +function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str); + return true; + } catch(e) { + return false; + } +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/compile/index.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/compile/index.js new file mode 100644 index 0000000000000000000000000000000000000000..321699020d34b5d799e8592b7839e795d4d73ce2 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/compile/index.js @@ -0,0 +1,389 @@ +'use strict'; + +var resolve = require('./resolve') + , util = require('./util') + , errorClasses = require('./error_classes') + , stableStringify = require('fast-json-stable-stringify'); + +var validateGenerator = require('../dotjs/validate'); + +/** + * Functions below are used inside compiled validations function + */ + +var ucs2length = util.ucs2length; +var equal = require('fast-deep-equal'); + +// this error is thrown by async schemas to return validation errors via exception +var ValidationError = errorClasses.Validation; + +module.exports = compile; + + +/** + * Compiles schema to validation function + * @this Ajv + * @param {Object} schema schema object + * @param {Object} root object with information about the root schema for this schema + * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution + * @param {String} baseId base ID for IDs in the schema + * @return {Function} validation function + */ +function compile(schema, root, localRefs, baseId) { + /* jshint validthis: true, evil: true */ + /* eslint no-shadow: 0 */ + var self = this + , opts = this._opts + , refVal = [ undefined ] + , refs = {} + , patterns = [] + , patternsHash = {} + , defaults = [] + , defaultsHash = {} + , customRules = []; + + function patternCode(i, patterns) { + var regExpCode = opts.regExp ? 'regExp' : 'new RegExp'; + return 'var pattern' + i + ' = ' + regExpCode + '(' + util.toQuotedString(patterns[i]) + ');'; + } + + root = root || { schema: schema, refVal: refVal, refs: refs }; + + var c = checkCompiling.call(this, schema, root, baseId); + var compilation = this._compilations[c.index]; + if (c.compiling) return (compilation.callValidate = callValidate); + + var formats = this._formats; + var RULES = this.RULES; + + try { + var v = localCompile(schema, root, localRefs, baseId); + compilation.validate = v; + var cv = compilation.callValidate; + if (cv) { + cv.schema = v.schema; + cv.errors = null; + cv.refs = v.refs; + cv.refVal = v.refVal; + cv.root = v.root; + cv.$async = v.$async; + if (opts.sourceCode) cv.source = v.source; + } + return v; + } finally { + endCompiling.call(this, schema, root, baseId); + } + + /* @this {*} - custom context, see passContext option */ + function callValidate() { + /* jshint validthis: true */ + var validate = compilation.validate; + var result = validate.apply(this, arguments); + callValidate.errors = validate.errors; + return result; + } + + function localCompile(_schema, _root, localRefs, baseId) { + var isRoot = !_root || (_root && _root.schema == _schema); + if (_root.schema != root.schema) + return compile.call(self, _schema, _root, localRefs, baseId); + + var $async = _schema.$async === true; + + var sourceCode = validateGenerator({ + isTop: true, + schema: _schema, + isRoot: isRoot, + baseId: baseId, + root: _root, + schemaPath: '', + errSchemaPath: '#', + errorPath: '""', + MissingRefError: errorClasses.MissingRef, + RULES: RULES, + validate: validateGenerator, + util: util, + resolve: resolve, + resolveRef: resolveRef, + usePattern: usePattern, + useDefault: useDefault, + useCustomRule: useCustomRule, + opts: opts, + formats: formats, + logger: self.logger, + self: self + }); + + sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + + sourceCode; + + if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema); + // console.log('\n\n\n *** \n', JSON.stringify(sourceCode)); + var validate; + try { + var makeValidate = new Function( + 'self', + 'RULES', + 'formats', + 'root', + 'refVal', + 'defaults', + 'customRules', + 'equal', + 'ucs2length', + 'ValidationError', + 'regExp', + sourceCode + ); + + validate = makeValidate( + self, + RULES, + formats, + root, + refVal, + defaults, + customRules, + equal, + ucs2length, + ValidationError, + opts.regExp + ); + + refVal[0] = validate; + } catch(e) { + self.logger.error('Error compiling schema, function code:', sourceCode); + throw e; + } + + validate.schema = _schema; + validate.errors = null; + validate.refs = refs; + validate.refVal = refVal; + validate.root = isRoot ? validate : _root; + if ($async) validate.$async = true; + if (opts.sourceCode === true) { + validate.source = { + code: sourceCode, + patterns: patterns, + defaults: defaults + }; + } + + return validate; + } + + function resolveRef(baseId, ref, isRoot) { + ref = resolve.url(baseId, ref); + var refIndex = refs[ref]; + var _refVal, refCode; + if (refIndex !== undefined) { + _refVal = refVal[refIndex]; + refCode = 'refVal[' + refIndex + ']'; + return resolvedRef(_refVal, refCode); + } + if (!isRoot && root.refs) { + var rootRefId = root.refs[ref]; + if (rootRefId !== undefined) { + _refVal = root.refVal[rootRefId]; + refCode = addLocalRef(ref, _refVal); + return resolvedRef(_refVal, refCode); + } + } + + refCode = addLocalRef(ref); + var v = resolve.call(self, localCompile, root, ref); + if (v === undefined) { + var localSchema = localRefs && localRefs[ref]; + if (localSchema) { + v = resolve.inlineRef(localSchema, opts.inlineRefs) + ? localSchema + : compile.call(self, localSchema, root, localRefs, baseId); + } + } + + if (v === undefined) { + removeLocalRef(ref); + } else { + replaceLocalRef(ref, v); + return resolvedRef(v, refCode); + } + } + + function addLocalRef(ref, v) { + var refId = refVal.length; + refVal[refId] = v; + refs[ref] = refId; + return 'refVal' + refId; + } + + function removeLocalRef(ref) { + delete refs[ref]; + } + + function replaceLocalRef(ref, v) { + var refId = refs[ref]; + refVal[refId] = v; + } + + function resolvedRef(refVal, code) { + return typeof refVal == 'object' || typeof refVal == 'boolean' + ? { code: code, schema: refVal, inline: true } + : { code: code, $async: refVal && !!refVal.$async }; + } + + function usePattern(regexStr) { + var index = patternsHash[regexStr]; + if (index === undefined) { + index = patternsHash[regexStr] = patterns.length; + patterns[index] = regexStr; + } + return 'pattern' + index; + } + + function useDefault(value) { + switch (typeof value) { + case 'boolean': + case 'number': + return '' + value; + case 'string': + return util.toQuotedString(value); + case 'object': + if (value === null) return 'null'; + var valueStr = stableStringify(value); + var index = defaultsHash[valueStr]; + if (index === undefined) { + index = defaultsHash[valueStr] = defaults.length; + defaults[index] = value; + } + return 'default' + index; + } + } + + function useCustomRule(rule, schema, parentSchema, it) { + if (self._opts.validateSchema !== false) { + var deps = rule.definition.dependencies; + if (deps && !deps.every(function(keyword) { + return Object.prototype.hasOwnProperty.call(parentSchema, keyword); + })) + throw new Error('parent schema must have all required keywords: ' + deps.join(',')); + + var validateSchema = rule.definition.validateSchema; + if (validateSchema) { + var valid = validateSchema(schema); + if (!valid) { + var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); + if (self._opts.validateSchema == 'log') self.logger.error(message); + else throw new Error(message); + } + } + } + + var compile = rule.definition.compile + , inline = rule.definition.inline + , macro = rule.definition.macro; + + var validate; + if (compile) { + validate = compile.call(self, schema, parentSchema, it); + } else if (macro) { + validate = macro.call(self, schema, parentSchema, it); + if (opts.validateSchema !== false) self.validateSchema(validate, true); + } else if (inline) { + validate = inline.call(self, it, rule.keyword, schema, parentSchema); + } else { + validate = rule.definition.validate; + if (!validate) return; + } + + if (validate === undefined) + throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); + + var index = customRules.length; + customRules[index] = validate; + + return { + code: 'customRule' + index, + validate: validate + }; + } +} + + +/** + * Checks if the schema is currently compiled + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) + */ +function checkCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var index = compIndex.call(this, schema, root, baseId); + if (index >= 0) return { index: index, compiling: true }; + index = this._compilations.length; + this._compilations[index] = { + schema: schema, + root: root, + baseId: baseId + }; + return { index: index, compiling: false }; +} + + +/** + * Removes the schema from the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + */ +function endCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var i = compIndex.call(this, schema, root, baseId); + if (i >= 0) this._compilations.splice(i, 1); +} + + +/** + * Index of schema compilation in the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Integer} compilation index + */ +function compIndex(schema, root, baseId) { + /* jshint validthis: true */ + for (var i=0; i= 0xD800 && value <= 0xDBFF && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos); + if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate + } + } + return length; +}; diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/compile/util.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/compile/util.js new file mode 100644 index 0000000000000000000000000000000000000000..ef07b8c75797239e79fa51e7ab0473c4f3745b74 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/compile/util.js @@ -0,0 +1,239 @@ +'use strict'; + + +module.exports = { + copy: copy, + checkDataType: checkDataType, + checkDataTypes: checkDataTypes, + coerceToTypes: coerceToTypes, + toHash: toHash, + getProperty: getProperty, + escapeQuotes: escapeQuotes, + equal: require('fast-deep-equal'), + ucs2length: require('./ucs2length'), + varOccurences: varOccurences, + varReplace: varReplace, + schemaHasRules: schemaHasRules, + schemaHasRulesExcept: schemaHasRulesExcept, + schemaUnknownRules: schemaUnknownRules, + toQuotedString: toQuotedString, + getPathExpr: getPathExpr, + getPath: getPath, + getData: getData, + unescapeFragment: unescapeFragment, + unescapeJsonPointer: unescapeJsonPointer, + escapeFragment: escapeFragment, + escapeJsonPointer: escapeJsonPointer +}; + + +function copy(o, to) { + to = to || {}; + for (var key in o) to[key] = o[key]; + return to; +} + + +function checkDataType(dataType, data, strictNumbers, negate) { + var EQUAL = negate ? ' !== ' : ' === ' + , AND = negate ? ' || ' : ' && ' + , OK = negate ? '!' : '' + , NOT = negate ? '' : '!'; + switch (dataType) { + case 'null': return data + EQUAL + 'null'; + case 'array': return OK + 'Array.isArray(' + data + ')'; + case 'object': return '(' + OK + data + AND + + 'typeof ' + data + EQUAL + '"object"' + AND + + NOT + 'Array.isArray(' + data + '))'; + case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND + + NOT + '(' + data + ' % 1)' + + AND + data + EQUAL + data + + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; + case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' + + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; + default: return 'typeof ' + data + EQUAL + '"' + dataType + '"'; + } +} + + +function checkDataTypes(dataTypes, data, strictNumbers) { + switch (dataTypes.length) { + case 1: return checkDataType(dataTypes[0], data, strictNumbers, true); + default: + var code = ''; + var types = toHash(dataTypes); + if (types.array && types.object) { + code = types.null ? '(': '(!' + data + ' || '; + code += 'typeof ' + data + ' !== "object")'; + delete types.null; + delete types.array; + delete types.object; + } + if (types.number) delete types.integer; + for (var t in types) + code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true); + + return code; + } +} + + +var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); +function coerceToTypes(optionCoerceTypes, dataTypes) { + if (Array.isArray(dataTypes)) { + var types = []; + for (var i=0; i= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); + return paths[lvl - up]; + } + + if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); + data = 'data' + ((lvl - up) || ''); + if (!jsonPointer) return data; + } + + var expr = data; + var segments = jsonPointer.split('/'); + for (var i=0; i' + , $notOp = $isMax ? '>' : '<' + , $errorKeyword = undefined; + + if (!($isData || typeof $schema == 'number' || $schema === undefined)) { + throw new Error($keyword + ' must be number'); + } + if (!($isDataExcl || $schemaExcl === undefined + || typeof $schemaExcl == 'number' + || typeof $schemaExcl == 'boolean')) { + throw new Error($exclusiveKeyword + ' must be number or boolean'); + } +}} + +{{? $isDataExcl }} + {{ + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr) + , $exclusive = 'exclusive' + $lvl + , $exclType = 'exclType' + $lvl + , $exclIsNumber = 'exclIsNumber' + $lvl + , $opExpr = 'op' + $lvl + , $opStr = '\' + ' + $opExpr + ' + \''; + }} + var schemaExcl{{=$lvl}} = {{=$schemaValueExcl}}; + {{ $schemaValueExcl = 'schemaExcl' + $lvl; }} + + var {{=$exclusive}}; + var {{=$exclType}} = typeof {{=$schemaValueExcl}}; + if ({{=$exclType}} != 'boolean' && {{=$exclType}} != 'undefined' && {{=$exclType}} != 'number') { + {{ var $errorKeyword = $exclusiveKeyword; }} + {{# def.error:'_exclusiveLimit' }} + } else if ({{# def.$dataNotType:'number' }} + {{=$exclType}} == 'number' + ? ( + ({{=$exclusive}} = {{=$schemaValue}} === undefined || {{=$schemaValueExcl}} {{=$op}}= {{=$schemaValue}}) + ? {{=$data}} {{=$notOp}}= {{=$schemaValueExcl}} + : {{=$data}} {{=$notOp}} {{=$schemaValue}} + ) + : ( + ({{=$exclusive}} = {{=$schemaValueExcl}} === true) + ? {{=$data}} {{=$notOp}}= {{=$schemaValue}} + : {{=$data}} {{=$notOp}} {{=$schemaValue}} + ) + || {{=$data}} !== {{=$data}}) { + var op{{=$lvl}} = {{=$exclusive}} ? '{{=$op}}' : '{{=$op}}='; + {{ + if ($schema === undefined) { + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaValueExcl; + $isData = $isDataExcl; + } + }} +{{??}} + {{ + var $exclIsNumber = typeof $schemaExcl == 'number' + , $opStr = $op; /*used in error*/ + }} + + {{? $exclIsNumber && $isData }} + {{ var $opExpr = '\'' + $opStr + '\''; /*used in error*/ }} + if ({{# def.$dataNotType:'number' }} + ( {{=$schemaValue}} === undefined + || {{=$schemaExcl}} {{=$op}}= {{=$schemaValue}} + ? {{=$data}} {{=$notOp}}= {{=$schemaExcl}} + : {{=$data}} {{=$notOp}} {{=$schemaValue}} ) + || {{=$data}} !== {{=$data}}) { + {{??}} + {{ + if ($exclIsNumber && $schema === undefined) { + {{# def.setExclusiveLimit }} + $schemaValue = $schemaExcl; + $notOp += '='; + } else { + if ($exclIsNumber) + $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); + + if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { + {{# def.setExclusiveLimit }} + $notOp += '='; + } else { + $exclusive = false; + $opStr += '='; + } + } + + var $opExpr = '\'' + $opStr + '\''; /*used in error*/ + }} + + if ({{# def.$dataNotType:'number' }} + {{=$data}} {{=$notOp}} {{=$schemaValue}} + || {{=$data}} !== {{=$data}}) { + {{?}} +{{?}} + {{ $errorKeyword = $errorKeyword || $keyword; }} + {{# def.error:'_limit' }} + } {{? $breakOnError }} else { {{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/_limitItems.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/_limitItems.jst new file mode 100644 index 0000000000000000000000000000000000000000..741329e7769ffc64f6e3214280772cdd1d7e1396 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/_limitItems.jst @@ -0,0 +1,12 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{# def.numberKeyword }} + +{{ var $op = $keyword == 'maxItems' ? '>' : '<'; }} +if ({{# def.$dataNotType:'number' }} {{=$data}}.length {{=$op}} {{=$schemaValue}}) { + {{ var $errorKeyword = $keyword; }} + {{# def.error:'_limitItems' }} +} {{? $breakOnError }} else { {{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/_limitLength.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/_limitLength.jst new file mode 100644 index 0000000000000000000000000000000000000000..285c66bd2eed2d3b6ec5f8586835665e18209c19 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/_limitLength.jst @@ -0,0 +1,12 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{# def.numberKeyword }} + +{{ var $op = $keyword == 'maxLength' ? '>' : '<'; }} +if ({{# def.$dataNotType:'number' }} {{# def.strLength }} {{=$op}} {{=$schemaValue}}) { + {{ var $errorKeyword = $keyword; }} + {{# def.error:'_limitLength' }} +} {{? $breakOnError }} else { {{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/_limitProperties.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/_limitProperties.jst new file mode 100644 index 0000000000000000000000000000000000000000..c4c21551abc3dbe491c55113dbeabf42253a2204 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/_limitProperties.jst @@ -0,0 +1,12 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{# def.numberKeyword }} + +{{ var $op = $keyword == 'maxProperties' ? '>' : '<'; }} +if ({{# def.$dataNotType:'number' }} Object.keys({{=$data}}).length {{=$op}} {{=$schemaValue}}) { + {{ var $errorKeyword = $keyword; }} + {{# def.error:'_limitProperties' }} +} {{? $breakOnError }} else { {{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/allOf.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/allOf.jst new file mode 100644 index 0000000000000000000000000000000000000000..0e782fe98e2da19e350ab69803cb152a70b749b4 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/allOf.jst @@ -0,0 +1,32 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + +{{ + var $currentBaseId = $it.baseId + , $allSchemasEmpty = true; +}} + +{{~ $schema:$sch:$i }} + {{? {{# def.nonEmptySchema:$sch }} }} + {{ + $allSchemasEmpty = false; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + }} + + {{# def.insertSubschemaCode }} + + {{# def.ifResultValid }} + {{?}} +{{~}} + +{{? $breakOnError }} + {{? $allSchemasEmpty }} + if (true) { + {{??}} + {{= $closingBraces.slice(0,-1) }} + {{?}} +{{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/anyOf.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/anyOf.jst new file mode 100644 index 0000000000000000000000000000000000000000..ea909ee628e6b3231437e4c1ec88527beebbab89 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/anyOf.jst @@ -0,0 +1,46 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + +{{ + var $noEmptySchema = $schema.every(function($sch) { + return {{# def.nonEmptySchema:$sch }}; + }); +}} +{{? $noEmptySchema }} + {{ var $currentBaseId = $it.baseId; }} + var {{=$errs}} = errors; + var {{=$valid}} = false; + + {{# def.setCompositeRule }} + + {{~ $schema:$sch:$i }} + {{ + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + }} + + {{# def.insertSubschemaCode }} + + {{=$valid}} = {{=$valid}} || {{=$nextValid}}; + + if (!{{=$valid}}) { + {{ $closingBraces += '}'; }} + {{~}} + + {{# def.resetCompositeRule }} + + {{= $closingBraces }} + + if (!{{=$valid}}) { + {{# def.extraError:'anyOf' }} + } else { + {{# def.resetErrors }} + {{? it.opts.allErrors }} } {{?}} +{{??}} + {{? $breakOnError }} + if (true) { + {{?}} +{{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/coerce.def b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/coerce.def new file mode 100644 index 0000000000000000000000000000000000000000..c947ed6af81d2583bf2bbdd9e0089b623b0df781 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/coerce.def @@ -0,0 +1,51 @@ +{{## def.coerceType: + {{ + var $dataType = 'dataType' + $lvl + , $coerced = 'coerced' + $lvl; + }} + var {{=$dataType}} = typeof {{=$data}}; + var {{=$coerced}} = undefined; + + {{? it.opts.coerceTypes == 'array' }} + if ({{=$dataType}} == 'object' && Array.isArray({{=$data}}) && {{=$data}}.length == 1) { + {{=$data}} = {{=$data}}[0]; + {{=$dataType}} = typeof {{=$data}}; + if ({{=it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)}}) {{=$coerced}} = {{=$data}}; + } + {{?}} + + if ({{=$coerced}} !== undefined) ; + {{~ $coerceToTypes:$type:$i }} + {{? $type == 'string' }} + else if ({{=$dataType}} == 'number' || {{=$dataType}} == 'boolean') + {{=$coerced}} = '' + {{=$data}}; + else if ({{=$data}} === null) {{=$coerced}} = ''; + {{?? $type == 'number' || $type == 'integer' }} + else if ({{=$dataType}} == 'boolean' || {{=$data}} === null + || ({{=$dataType}} == 'string' && {{=$data}} && {{=$data}} == +{{=$data}} + {{? $type == 'integer' }} && !({{=$data}} % 1){{?}})) + {{=$coerced}} = +{{=$data}}; + {{?? $type == 'boolean' }} + else if ({{=$data}} === 'false' || {{=$data}} === 0 || {{=$data}} === null) + {{=$coerced}} = false; + else if ({{=$data}} === 'true' || {{=$data}} === 1) + {{=$coerced}} = true; + {{?? $type == 'null' }} + else if ({{=$data}} === '' || {{=$data}} === 0 || {{=$data}} === false) + {{=$coerced}} = null; + {{?? it.opts.coerceTypes == 'array' && $type == 'array' }} + else if ({{=$dataType}} == 'string' || {{=$dataType}} == 'number' || {{=$dataType}} == 'boolean' || {{=$data}} == null) + {{=$coerced}} = [{{=$data}}]; + {{?}} + {{~}} + else { + {{# def.error:'type' }} + } + + if ({{=$coerced}} !== undefined) { + {{# def.setParentData }} + {{=$data}} = {{=$coerced}}; + {{? !$dataLvl }}if ({{=$parentData}} !== undefined){{?}} + {{=$parentData}}[{{=$parentDataProperty}}] = {{=$coerced}}; + } +#}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/comment.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/comment.jst new file mode 100644 index 0000000000000000000000000000000000000000..f95915035c6b5b9e5b28f98235fd78c6d04feb2b --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/comment.jst @@ -0,0 +1,9 @@ +{{# def.definitions }} +{{# def.setupKeyword }} + +{{ var $comment = it.util.toQuotedString($schema); }} +{{? it.opts.$comment === true }} + console.log({{=$comment}}); +{{?? typeof it.opts.$comment == 'function' }} + self._opts.$comment({{=$comment}}, {{=it.util.toQuotedString($errSchemaPath)}}, validate.root.schema); +{{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/const.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/const.jst new file mode 100644 index 0000000000000000000000000000000000000000..2aa22980d7fc6d93a0cb397229888b86e0b2cd82 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/const.jst @@ -0,0 +1,11 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{? !$isData }} + var schema{{=$lvl}} = validate.schema{{=$schemaPath}}; +{{?}} +var {{=$valid}} = equal({{=$data}}, schema{{=$lvl}}); +{{# def.checkError:'const' }} +{{? $breakOnError }} else { {{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/contains.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/contains.jst new file mode 100644 index 0000000000000000000000000000000000000000..4dc9967418dece83a6cdb31700818a1b316b2d62 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/contains.jst @@ -0,0 +1,55 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + + +{{ + var $idx = 'i' + $lvl + , $dataNxt = $it.dataLevel = it.dataLevel + 1 + , $nextData = 'data' + $dataNxt + , $currentBaseId = it.baseId + , $nonEmptySchema = {{# def.nonEmptySchema:$schema }}; +}} + +var {{=$errs}} = errors; +var {{=$valid}}; + +{{? $nonEmptySchema }} + {{# def.setCompositeRule }} + + {{ + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + }} + + var {{=$nextValid}} = false; + + for (var {{=$idx}} = 0; {{=$idx}} < {{=$data}}.length; {{=$idx}}++) { + {{ + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + }} + + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} + + if ({{=$nextValid}}) break; + } + + {{# def.resetCompositeRule }} + {{= $closingBraces }} + + if (!{{=$nextValid}}) { +{{??}} + if ({{=$data}}.length == 0) { +{{?}} + + {{# def.error:'contains' }} + } else { + {{? $nonEmptySchema }} + {{# def.resetErrors }} + {{?}} + {{? it.opts.allErrors }} } {{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/custom.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/custom.jst new file mode 100644 index 0000000000000000000000000000000000000000..d30588fb0b4b5f41507b566058efd150f786bfaf --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/custom.jst @@ -0,0 +1,191 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{ + var $rule = this + , $definition = 'definition' + $lvl + , $rDef = $rule.definition + , $closingBraces = ''; + var $validate = $rDef.validate; + var $compile, $inline, $macro, $ruleValidate, $validateCode; +}} + +{{? $isData && $rDef.$data }} + {{ + $validateCode = 'keywordValidate' + $lvl; + var $validateSchema = $rDef.validateSchema; + }} + var {{=$definition}} = RULES.custom['{{=$keyword}}'].definition; + var {{=$validateCode}} = {{=$definition}}.validate; +{{??}} + {{ + $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); + if (!$ruleValidate) return; + $schemaValue = 'validate.schema' + $schemaPath; + $validateCode = $ruleValidate.code; + $compile = $rDef.compile; + $inline = $rDef.inline; + $macro = $rDef.macro; + }} +{{?}} + +{{ + var $ruleErrs = $validateCode + '.errors' + , $i = 'i' + $lvl + , $ruleErr = 'ruleErr' + $lvl + , $asyncKeyword = $rDef.async; + + if ($asyncKeyword && !it.async) + throw new Error('async keyword in sync schema'); +}} + + +{{? !($inline || $macro) }}{{=$ruleErrs}} = null;{{?}} +var {{=$errs}} = errors; +var {{=$valid}}; + +{{## def.callRuleValidate: + {{=$validateCode}}.call( + {{? it.opts.passContext }}this{{??}}self{{?}} + {{? $compile || $rDef.schema === false }} + , {{=$data}} + {{??}} + , {{=$schemaValue}} + , {{=$data}} + , validate.schema{{=it.schemaPath}} + {{?}} + , {{# def.dataPath }} + {{# def.passParentData }} + , rootData + ) +#}} + +{{## def.extendErrors:_inline: + for (var {{=$i}}={{=$errs}}; {{=$i}} 0) + || _schema === false + : it.util.schemaHasRules(_schema, it.RULES.all)) +#}} + + +{{## def.strLength: + {{? it.opts.unicode === false }} + {{=$data}}.length + {{??}} + ucs2length({{=$data}}) + {{?}} +#}} + + +{{## def.willOptimize: + it.util.varOccurences($code, $nextData) < 2 +#}} + + +{{## def.generateSubschemaCode: + {{ + var $code = it.validate($it); + $it.baseId = $currentBaseId; + }} +#}} + + +{{## def.insertSubschemaCode: + {{= it.validate($it) }} + {{ $it.baseId = $currentBaseId; }} +#}} + + +{{## def._optimizeValidate: + it.util.varReplace($code, $nextData, $passData) +#}} + + +{{## def.optimizeValidate: + {{? {{# def.willOptimize}} }} + {{= {{# def._optimizeValidate }} }} + {{??}} + var {{=$nextData}} = {{=$passData}}; + {{= $code }} + {{?}} +#}} + + +{{## def.$data: + {{ + var $isData = it.opts.$data && $schema && $schema.$data + , $schemaValue; + }} + {{? $isData }} + var schema{{=$lvl}} = {{= it.util.getData($schema.$data, $dataLvl, it.dataPathArr) }}; + {{ $schemaValue = 'schema' + $lvl; }} + {{??}} + {{ $schemaValue = $schema; }} + {{?}} +#}} + + +{{## def.$dataNotType:_type: + {{?$isData}} ({{=$schemaValue}} !== undefined && typeof {{=$schemaValue}} != _type) || {{?}} +#}} + + +{{## def.check$dataIsArray: + if (schema{{=$lvl}} === undefined) {{=$valid}} = true; + else if (!Array.isArray(schema{{=$lvl}})) {{=$valid}} = false; + else { +#}} + + +{{## def.numberKeyword: + {{? !($isData || typeof $schema == 'number') }} + {{ throw new Error($keyword + ' must be number'); }} + {{?}} +#}} + + +{{## def.beginDefOut: + {{ + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + }} +#}} + + +{{## def.storeDefOut:_variable: + {{ + var _variable = out; + out = $$outStack.pop(); + }} +#}} + + +{{## def.dataPath:(dataPath || ''){{? it.errorPath != '""'}} + {{= it.errorPath }}{{?}}#}} + +{{## def.setParentData: + {{ + var $parentData = $dataLvl ? 'data' + (($dataLvl-1)||'') : 'parentData' + , $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + }} +#}} + +{{## def.passParentData: + {{# def.setParentData }} + , {{= $parentData }} + , {{= $parentDataProperty }} +#}} + + +{{## def.iterateProperties: + {{? $ownProperties }} + {{=$dataProperties}} = {{=$dataProperties}} || Object.keys({{=$data}}); + for (var {{=$idx}}=0; {{=$idx}}<{{=$dataProperties}}.length; {{=$idx}}++) { + var {{=$key}} = {{=$dataProperties}}[{{=$idx}}]; + {{??}} + for (var {{=$key}} in {{=$data}}) { + {{?}} +#}} + + +{{## def.noPropertyInData: + {{=$useData}} === undefined + {{? $ownProperties }} + || !{{# def.isOwnProperty }} + {{?}} +#}} + + +{{## def.isOwnProperty: + Object.prototype.hasOwnProperty.call({{=$data}}, '{{=it.util.escapeQuotes($propertyKey)}}') +#}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/dependencies.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/dependencies.jst new file mode 100644 index 0000000000000000000000000000000000000000..e4bdddec8eb9537ffb3621f1ce42b63d6e87a2ad --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/dependencies.jst @@ -0,0 +1,79 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.missing }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + + +{{## def.propertyInData: + {{=$data}}{{= it.util.getProperty($property) }} !== undefined + {{? $ownProperties }} + && Object.prototype.hasOwnProperty.call({{=$data}}, '{{=it.util.escapeQuotes($property)}}') + {{?}} +#}} + + +{{ + var $schemaDeps = {} + , $propertyDeps = {} + , $ownProperties = it.opts.ownProperties; + + for ($property in $schema) { + if ($property == '__proto__') continue; + var $sch = $schema[$property]; + var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps; + $deps[$property] = $sch; + } +}} + +var {{=$errs}} = errors; + +{{ var $currentErrorPath = it.errorPath; }} + +var missing{{=$lvl}}; +{{ for (var $property in $propertyDeps) { }} + {{ $deps = $propertyDeps[$property]; }} + {{? $deps.length }} + if ({{# def.propertyInData }} + {{? $breakOnError }} + && ({{# def.checkMissingProperty:$deps }})) { + {{# def.errorMissingProperty:'dependencies' }} + {{??}} + ) { + {{~ $deps:$propertyKey }} + {{# def.allErrorsMissingProperty:'dependencies' }} + {{~}} + {{?}} + } {{# def.elseIfValid }} + {{?}} +{{ } }} + +{{ + it.errorPath = $currentErrorPath; + var $currentBaseId = $it.baseId; +}} + + +{{ for (var $property in $schemaDeps) { }} + {{ var $sch = $schemaDeps[$property]; }} + {{? {{# def.nonEmptySchema:$sch }} }} + {{=$nextValid}} = true; + + if ({{# def.propertyInData }}) { + {{ + $it.schema = $sch; + $it.schemaPath = $schemaPath + it.util.getProperty($property); + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property); + }} + + {{# def.insertSubschemaCode }} + } + + {{# def.ifResultValid }} + {{?}} +{{ } }} + +{{? $breakOnError }} + {{= $closingBraces }} + if ({{=$errs}} == errors) { +{{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/enum.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/enum.jst new file mode 100644 index 0000000000000000000000000000000000000000..357c2e8c081d125ac0adabcb91bf6da44dc4652f --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/enum.jst @@ -0,0 +1,30 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{ + var $i = 'i' + $lvl + , $vSchema = 'schema' + $lvl; +}} + +{{? !$isData }} + var {{=$vSchema}} = validate.schema{{=$schemaPath}}; +{{?}} +var {{=$valid}}; + +{{?$isData}}{{# def.check$dataIsArray }}{{?}} + +{{=$valid}} = false; + +for (var {{=$i}}=0; {{=$i}}<{{=$vSchema}}.length; {{=$i}}++) + if (equal({{=$data}}, {{=$vSchema}}[{{=$i}}])) { + {{=$valid}} = true; + break; + } + +{{? $isData }} } {{?}} + +{{# def.checkError:'enum' }} + +{{? $breakOnError }} else { {{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/errors.def b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/errors.def new file mode 100644 index 0000000000000000000000000000000000000000..5c5752cb04db907abe70ae71a5eae347f18274f8 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/errors.def @@ -0,0 +1,194 @@ +{{# def.definitions }} + +{{## def._error:_rule: + {{ 'istanbul ignore else'; }} + {{? it.createErrors !== false }} + { + keyword: '{{= $errorKeyword || _rule }}' + , dataPath: (dataPath || '') + {{= it.errorPath }} + , schemaPath: {{=it.util.toQuotedString($errSchemaPath)}} + , params: {{# def._errorParams[_rule] }} + {{? it.opts.messages !== false }} + , message: {{# def._errorMessages[_rule] }} + {{?}} + {{? it.opts.verbose }} + , schema: {{# def._errorSchemas[_rule] }} + , parentSchema: validate.schema{{=it.schemaPath}} + , data: {{=$data}} + {{?}} + } + {{??}} + {} + {{?}} +#}} + + +{{## def._addError:_rule: + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; +#}} + + +{{## def.addError:_rule: + var err = {{# def._error:_rule }}; + {{# def._addError:_rule }} +#}} + + +{{## def.error:_rule: + {{# def.beginDefOut}} + {{# def._error:_rule }} + {{# def.storeDefOut:__err }} + + {{? !it.compositeRule && $breakOnError }} + {{ 'istanbul ignore if'; }} + {{? it.async }} + throw new ValidationError([{{=__err}}]); + {{??}} + validate.errors = [{{=__err}}]; + return false; + {{?}} + {{??}} + var err = {{=__err}}; + {{# def._addError:_rule }} + {{?}} +#}} + + +{{## def.extraError:_rule: + {{# def.addError:_rule}} + {{? !it.compositeRule && $breakOnError }} + {{ 'istanbul ignore if'; }} + {{? it.async }} + throw new ValidationError(vErrors); + {{??}} + validate.errors = vErrors; + return false; + {{?}} + {{?}} +#}} + + +{{## def.checkError:_rule: + if (!{{=$valid}}) { + {{# def.error:_rule }} + } +#}} + + +{{## def.resetErrors: + errors = {{=$errs}}; + if (vErrors !== null) { + if ({{=$errs}}) vErrors.length = {{=$errs}}; + else vErrors = null; + } +#}} + + +{{## def.concatSchema:{{?$isData}}' + {{=$schemaValue}} + '{{??}}{{=$schema}}{{?}}#}} +{{## def.appendSchema:{{?$isData}}' + {{=$schemaValue}}{{??}}{{=$schemaValue}}'{{?}}#}} +{{## def.concatSchemaEQ:{{?$isData}}' + {{=$schemaValue}} + '{{??}}{{=it.util.escapeQuotes($schema)}}{{?}}#}} + +{{## def._errorMessages = { + 'false schema': "'boolean schema is false'", + $ref: "'can\\\'t resolve reference {{=it.util.escapeQuotes($schema)}}'", + additionalItems: "'should NOT have more than {{=$schema.length}} items'", + additionalProperties: "'{{? it.opts._errorDataPathProperty }}is an invalid additional property{{??}}should NOT have additional properties{{?}}'", + anyOf: "'should match some schema in anyOf'", + const: "'should be equal to constant'", + contains: "'should contain a valid item'", + dependencies: "'should have {{? $deps.length == 1 }}property {{= it.util.escapeQuotes($deps[0]) }}{{??}}properties {{= it.util.escapeQuotes($deps.join(\", \")) }}{{?}} when property {{= it.util.escapeQuotes($property) }} is present'", + 'enum': "'should be equal to one of the allowed values'", + format: "'should match format \"{{#def.concatSchemaEQ}}\"'", + 'if': "'should match \"' + {{=$ifClause}} + '\" schema'", + _limit: "'should be {{=$opStr}} {{#def.appendSchema}}", + _exclusiveLimit: "'{{=$exclusiveKeyword}} should be boolean'", + _limitItems: "'should NOT have {{?$keyword=='maxItems'}}more{{??}}fewer{{?}} than {{#def.concatSchema}} items'", + _limitLength: "'should NOT be {{?$keyword=='maxLength'}}longer{{??}}shorter{{?}} than {{#def.concatSchema}} characters'", + _limitProperties:"'should NOT have {{?$keyword=='maxProperties'}}more{{??}}fewer{{?}} than {{#def.concatSchema}} properties'", + multipleOf: "'should be multiple of {{#def.appendSchema}}", + not: "'should NOT be valid'", + oneOf: "'should match exactly one schema in oneOf'", + pattern: "'should match pattern \"{{#def.concatSchemaEQ}}\"'", + propertyNames: "'property name \\'{{=$invalidName}}\\' is invalid'", + required: "'{{? it.opts._errorDataPathProperty }}is a required property{{??}}should have required property \\'{{=$missingProperty}}\\'{{?}}'", + type: "'should be {{? $typeIsArray }}{{= $typeSchema.join(\",\") }}{{??}}{{=$typeSchema}}{{?}}'", + uniqueItems: "'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)'", + custom: "'should pass \"{{=$rule.keyword}}\" keyword validation'", + patternRequired: "'should have property matching pattern \\'{{=$missingPattern}}\\''", + switch: "'should pass \"switch\" keyword validation'", + _formatLimit: "'should be {{=$opStr}} \"{{#def.concatSchemaEQ}}\"'", + _formatExclusiveLimit: "'{{=$exclusiveKeyword}} should be boolean'" +} #}} + + +{{## def.schemaRefOrVal: {{?$isData}}validate.schema{{=$schemaPath}}{{??}}{{=$schema}}{{?}} #}} +{{## def.schemaRefOrQS: {{?$isData}}validate.schema{{=$schemaPath}}{{??}}{{=it.util.toQuotedString($schema)}}{{?}} #}} + +{{## def._errorSchemas = { + 'false schema': "false", + $ref: "{{=it.util.toQuotedString($schema)}}", + additionalItems: "false", + additionalProperties: "false", + anyOf: "validate.schema{{=$schemaPath}}", + const: "validate.schema{{=$schemaPath}}", + contains: "validate.schema{{=$schemaPath}}", + dependencies: "validate.schema{{=$schemaPath}}", + 'enum': "validate.schema{{=$schemaPath}}", + format: "{{#def.schemaRefOrQS}}", + 'if': "validate.schema{{=$schemaPath}}", + _limit: "{{#def.schemaRefOrVal}}", + _exclusiveLimit: "validate.schema{{=$schemaPath}}", + _limitItems: "{{#def.schemaRefOrVal}}", + _limitLength: "{{#def.schemaRefOrVal}}", + _limitProperties:"{{#def.schemaRefOrVal}}", + multipleOf: "{{#def.schemaRefOrVal}}", + not: "validate.schema{{=$schemaPath}}", + oneOf: "validate.schema{{=$schemaPath}}", + pattern: "{{#def.schemaRefOrQS}}", + propertyNames: "validate.schema{{=$schemaPath}}", + required: "validate.schema{{=$schemaPath}}", + type: "validate.schema{{=$schemaPath}}", + uniqueItems: "{{#def.schemaRefOrVal}}", + custom: "validate.schema{{=$schemaPath}}", + patternRequired: "validate.schema{{=$schemaPath}}", + switch: "validate.schema{{=$schemaPath}}", + _formatLimit: "{{#def.schemaRefOrQS}}", + _formatExclusiveLimit: "validate.schema{{=$schemaPath}}" +} #}} + + +{{## def.schemaValueQS: {{?$isData}}{{=$schemaValue}}{{??}}{{=it.util.toQuotedString($schema)}}{{?}} #}} + +{{## def._errorParams = { + 'false schema': "{}", + $ref: "{ ref: '{{=it.util.escapeQuotes($schema)}}' }", + additionalItems: "{ limit: {{=$schema.length}} }", + additionalProperties: "{ additionalProperty: '{{=$additionalProperty}}' }", + anyOf: "{}", + const: "{ allowedValue: schema{{=$lvl}} }", + contains: "{}", + dependencies: "{ property: '{{= it.util.escapeQuotes($property) }}', missingProperty: '{{=$missingProperty}}', depsCount: {{=$deps.length}}, deps: '{{= it.util.escapeQuotes($deps.length==1 ? $deps[0] : $deps.join(\", \")) }}' }", + 'enum': "{ allowedValues: schema{{=$lvl}} }", + format: "{ format: {{#def.schemaValueQS}} }", + 'if': "{ failingKeyword: {{=$ifClause}} }", + _limit: "{ comparison: {{=$opExpr}}, limit: {{=$schemaValue}}, exclusive: {{=$exclusive}} }", + _exclusiveLimit: "{}", + _limitItems: "{ limit: {{=$schemaValue}} }", + _limitLength: "{ limit: {{=$schemaValue}} }", + _limitProperties:"{ limit: {{=$schemaValue}} }", + multipleOf: "{ multipleOf: {{=$schemaValue}} }", + not: "{}", + oneOf: "{ passingSchemas: {{=$passingSchemas}} }", + pattern: "{ pattern: {{#def.schemaValueQS}} }", + propertyNames: "{ propertyName: '{{=$invalidName}}' }", + required: "{ missingProperty: '{{=$missingProperty}}' }", + type: "{ type: '{{? $typeIsArray }}{{= $typeSchema.join(\",\") }}{{??}}{{=$typeSchema}}{{?}}' }", + uniqueItems: "{ i: i, j: j }", + custom: "{ keyword: '{{=$rule.keyword}}' }", + patternRequired: "{ missingPattern: '{{=$missingPattern}}' }", + switch: "{ caseIndex: {{=$caseIndex}} }", + _formatLimit: "{ comparison: {{=$opExpr}}, limit: {{#def.schemaValueQS}}, exclusive: {{=$exclusive}} }", + _formatExclusiveLimit: "{}" +} #}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/format.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/format.jst new file mode 100644 index 0000000000000000000000000000000000000000..37f14da80ef8f0697e4333eee663b87799b0baa4 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/format.jst @@ -0,0 +1,106 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} + +{{## def.skipFormat: + {{? $breakOnError }} if (true) { {{?}} + {{ return out; }} +#}} + +{{? it.opts.format === false }}{{# def.skipFormat }}{{?}} + + +{{# def.$data }} + + +{{## def.$dataCheckFormat: + {{# def.$dataNotType:'string' }} + ({{? $unknownFormats != 'ignore' }} + ({{=$schemaValue}} && !{{=$format}} + {{? $allowUnknown }} + && self._opts.unknownFormats.indexOf({{=$schemaValue}}) == -1 + {{?}}) || + {{?}} + ({{=$format}} && {{=$formatType}} == '{{=$ruleType}}' + && !(typeof {{=$format}} == 'function' + ? {{? it.async}} + (async{{=$lvl}} ? await {{=$format}}({{=$data}}) : {{=$format}}({{=$data}})) + {{??}} + {{=$format}}({{=$data}}) + {{?}} + : {{=$format}}.test({{=$data}})))) +#}} + +{{## def.checkFormat: + {{ + var $formatRef = 'formats' + it.util.getProperty($schema); + if ($isObject) $formatRef += '.validate'; + }} + {{? typeof $format == 'function' }} + {{=$formatRef}}({{=$data}}) + {{??}} + {{=$formatRef}}.test({{=$data}}) + {{?}} +#}} + + +{{ + var $unknownFormats = it.opts.unknownFormats + , $allowUnknown = Array.isArray($unknownFormats); +}} + +{{? $isData }} + {{ + var $format = 'format' + $lvl + , $isObject = 'isObject' + $lvl + , $formatType = 'formatType' + $lvl; + }} + var {{=$format}} = formats[{{=$schemaValue}}]; + var {{=$isObject}} = typeof {{=$format}} == 'object' + && !({{=$format}} instanceof RegExp) + && {{=$format}}.validate; + var {{=$formatType}} = {{=$isObject}} && {{=$format}}.type || 'string'; + if ({{=$isObject}}) { + {{? it.async}} + var async{{=$lvl}} = {{=$format}}.async; + {{?}} + {{=$format}} = {{=$format}}.validate; + } + if ({{# def.$dataCheckFormat }}) { +{{??}} + {{ var $format = it.formats[$schema]; }} + {{? !$format }} + {{? $unknownFormats == 'ignore' }} + {{ it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); }} + {{# def.skipFormat }} + {{?? $allowUnknown && $unknownFormats.indexOf($schema) >= 0 }} + {{# def.skipFormat }} + {{??}} + {{ throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); }} + {{?}} + {{?}} + {{ + var $isObject = typeof $format == 'object' + && !($format instanceof RegExp) + && $format.validate; + var $formatType = $isObject && $format.type || 'string'; + if ($isObject) { + var $async = $format.async === true; + $format = $format.validate; + } + }} + {{? $formatType != $ruleType }} + {{# def.skipFormat }} + {{?}} + {{? $async }} + {{ + if (!it.async) throw new Error('async format in sync schema'); + var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; + }} + if (!(await {{=$formatRef}}({{=$data}}))) { + {{??}} + if (!{{# def.checkFormat }}) { + {{?}} +{{?}} + {{# def.error:'format' }} + } {{? $breakOnError }} else { {{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/if.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/if.jst new file mode 100644 index 0000000000000000000000000000000000000000..adb50361245a1f6a19b4fcb245a48b43f1fc933e --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/if.jst @@ -0,0 +1,73 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + + +{{## def.validateIfClause:_clause: + {{ + $it.schema = it.schema['_clause']; + $it.schemaPath = it.schemaPath + '._clause'; + $it.errSchemaPath = it.errSchemaPath + '/_clause'; + }} + {{# def.insertSubschemaCode }} + {{=$valid}} = {{=$nextValid}}; + {{? $thenPresent && $elsePresent }} + {{ $ifClause = 'ifClause' + $lvl; }} + var {{=$ifClause}} = '_clause'; + {{??}} + {{ $ifClause = '\'_clause\''; }} + {{?}} +#}} + +{{ + var $thenSch = it.schema['then'] + , $elseSch = it.schema['else'] + , $thenPresent = $thenSch !== undefined && {{# def.nonEmptySchema:$thenSch }} + , $elsePresent = $elseSch !== undefined && {{# def.nonEmptySchema:$elseSch }} + , $currentBaseId = $it.baseId; +}} + +{{? $thenPresent || $elsePresent }} + {{ + var $ifClause; + $it.createErrors = false; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + }} + var {{=$errs}} = errors; + var {{=$valid}} = true; + + {{# def.setCompositeRule }} + {{# def.insertSubschemaCode }} + {{ $it.createErrors = true; }} + {{# def.resetErrors }} + {{# def.resetCompositeRule }} + + {{? $thenPresent }} + if ({{=$nextValid}}) { + {{# def.validateIfClause:then }} + } + {{? $elsePresent }} + else { + {{?}} + {{??}} + if (!{{=$nextValid}}) { + {{?}} + + {{? $elsePresent }} + {{# def.validateIfClause:else }} + } + {{?}} + + if (!{{=$valid}}) { + {{# def.extraError:'if' }} + } + {{? $breakOnError }} else { {{?}} +{{??}} + {{? $breakOnError }} + if (true) { + {{?}} +{{?}} + diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/items.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/items.jst new file mode 100644 index 0000000000000000000000000000000000000000..acc932a26eea8cb00f21a813bd93c400707d3f54 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/items.jst @@ -0,0 +1,98 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + + +{{## def.validateItems:startFrom: + for (var {{=$idx}} = {{=startFrom}}; {{=$idx}} < {{=$data}}.length; {{=$idx}}++) { + {{ + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + }} + + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} + + {{? $breakOnError }} + if (!{{=$nextValid}}) break; + {{?}} + } +#}} + +{{ + var $idx = 'i' + $lvl + , $dataNxt = $it.dataLevel = it.dataLevel + 1 + , $nextData = 'data' + $dataNxt + , $currentBaseId = it.baseId; +}} + +var {{=$errs}} = errors; +var {{=$valid}}; + +{{? Array.isArray($schema) }} + {{ /* 'items' is an array of schemas */}} + {{ var $additionalItems = it.schema.additionalItems; }} + {{? $additionalItems === false }} + {{=$valid}} = {{=$data}}.length <= {{= $schema.length }}; + {{ + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalItems'; + }} + {{# def.checkError:'additionalItems' }} + {{ $errSchemaPath = $currErrSchemaPath; }} + {{# def.elseIfValid}} + {{?}} + + {{~ $schema:$sch:$i }} + {{? {{# def.nonEmptySchema:$sch }} }} + {{=$nextValid}} = true; + + if ({{=$data}}.length > {{=$i}}) { + {{ + var $passData = $data + '[' + $i + ']'; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); + $it.dataPathArr[$dataNxt] = $i; + }} + + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} + } + + {{# def.ifResultValid }} + {{?}} + {{~}} + + {{? typeof $additionalItems == 'object' && {{# def.nonEmptySchema:$additionalItems }} }} + {{ + $it.schema = $additionalItems; + $it.schemaPath = it.schemaPath + '.additionalItems'; + $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; + }} + {{=$nextValid}} = true; + + if ({{=$data}}.length > {{= $schema.length }}) { + {{# def.validateItems: $schema.length }} + } + + {{# def.ifResultValid }} + {{?}} + +{{?? {{# def.nonEmptySchema:$schema }} }} + {{ /* 'items' is a single schema */}} + {{ + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + }} + {{# def.validateItems: 0 }} +{{?}} + +{{? $breakOnError }} + {{= $closingBraces }} + if ({{=$errs}} == errors) { +{{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/missing.def b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/missing.def new file mode 100644 index 0000000000000000000000000000000000000000..a73b9f966e9e84af741b043b5339a3f12e8a0ae9 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/missing.def @@ -0,0 +1,39 @@ +{{## def.checkMissingProperty:_properties: + {{~ _properties:$propertyKey:$i }} + {{?$i}} || {{?}} + {{ + var $prop = it.util.getProperty($propertyKey) + , $useData = $data + $prop; + }} + ( ({{# def.noPropertyInData }}) && (missing{{=$lvl}} = {{= it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) }}) ) + {{~}} +#}} + + +{{## def.errorMissingProperty:_error: + {{ + var $propertyPath = 'missing' + $lvl + , $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers + ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) + : $currentErrorPath + ' + ' + $propertyPath; + } + }} + {{# def.error:_error }} +#}} + + +{{## def.allErrorsMissingProperty:_error: + {{ + var $prop = it.util.getProperty($propertyKey) + , $missingProperty = it.util.escapeQuotes($propertyKey) + , $useData = $data + $prop; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + }} + if ({{# def.noPropertyInData }}) { + {{# def.addError:_error }} + } +#}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/multipleOf.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/multipleOf.jst new file mode 100644 index 0000000000000000000000000000000000000000..6d88a456f3817fd962633e038d24f812427ef2fe --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/multipleOf.jst @@ -0,0 +1,22 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{# def.numberKeyword }} + +var division{{=$lvl}}; +if ({{?$isData}} + {{=$schemaValue}} !== undefined && ( + typeof {{=$schemaValue}} != 'number' || + {{?}} + (division{{=$lvl}} = {{=$data}} / {{=$schemaValue}}, + {{? it.opts.multipleOfPrecision }} + Math.abs(Math.round(division{{=$lvl}}) - division{{=$lvl}}) > 1e-{{=it.opts.multipleOfPrecision}} + {{??}} + division{{=$lvl}} !== parseInt(division{{=$lvl}}) + {{?}} + ) + {{?$isData}} ) {{?}} ) { + {{# def.error:'multipleOf' }} +} {{? $breakOnError }} else { {{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/not.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/not.jst new file mode 100644 index 0000000000000000000000000000000000000000..e03185ae874052dc660b7ce7aaecece466a023b2 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/not.jst @@ -0,0 +1,43 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + +{{? {{# def.nonEmptySchema:$schema }} }} + {{ + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + }} + + var {{=$errs}} = errors; + + {{# def.setCompositeRule }} + + {{ + $it.createErrors = false; + var $allErrorsOption; + if ($it.opts.allErrors) { + $allErrorsOption = $it.opts.allErrors; + $it.opts.allErrors = false; + } + }} + {{= it.validate($it) }} + {{ + $it.createErrors = true; + if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; + }} + + {{# def.resetCompositeRule }} + + if ({{=$nextValid}}) { + {{# def.error:'not' }} + } else { + {{# def.resetErrors }} + {{? it.opts.allErrors }} } {{?}} +{{??}} + {{# def.addError:'not' }} + {{? $breakOnError}} + if (false) { + {{?}} +{{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/oneOf.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/oneOf.jst new file mode 100644 index 0000000000000000000000000000000000000000..bcce2c6ed5afe7a45642cfc43c790d1b516f515e --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/oneOf.jst @@ -0,0 +1,54 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + +{{ + var $currentBaseId = $it.baseId + , $prevValid = 'prevValid' + $lvl + , $passingSchemas = 'passingSchemas' + $lvl; +}} + +var {{=$errs}} = errors + , {{=$prevValid}} = false + , {{=$valid}} = false + , {{=$passingSchemas}} = null; + +{{# def.setCompositeRule }} + +{{~ $schema:$sch:$i }} + {{? {{# def.nonEmptySchema:$sch }} }} + {{ + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + }} + + {{# def.insertSubschemaCode }} + {{??}} + var {{=$nextValid}} = true; + {{?}} + + {{? $i }} + if ({{=$nextValid}} && {{=$prevValid}}) { + {{=$valid}} = false; + {{=$passingSchemas}} = [{{=$passingSchemas}}, {{=$i}}]; + } else { + {{ $closingBraces += '}'; }} + {{?}} + + if ({{=$nextValid}}) { + {{=$valid}} = {{=$prevValid}} = true; + {{=$passingSchemas}} = {{=$i}}; + } +{{~}} + +{{# def.resetCompositeRule }} + +{{= $closingBraces }} + +if (!{{=$valid}}) { + {{# def.extraError:'oneOf' }} +} else { + {{# def.resetErrors }} +{{? it.opts.allErrors }} } {{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/pattern.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/pattern.jst new file mode 100644 index 0000000000000000000000000000000000000000..8f7f9993881678c6caaa9b082c1d8bc0d240380c --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/pattern.jst @@ -0,0 +1,25 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{ + var $regExpCode = it.opts.regExp ? 'regExp' : 'new RegExp'; +}} + +{{? $isData }} + var {{=$valid}} = true; + try { + {{=$valid}} = {{=$regExpCode}}({{=$schemaValue}}).test({{=$data}}); + } catch(e) { + {{=$valid}} = false; + } + if ({{# def.$dataNotType:'string' }} !{{=$valid}}) { +{{??}} + {{ + var $regexp = it.usePattern($schema); + }} + if ({{# def.$dataNotType:'string' }} !{{=$regexp}}.test({{=$data}}) ) { +{{?}} + {{# def.error:'pattern' }} +} {{? $breakOnError }} else { {{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/properties.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/properties.jst new file mode 100644 index 0000000000000000000000000000000000000000..5cebb9b12e948e9d0ff000dcc5cd8a4aeb71d4a7 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/properties.jst @@ -0,0 +1,245 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + + +{{## def.validateAdditional: + {{ /* additionalProperties is schema */ + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty + ? it.errorPath + : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + }} + + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} +#}} + + +{{ + var $key = 'key' + $lvl + , $idx = 'idx' + $lvl + , $dataNxt = $it.dataLevel = it.dataLevel + 1 + , $nextData = 'data' + $dataNxt + , $dataProperties = 'dataProperties' + $lvl; + + var $schemaKeys = Object.keys($schema || {}).filter(notProto) + , $pProperties = it.schema.patternProperties || {} + , $pPropertyKeys = Object.keys($pProperties).filter(notProto) + , $aProperties = it.schema.additionalProperties + , $someProperties = $schemaKeys.length || $pPropertyKeys.length + , $noAdditional = $aProperties === false + , $additionalIsSchema = typeof $aProperties == 'object' + && Object.keys($aProperties).length + , $removeAdditional = it.opts.removeAdditional + , $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional + , $ownProperties = it.opts.ownProperties + , $currentBaseId = it.baseId; + + var $required = it.schema.required; + if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) { + var $requiredHash = it.util.toHash($required); + } + + function notProto(p) { return p !== '__proto__'; } +}} + + +var {{=$errs}} = errors; +var {{=$nextValid}} = true; +{{? $ownProperties }} + var {{=$dataProperties}} = undefined; +{{?}} + +{{? $checkAdditional }} + {{# def.iterateProperties }} + {{? $someProperties }} + var isAdditional{{=$lvl}} = !(false + {{? $schemaKeys.length }} + {{? $schemaKeys.length > 8 }} + || validate.schema{{=$schemaPath}}.hasOwnProperty({{=$key}}) + {{??}} + {{~ $schemaKeys:$propertyKey }} + || {{=$key}} == {{= it.util.toQuotedString($propertyKey) }} + {{~}} + {{?}} + {{?}} + {{? $pPropertyKeys.length }} + {{~ $pPropertyKeys:$pProperty:$i }} + || {{= it.usePattern($pProperty) }}.test({{=$key}}) + {{~}} + {{?}} + ); + + if (isAdditional{{=$lvl}}) { + {{?}} + {{? $removeAdditional == 'all' }} + delete {{=$data}}[{{=$key}}]; + {{??}} + {{ + var $currentErrorPath = it.errorPath; + var $additionalProperty = '\' + ' + $key + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + } + }} + {{? $noAdditional }} + {{? $removeAdditional }} + delete {{=$data}}[{{=$key}}]; + {{??}} + {{=$nextValid}} = false; + {{ + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalProperties'; + }} + {{# def.error:'additionalProperties' }} + {{ $errSchemaPath = $currErrSchemaPath; }} + {{? $breakOnError }} break; {{?}} + {{?}} + {{?? $additionalIsSchema }} + {{? $removeAdditional == 'failing' }} + var {{=$errs}} = errors; + {{# def.setCompositeRule }} + + {{# def.validateAdditional }} + + if (!{{=$nextValid}}) { + errors = {{=$errs}}; + if (validate.errors !== null) { + if (errors) validate.errors.length = errors; + else validate.errors = null; + } + delete {{=$data}}[{{=$key}}]; + } + + {{# def.resetCompositeRule }} + {{??}} + {{# def.validateAdditional }} + {{? $breakOnError }} if (!{{=$nextValid}}) break; {{?}} + {{?}} + {{?}} + {{ it.errorPath = $currentErrorPath; }} + {{?}} + {{? $someProperties }} + } + {{?}} + } + + {{# def.ifResultValid }} +{{?}} + +{{ var $useDefaults = it.opts.useDefaults && !it.compositeRule; }} + +{{? $schemaKeys.length }} + {{~ $schemaKeys:$propertyKey }} + {{ var $sch = $schema[$propertyKey]; }} + + {{? {{# def.nonEmptySchema:$sch}} }} + {{ + var $prop = it.util.getProperty($propertyKey) + , $passData = $data + $prop + , $hasDefault = $useDefaults && $sch.default !== undefined; + $it.schema = $sch; + $it.schemaPath = $schemaPath + $prop; + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); + $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); + $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); + }} + + {{# def.generateSubschemaCode }} + + {{? {{# def.willOptimize }} }} + {{ + $code = {{# def._optimizeValidate }}; + var $useData = $passData; + }} + {{??}} + {{ var $useData = $nextData; }} + var {{=$nextData}} = {{=$passData}}; + {{?}} + + {{? $hasDefault }} + {{= $code }} + {{??}} + {{? $requiredHash && $requiredHash[$propertyKey] }} + if ({{# def.noPropertyInData }}) { + {{=$nextValid}} = false; + {{ + var $currentErrorPath = it.errorPath + , $currErrSchemaPath = $errSchemaPath + , $missingProperty = it.util.escapeQuotes($propertyKey); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + $errSchemaPath = it.errSchemaPath + '/required'; + }} + {{# def.error:'required' }} + {{ $errSchemaPath = $currErrSchemaPath; }} + {{ it.errorPath = $currentErrorPath; }} + } else { + {{??}} + {{? $breakOnError }} + if ({{# def.noPropertyInData }}) { + {{=$nextValid}} = true; + } else { + {{??}} + if ({{=$useData}} !== undefined + {{? $ownProperties }} + && {{# def.isOwnProperty }} + {{?}} + ) { + {{?}} + {{?}} + + {{= $code }} + } + {{?}} {{ /* $hasDefault */ }} + {{?}} {{ /* def.nonEmptySchema */ }} + + {{# def.ifResultValid }} + {{~}} +{{?}} + +{{? $pPropertyKeys.length }} + {{~ $pPropertyKeys:$pProperty }} + {{ var $sch = $pProperties[$pProperty]; }} + + {{? {{# def.nonEmptySchema:$sch}} }} + {{ + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); + $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + + it.util.escapeFragment($pProperty); + }} + + {{# def.iterateProperties }} + if ({{= it.usePattern($pProperty) }}.test({{=$key}})) { + {{ + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + }} + + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} + + {{? $breakOnError }} if (!{{=$nextValid}}) break; {{?}} + } + {{? $breakOnError }} else {{=$nextValid}} = true; {{?}} + } + + {{# def.ifResultValid }} + {{?}} {{ /* def.nonEmptySchema */ }} + {{~}} +{{?}} + + +{{? $breakOnError }} + {{= $closingBraces }} + if ({{=$errs}} == errors) { +{{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/propertyNames.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/propertyNames.jst new file mode 100644 index 0000000000000000000000000000000000000000..d456ccafc4b5875363ccf42af41fb51edaf0a0a9 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/propertyNames.jst @@ -0,0 +1,52 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + +var {{=$errs}} = errors; + +{{? {{# def.nonEmptySchema:$schema }} }} + {{ + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + }} + + {{ + var $key = 'key' + $lvl + , $idx = 'idx' + $lvl + , $i = 'i' + $lvl + , $invalidName = '\' + ' + $key + ' + \'' + , $dataNxt = $it.dataLevel = it.dataLevel + 1 + , $nextData = 'data' + $dataNxt + , $dataProperties = 'dataProperties' + $lvl + , $ownProperties = it.opts.ownProperties + , $currentBaseId = it.baseId; + }} + + {{? $ownProperties }} + var {{=$dataProperties}} = undefined; + {{?}} + {{# def.iterateProperties }} + var startErrs{{=$lvl}} = errors; + + {{ var $passData = $key; }} + {{# def.setCompositeRule }} + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} + {{# def.resetCompositeRule }} + + if (!{{=$nextValid}}) { + for (var {{=$i}}=startErrs{{=$lvl}}; {{=$i}}= it.opts.loopRequired + , $ownProperties = it.opts.ownProperties; + }} + + {{? $breakOnError }} + var missing{{=$lvl}}; + {{? $loopRequired }} + {{# def.setupLoop }} + var {{=$valid}} = true; + + {{?$isData}}{{# def.check$dataIsArray }}{{?}} + + for (var {{=$i}} = 0; {{=$i}} < {{=$vSchema}}.length; {{=$i}}++) { + {{=$valid}} = {{=$data}}[{{=$vSchema}}[{{=$i}}]] !== undefined + {{? $ownProperties }} + && {{# def.isRequiredOwnProperty }} + {{?}}; + if (!{{=$valid}}) break; + } + + {{? $isData }} } {{?}} + + {{# def.checkError:'required' }} + else { + {{??}} + if ({{# def.checkMissingProperty:$required }}) { + {{# def.errorMissingProperty:'required' }} + } else { + {{?}} + {{??}} + {{? $loopRequired }} + {{# def.setupLoop }} + {{? $isData }} + if ({{=$vSchema}} && !Array.isArray({{=$vSchema}})) { + {{# def.addError:'required' }} + } else if ({{=$vSchema}} !== undefined) { + {{?}} + + for (var {{=$i}} = 0; {{=$i}} < {{=$vSchema}}.length; {{=$i}}++) { + if ({{=$data}}[{{=$vSchema}}[{{=$i}}]] === undefined + {{? $ownProperties }} + || !{{# def.isRequiredOwnProperty }} + {{?}}) { + {{# def.addError:'required' }} + } + } + + {{? $isData }} } {{?}} + {{??}} + {{~ $required:$propertyKey }} + {{# def.allErrorsMissingProperty:'required' }} + {{~}} + {{?}} + {{?}} + + {{ it.errorPath = $currentErrorPath; }} + +{{?? $breakOnError }} + if (true) { +{{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/uniqueItems.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/uniqueItems.jst new file mode 100644 index 0000000000000000000000000000000000000000..e69b8308d2c47d0a1ca5bd59c89cd99dce90c6fc --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/uniqueItems.jst @@ -0,0 +1,62 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + + +{{? ($schema || $isData) && it.opts.uniqueItems !== false }} + {{? $isData }} + var {{=$valid}}; + if ({{=$schemaValue}} === false || {{=$schemaValue}} === undefined) + {{=$valid}} = true; + else if (typeof {{=$schemaValue}} != 'boolean') + {{=$valid}} = false; + else { + {{?}} + + var i = {{=$data}}.length + , {{=$valid}} = true + , j; + if (i > 1) { + {{ + var $itemType = it.schema.items && it.schema.items.type + , $typeIsArray = Array.isArray($itemType); + }} + {{? !$itemType || $itemType == 'object' || $itemType == 'array' || + ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0)) }} + outer: + for (;i--;) { + for (j = i; j--;) { + if (equal({{=$data}}[i], {{=$data}}[j])) { + {{=$valid}} = false; + break outer; + } + } + } + {{??}} + var itemIndices = {}, item; + for (;i--;) { + var item = {{=$data}}[i]; + {{ var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); }} + if ({{= it.util[$method]($itemType, 'item', it.opts.strictNumbers, true) }}) continue; + {{? $typeIsArray}} + if (typeof item == 'string') item = '"' + item; + {{?}} + if (typeof itemIndices[item] == 'number') { + {{=$valid}} = false; + j = itemIndices[item]; + break; + } + itemIndices[item] = i; + } + {{?}} + } + + {{? $isData }} } {{?}} + + if (!{{=$valid}}) { + {{# def.error:'uniqueItems' }} + } {{? $breakOnError }} else { {{?}} +{{??}} + {{? $breakOnError }} if (true) { {{?}} +{{?}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/validate.jst b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/validate.jst new file mode 100644 index 0000000000000000000000000000000000000000..32087e71c0d53e789dac40d040f7b5c1f4c64363 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dot/validate.jst @@ -0,0 +1,276 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.defaults }} +{{# def.coerce }} + +{{ /** + * schema compilation (render) time: + * it = { schema, RULES, _validate, opts } + * it.validate - this template function, + * it is used recursively to generate code for subschemas + * + * runtime: + * "validate" is a variable name to which this function will be assigned + * validateRef etc. are defined in the parent scope in index.js + */ }} + +{{ + var $async = it.schema.$async === true + , $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref') + , $id = it.self._getId(it.schema); +}} + +{{ + if (it.opts.strictKeywords) { + var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords); + if ($unknownKwd) { + var $keywordsMsg = 'unknown keyword: ' + $unknownKwd; + if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg); + else throw new Error($keywordsMsg); + } + } +}} + +{{? it.isTop }} + var validate = {{?$async}}{{it.async = true;}}async {{?}}function(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + {{? $id && (it.opts.sourceCode || it.opts.processCode) }} + {{= '/\*# sourceURL=' + $id + ' */' }} + {{?}} +{{?}} + +{{? typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref) }} + {{ var $keyword = 'false schema'; }} + {{# def.setupKeyword }} + {{? it.schema === false}} + {{? it.isTop}} + {{ $breakOnError = true; }} + {{??}} + var {{=$valid}} = false; + {{?}} + {{# def.error:'false schema' }} + {{??}} + {{? it.isTop}} + {{? $async }} + return data; + {{??}} + validate.errors = null; + return true; + {{?}} + {{??}} + var {{=$valid}} = true; + {{?}} + {{?}} + + {{? it.isTop}} + }; + return validate; + {{?}} + + {{ return out; }} +{{?}} + + +{{? it.isTop }} + {{ + var $top = it.isTop + , $lvl = it.level = 0 + , $dataLvl = it.dataLevel = 0 + , $data = 'data'; + it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); + it.baseId = it.baseId || it.rootId; + delete it.isTop; + + it.dataPathArr = [""]; + + if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored in the schema root'; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + }} + + var vErrors = null; {{ /* don't edit, used in replace */ }} + var errors = 0; {{ /* don't edit, used in replace */ }} + if (rootData === undefined) rootData = data; {{ /* don't edit, used in replace */ }} +{{??}} + {{ + var $lvl = it.level + , $dataLvl = it.dataLevel + , $data = 'data' + ($dataLvl || ''); + + if ($id) it.baseId = it.resolve.url(it.baseId, $id); + + if ($async && !it.async) throw new Error('async schema in sync schema'); + }} + + var errs_{{=$lvl}} = errors; +{{?}} + +{{ + var $valid = 'valid' + $lvl + , $breakOnError = !it.opts.allErrors + , $closingBraces1 = '' + , $closingBraces2 = ''; + + var $errorKeyword; + var $typeSchema = it.schema.type + , $typeIsArray = Array.isArray($typeSchema); + + if ($typeSchema && it.opts.nullable && it.schema.nullable === true) { + if ($typeIsArray) { + if ($typeSchema.indexOf('null') == -1) + $typeSchema = $typeSchema.concat('null'); + } else if ($typeSchema != 'null') { + $typeSchema = [$typeSchema, 'null']; + $typeIsArray = true; + } + } + + if ($typeIsArray && $typeSchema.length == 1) { + $typeSchema = $typeSchema[0]; + $typeIsArray = false; + } +}} + +{{## def.checkType: + {{ + var $schemaPath = it.schemaPath + '.type' + , $errSchemaPath = it.errSchemaPath + '/type' + , $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; + }} + + if ({{= it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true) }}) { +#}} + +{{? it.schema.$ref && $refKeywords }} + {{? it.opts.extendRefs == 'fail' }} + {{ throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); }} + {{?? it.opts.extendRefs !== true }} + {{ + $refKeywords = false; + it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); + }} + {{?}} +{{?}} + +{{? it.schema.$comment && it.opts.$comment }} + {{= it.RULES.all.$comment.code(it, '$comment') }} +{{?}} + +{{? $typeSchema }} + {{? it.opts.coerceTypes }} + {{ var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); }} + {{?}} + + {{ var $rulesGroup = it.RULES.types[$typeSchema]; }} + {{? $coerceToTypes || $typeIsArray || $rulesGroup === true || + ($rulesGroup && !$shouldUseGroup($rulesGroup)) }} + {{ + var $schemaPath = it.schemaPath + '.type' + , $errSchemaPath = it.errSchemaPath + '/type'; + }} + {{# def.checkType }} + {{? $coerceToTypes }} + {{# def.coerceType }} + {{??}} + {{# def.error:'type' }} + {{?}} + } + {{?}} +{{?}} + + +{{? it.schema.$ref && !$refKeywords }} + {{= it.RULES.all.$ref.code(it, '$ref') }} + {{? $breakOnError }} + } + if (errors === {{?$top}}0{{??}}errs_{{=$lvl}}{{?}}) { + {{ $closingBraces2 += '}'; }} + {{?}} +{{??}} + {{~ it.RULES:$rulesGroup }} + {{? $shouldUseGroup($rulesGroup) }} + {{? $rulesGroup.type }} + if ({{= it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers) }}) { + {{?}} + {{? it.opts.useDefaults }} + {{? $rulesGroup.type == 'object' && it.schema.properties }} + {{# def.defaultProperties }} + {{?? $rulesGroup.type == 'array' && Array.isArray(it.schema.items) }} + {{# def.defaultItems }} + {{?}} + {{?}} + {{~ $rulesGroup.rules:$rule }} + {{? $shouldUseRule($rule) }} + {{ var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); }} + {{? $code }} + {{= $code }} + {{? $breakOnError }} + {{ $closingBraces1 += '}'; }} + {{?}} + {{?}} + {{?}} + {{~}} + {{? $breakOnError }} + {{= $closingBraces1 }} + {{ $closingBraces1 = ''; }} + {{?}} + {{? $rulesGroup.type }} + } + {{? $typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes }} + else { + {{ + var $schemaPath = it.schemaPath + '.type' + , $errSchemaPath = it.errSchemaPath + '/type'; + }} + {{# def.error:'type' }} + } + {{?}} + {{?}} + + {{? $breakOnError }} + if (errors === {{?$top}}0{{??}}errs_{{=$lvl}}{{?}}) { + {{ $closingBraces2 += '}'; }} + {{?}} + {{?}} + {{~}} +{{?}} + +{{? $breakOnError }} {{= $closingBraces2 }} {{?}} + +{{? $top }} + {{? $async }} + if (errors === 0) return data; {{ /* don't edit, used in replace */ }} + else throw new ValidationError(vErrors); {{ /* don't edit, used in replace */ }} + {{??}} + validate.errors = vErrors; {{ /* don't edit, used in replace */ }} + return errors === 0; {{ /* don't edit, used in replace */ }} + {{?}} + }; + + return validate; +{{??}} + var {{=$valid}} = errors === errs_{{=$lvl}}; +{{?}} + +{{ + function $shouldUseGroup($rulesGroup) { + var rules = $rulesGroup.rules; + for (var i=0; i < rules.length; i++) + if ($shouldUseRule(rules[i])) + return true; + } + + function $shouldUseRule($rule) { + return it.schema[$rule.keyword] !== undefined || + ($rule.implements && $ruleImplementsSomeKeyword($rule)); + } + + function $ruleImplementsSomeKeyword($rule) { + var impl = $rule.implements; + for (var i=0; i < impl.length; i++) + if (it.schema[impl[i]] !== undefined) + return true; + } +}} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/README.md b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4d994846c81f6303d08f97bba685d9c734527c52 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/README.md @@ -0,0 +1,3 @@ +These files are compiled dot templates from dot folder. + +Do NOT edit them directly, edit the templates and run `npm run build` from main ajv folder. diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/_limit.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/_limit.js new file mode 100644 index 0000000000000000000000000000000000000000..05a1979dcb8e922a048a95120bf8a29f093a267a --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/_limit.js @@ -0,0 +1,163 @@ +'use strict'; +module.exports = function generate__limit(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $isMax = $keyword == 'maximum', + $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum', + $schemaExcl = it.schema[$exclusiveKeyword], + $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, + $op = $isMax ? '<' : '>', + $notOp = $isMax ? '>' : '<', + $errorKeyword = undefined; + if (!($isData || typeof $schema == 'number' || $schema === undefined)) { + throw new Error($keyword + ' must be number'); + } + if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) { + throw new Error($exclusiveKeyword + ' must be number or boolean'); + } + if ($isDataExcl) { + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), + $exclusive = 'exclusive' + $lvl, + $exclType = 'exclType' + $lvl, + $exclIsNumber = 'exclIsNumber' + $lvl, + $opExpr = 'op' + $lvl, + $opStr = '\' + ' + $opExpr + ' + \''; + out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; + $schemaValueExcl = 'schemaExcl' + $lvl; + out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { '; + var $errorKeyword = $exclusiveKeyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; '; + if ($schema === undefined) { + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaValueExcl; + $isData = $isDataExcl; + } + } else { + var $exclIsNumber = typeof $schemaExcl == 'number', + $opStr = $op; + if ($exclIsNumber && $isData) { + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { '; + } else { + if ($exclIsNumber && $schema === undefined) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaExcl; + $notOp += '='; + } else { + if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); + if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $notOp += '='; + } else { + $exclusive = false; + $opStr += '='; + } + } + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { '; + } + } + $errorKeyword = $errorKeyword || $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be ' + ($opStr) + ' '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schemaValue) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/_limitItems.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/_limitItems.js new file mode 100644 index 0000000000000000000000000000000000000000..e092a559ea0ae07ac8042d1e8935e80f5a6d08a5 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/_limitItems.js @@ -0,0 +1,80 @@ +'use strict'; +module.exports = function generate__limitItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxItems' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxItems') { + out += 'more'; + } else { + out += 'fewer'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/_limitLength.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/_limitLength.js new file mode 100644 index 0000000000000000000000000000000000000000..ecbd3fe1906f346724d23c338b9fa17e02a92357 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/_limitLength.js @@ -0,0 +1,85 @@ +'use strict'; +module.exports = function generate__limitLength(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxLength' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + if (it.opts.unicode === false) { + out += ' ' + ($data) + '.length '; + } else { + out += ' ucs2length(' + ($data) + ') '; + } + out += ' ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be '; + if ($keyword == 'maxLength') { + out += 'longer'; + } else { + out += 'shorter'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' characters\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/_limitProperties.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/_limitProperties.js new file mode 100644 index 0000000000000000000000000000000000000000..d232755ad0b21ef7d4bc4dd4bffe38c6664fc1a9 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/_limitProperties.js @@ -0,0 +1,80 @@ +'use strict'; +module.exports = function generate__limitProperties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxProperties' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxProperties') { + out += 'more'; + } else { + out += 'fewer'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' properties\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/allOf.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/allOf.js new file mode 100644 index 0000000000000000000000000000000000000000..fb8c2e4bbefe95fbf3e0004ecbfdfa7f6f0902f8 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/allOf.js @@ -0,0 +1,42 @@ +'use strict'; +module.exports = function generate_allOf(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $allSchemasEmpty = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $allSchemasEmpty = false; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if ($breakOnError) { + if ($allSchemasEmpty) { + out += ' if (true) { '; + } else { + out += ' ' + ($closingBraces.slice(0, -1)) + ' '; + } + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/anyOf.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/anyOf.js new file mode 100644 index 0000000000000000000000000000000000000000..0600a9d42bce5b07e496f64bc54a4a983211dd2c --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/anyOf.js @@ -0,0 +1,73 @@ +'use strict'; +module.exports = function generate_anyOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $noEmptySchema = $schema.every(function($sch) { + return (it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)); + }); + if ($noEmptySchema) { + var $currentBaseId = $it.baseId; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { '; + $closingBraces += '}'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should match some schema in anyOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/comment.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/comment.js new file mode 100644 index 0000000000000000000000000000000000000000..dd66bb8f0f951a4a22482e15e1c33585f934d558 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/comment.js @@ -0,0 +1,14 @@ +'use strict'; +module.exports = function generate_comment(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $comment = it.util.toQuotedString($schema); + if (it.opts.$comment === true) { + out += ' console.log(' + ($comment) + ');'; + } else if (typeof it.opts.$comment == 'function') { + out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);'; + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/const.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/const.js new file mode 100644 index 0000000000000000000000000000000000000000..15b7c619fff050cd69ae61581a873e4806821f57 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/const.js @@ -0,0 +1,56 @@ +'use strict'; +module.exports = function generate_const(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!$isData) { + out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to constant\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/contains.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/contains.js new file mode 100644 index 0000000000000000000000000000000000000000..7d763009073aa324d9147c26e102055aa607a287 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/contains.js @@ -0,0 +1,81 @@ +'use strict'; +module.exports = function generate_contains(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId, + $nonEmptySchema = (it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all)); + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($nonEmptySchema) { + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (' + ($nextValid) + ') break; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {'; + } else { + out += ' if (' + ($data) + '.length == 0) {'; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should contain a valid item\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + if ($nonEmptySchema) { + out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + } + if (it.opts.allErrors) { + out += ' } '; + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/custom.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/custom.js new file mode 100644 index 0000000000000000000000000000000000000000..f3e641e701709c9defa346efe3d25438a53de97e --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/custom.js @@ -0,0 +1,228 @@ +'use strict'; +module.exports = function generate_custom(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $rule = this, + $definition = 'definition' + $lvl, + $rDef = $rule.definition, + $closingBraces = ''; + var $compile, $inline, $macro, $ruleValidate, $validateCode; + if ($isData && $rDef.$data) { + $validateCode = 'keywordValidate' + $lvl; + var $validateSchema = $rDef.validateSchema; + out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;'; + } else { + $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); + if (!$ruleValidate) return; + $schemaValue = 'validate.schema' + $schemaPath; + $validateCode = $ruleValidate.code; + $compile = $rDef.compile; + $inline = $rDef.inline; + $macro = $rDef.macro; + } + var $ruleErrs = $validateCode + '.errors', + $i = 'i' + $lvl, + $ruleErr = 'ruleErr' + $lvl, + $asyncKeyword = $rDef.async; + if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); + if (!($inline || $macro)) { + out += '' + ($ruleErrs) + ' = null;'; + } + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($isData && $rDef.$data) { + $closingBraces += '}'; + out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { '; + if ($validateSchema) { + $closingBraces += '}'; + out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { '; + } + } + if ($inline) { + if ($rDef.statements) { + out += ' ' + ($ruleValidate.validate) + ' '; + } else { + out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; '; + } + } else if ($macro) { + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $ruleValidate.validate; + $it.schemaPath = ''; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($code); + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + out += ' ' + ($validateCode) + '.call( '; + if (it.opts.passContext) { + out += 'this'; + } else { + out += 'self'; + } + if ($compile || $rDef.schema === false) { + out += ' , ' + ($data) + ' '; + } else { + out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' '; + } + out += ' , (dataPath || \'\')'; + if (it.errorPath != '""') { + out += ' + ' + (it.errorPath); + } + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) '; + var def_callRuleValidate = out; + out = $$outStack.pop(); + if ($rDef.errors === false) { + out += ' ' + ($valid) + ' = '; + if ($asyncKeyword) { + out += 'await '; + } + out += '' + (def_callRuleValidate) + '; '; + } else { + if ($asyncKeyword) { + $ruleErrs = 'customErrors' + $lvl; + out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } '; + } else { + out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; '; + } + } + } + if ($rDef.modifying) { + out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; + } + out += '' + ($closingBraces); + if ($rDef.valid) { + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + out += ' if ( '; + if ($rDef.valid === undefined) { + out += ' !'; + if ($macro) { + out += '' + ($nextValid); + } else { + out += '' + ($valid); + } + } else { + out += ' ' + (!$rDef.valid) + ' '; + } + out += ') { '; + $errorKeyword = $rule.keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + var def_customError = out; + out = $$outStack.pop(); + if ($inline) { + if ($rDef.errors) { + if ($rDef.errors != 'full') { + out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + ' 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; + } + out += ') { '; + $it.schema = $sch; + $it.schemaPath = $schemaPath + it.util.getProperty($property); + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property); + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/enum.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/enum.js new file mode 100644 index 0000000000000000000000000000000000000000..90580b9ff7940f11b2c15372dab46a2968a262bc --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/enum.js @@ -0,0 +1,66 @@ +'use strict'; +module.exports = function generate_enum(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $i = 'i' + $lvl, + $vSchema = 'schema' + $lvl; + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ';'; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }'; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to one of the allowed values\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/format.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/format.js new file mode 100644 index 0000000000000000000000000000000000000000..cd9a5693e70e90a4ca369a33cc15688f5081ba1a --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/format.js @@ -0,0 +1,150 @@ +'use strict'; +module.exports = function generate_format(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + if (it.opts.format === false) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $unknownFormats = it.opts.unknownFormats, + $allowUnknown = Array.isArray($unknownFormats); + if ($isData) { + var $format = 'format' + $lvl, + $isObject = 'isObject' + $lvl, + $formatType = 'formatType' + $lvl; + out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { '; + if (it.async) { + out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; '; + } + out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' ('; + if ($unknownFormats != 'ignore') { + out += ' (' + ($schemaValue) + ' && !' + ($format) + ' '; + if ($allowUnknown) { + out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 '; + } + out += ') || '; + } + out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? '; + if (it.async) { + out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) '; + } else { + out += ' ' + ($format) + '(' + ($data) + ') '; + } + out += ' : ' + ($format) + '.test(' + ($data) + '))))) {'; + } else { + var $format = it.formats[$schema]; + if (!$format) { + if ($unknownFormats == 'ignore') { + it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } else { + throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); + } + } + var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate; + var $formatType = $isObject && $format.type || 'string'; + if ($isObject) { + var $async = $format.async === true; + $format = $format.validate; + } + if ($formatType != $ruleType) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + if ($async) { + if (!it.async) throw new Error('async format in sync schema'); + var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; + out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { '; + } else { + out += ' if (! '; + var $formatRef = 'formats' + it.util.getProperty($schema); + if ($isObject) $formatRef += '.validate'; + if (typeof $format == 'function') { + out += ' ' + ($formatRef) + '(' + ($data) + ') '; + } else { + out += ' ' + ($formatRef) + '.test(' + ($data) + ') '; + } + out += ') { '; + } + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match format "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/if.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/if.js new file mode 100644 index 0000000000000000000000000000000000000000..94d27ad853836ddbcceafc56d244af16f00fb367 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/if.js @@ -0,0 +1,103 @@ +'use strict'; +module.exports = function generate_if(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + var $thenSch = it.schema['then'], + $elseSch = it.schema['else'], + $thenPresent = $thenSch !== undefined && (it.opts.strictKeywords ? (typeof $thenSch == 'object' && Object.keys($thenSch).length > 0) || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)), + $elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? (typeof $elseSch == 'object' && Object.keys($elseSch).length > 0) || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)), + $currentBaseId = $it.baseId; + if ($thenPresent || $elsePresent) { + var $ifClause; + $it.createErrors = false; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + $it.createErrors = true; + out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + if ($thenPresent) { + out += ' if (' + ($nextValid) + ') { '; + $it.schema = it.schema['then']; + $it.schemaPath = it.schemaPath + '.then'; + $it.errSchemaPath = it.errSchemaPath + '/then'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + ($ifClause) + ' = \'then\'; '; + } else { + $ifClause = '\'then\''; + } + out += ' } '; + if ($elsePresent) { + out += ' else { '; + } + } else { + out += ' if (!' + ($nextValid) + ') { '; + } + if ($elsePresent) { + $it.schema = it.schema['else']; + $it.schemaPath = it.schemaPath + '.else'; + $it.errSchemaPath = it.errSchemaPath + '/else'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + ($ifClause) + ' = \'else\'; '; + } else { + $ifClause = '\'else\''; + } + out += ' } '; + } + out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/index.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2fb1b00ef69f67070e7f86c89cd371dcd9f7bd59 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/index.js @@ -0,0 +1,33 @@ +'use strict'; + +//all requires must be explicit because browserify won't work with dynamic requires +module.exports = { + '$ref': require('./ref'), + allOf: require('./allOf'), + anyOf: require('./anyOf'), + '$comment': require('./comment'), + const: require('./const'), + contains: require('./contains'), + dependencies: require('./dependencies'), + 'enum': require('./enum'), + format: require('./format'), + 'if': require('./if'), + items: require('./items'), + maximum: require('./_limit'), + minimum: require('./_limit'), + maxItems: require('./_limitItems'), + minItems: require('./_limitItems'), + maxLength: require('./_limitLength'), + minLength: require('./_limitLength'), + maxProperties: require('./_limitProperties'), + minProperties: require('./_limitProperties'), + multipleOf: require('./multipleOf'), + not: require('./not'), + oneOf: require('./oneOf'), + pattern: require('./pattern'), + properties: require('./properties'), + propertyNames: require('./propertyNames'), + required: require('./required'), + uniqueItems: require('./uniqueItems'), + validate: require('./validate') +}; diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/items.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/items.js new file mode 100644 index 0000000000000000000000000000000000000000..bee5d67da246f354c106e70ad5b1979ef901554c --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/items.js @@ -0,0 +1,140 @@ +'use strict'; +module.exports = function generate_items(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId; + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if (Array.isArray($schema)) { + var $additionalItems = it.schema.additionalItems; + if ($additionalItems === false) { + out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { '; + var $passData = $data + '[' + $i + ']'; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); + $it.dataPathArr[$dataNxt] = $i; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? (typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0) || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) { + $it.schema = $additionalItems; + $it.schemaPath = it.schemaPath + '.additionalItems'; + $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } else if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' }'; + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/multipleOf.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/multipleOf.js new file mode 100644 index 0000000000000000000000000000000000000000..9d6401b8f723f0189387c201849868d81ce2c536 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/multipleOf.js @@ -0,0 +1,80 @@ +'use strict'; +module.exports = function generate_multipleOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + out += 'var division' + ($lvl) + ';if ('; + if ($isData) { + out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || '; + } + out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', '; + if (it.opts.multipleOfPrecision) { + out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' '; + } else { + out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') '; + } + out += ' ) '; + if ($isData) { + out += ' ) '; + } + out += ' ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be multiple of '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schemaValue) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/not.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/not.js new file mode 100644 index 0000000000000000000000000000000000000000..f50c93785b7129b8de3c1429d25199f3e32a9b41 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/not.js @@ -0,0 +1,84 @@ +'use strict'; +module.exports = function generate_not(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.createErrors = false; + var $allErrorsOption; + if ($it.opts.allErrors) { + $allErrorsOption = $it.opts.allErrors; + $it.opts.allErrors = false; + } + out += ' ' + (it.validate($it)) + ' '; + $it.createErrors = true; + if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (' + ($nextValid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + out += ' var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if ($breakOnError) { + out += ' if (false) { '; + } + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/oneOf.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/oneOf.js new file mode 100644 index 0000000000000000000000000000000000000000..dfe2fd550ef2894b2ae273c9602216a4302e2d54 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/oneOf.js @@ -0,0 +1,73 @@ +'use strict'; +module.exports = function generate_oneOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $prevValid = 'prevValid' + $lvl, + $passingSchemas = 'passingSchemas' + $lvl; + out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } else { + out += ' var ' + ($nextValid) + ' = true; '; + } + if ($i) { + out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { '; + $closingBraces += '}'; + } + out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match exactly one schema in oneOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }'; + if (it.opts.allErrors) { + out += ' } '; + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/pattern.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/pattern.js new file mode 100644 index 0000000000000000000000000000000000000000..7efafef3132e1b953be2703bd9bbaa932f0e5314 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/pattern.js @@ -0,0 +1,85 @@ +'use strict'; +module.exports = function generate_pattern(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $regExpCode = it.opts.regExp ? 'regExp' : 'new RegExp'; + if ($isData) { + out += ' var ' + ($valid) + ' = true; try { ' + ($valid) + ' = ' + ($regExpCode) + '(' + ($schemaValue) + ').test(' + ($data) + '); } catch(e) { ' + ($valid) + ' = false; } if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' !' + ($valid) + ') {'; + } else { + var $regexp = it.usePattern($schema); + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' !' + ($regexp) + '.test(' + ($data) + ') ) {'; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match pattern "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/properties.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/properties.js new file mode 100644 index 0000000000000000000000000000000000000000..bc5ee55478090bd9dad1b7bb4653195f6aed5c7e --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/properties.js @@ -0,0 +1,335 @@ +'use strict'; +module.exports = function generate_properties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl; + var $schemaKeys = Object.keys($schema || {}).filter(notProto), + $pProperties = it.schema.patternProperties || {}, + $pPropertyKeys = Object.keys($pProperties).filter(notProto), + $aProperties = it.schema.additionalProperties, + $someProperties = $schemaKeys.length || $pPropertyKeys.length, + $noAdditional = $aProperties === false, + $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length, + $removeAdditional = it.opts.removeAdditional, + $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + var $required = it.schema.required; + if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) { + var $requiredHash = it.util.toHash($required); + } + + function notProto(p) { + return p !== '__proto__'; + } + out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined;'; + } + if ($checkAdditional) { + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + if ($someProperties) { + out += ' var isAdditional' + ($lvl) + ' = !(false '; + if ($schemaKeys.length) { + if ($schemaKeys.length > 8) { + out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') '; + } else { + var arr1 = $schemaKeys; + if (arr1) { + var $propertyKey, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $propertyKey = arr1[i1 += 1]; + out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' '; + } + } + } + } + if ($pPropertyKeys.length) { + var arr2 = $pPropertyKeys; + if (arr2) { + var $pProperty, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $pProperty = arr2[$i += 1]; + out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') '; + } + } + } + out += ' ); if (isAdditional' + ($lvl) + ') { '; + } + if ($removeAdditional == 'all') { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + var $currentErrorPath = it.errorPath; + var $additionalProperty = '\' + ' + $key + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + } + if ($noAdditional) { + if ($removeAdditional) { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + out += ' ' + ($nextValid) + ' = false; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalProperties'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is an invalid additional property'; + } else { + out += 'should NOT have additional properties'; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + out += ' break; '; + } + } + } else if ($additionalIsSchema) { + if ($removeAdditional == 'failing') { + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + } else { + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + } + } + it.errorPath = $currentErrorPath; + } + if ($someProperties) { + out += ' } '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + var $useDefaults = it.opts.useDefaults && !it.compositeRule; + if ($schemaKeys.length) { + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + var $prop = it.util.getProperty($propertyKey), + $passData = $data + $prop, + $hasDefault = $useDefaults && $sch.default !== undefined; + $it.schema = $sch; + $it.schemaPath = $schemaPath + $prop; + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); + $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); + $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + $code = it.util.varReplace($code, $nextData, $passData); + var $useData = $passData; + } else { + var $useData = $nextData; + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; '; + } + if ($hasDefault) { + out += ' ' + ($code) + ' '; + } else { + if ($requiredHash && $requiredHash[$propertyKey]) { + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { ' + ($nextValid) + ' = false; '; + var $currentErrorPath = it.errorPath, + $currErrSchemaPath = $errSchemaPath, + $missingProperty = it.util.escapeQuotes($propertyKey); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + $errSchemaPath = it.errSchemaPath + '/required'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + it.errorPath = $currentErrorPath; + out += ' } else { '; + } else { + if ($breakOnError) { + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { ' + ($nextValid) + ' = true; } else { '; + } else { + out += ' if (' + ($useData) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ' ) { '; + } + } + out += ' ' + ($code) + ' } '; + } + } + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if ($pPropertyKeys.length) { + var arr4 = $pPropertyKeys; + if (arr4) { + var $pProperty, i4 = -1, + l4 = arr4.length - 1; + while (i4 < l4) { + $pProperty = arr4[i4 += 1]; + var $sch = $pProperties[$pProperty]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); + $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty); + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else ' + ($nextValid) + ' = true; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/propertyNames.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/propertyNames.js new file mode 100644 index 0000000000000000000000000000000000000000..2a54a08f45e5495f24a0d3ed60a1ec3f7bf9cfc9 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/propertyNames.js @@ -0,0 +1,81 @@ +'use strict'; +module.exports = function generate_propertyNames(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + out += 'var ' + ($errs) + ' = errors;'; + if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $i = 'i' + $lvl, + $invalidName = '\' + ' + $key + ' + \'', + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined; '; + } + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + out += ' var startErrs' + ($lvl) + ' = errors; '; + var $passData = $key; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + ' 0) || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) { + $required[$required.length] = $property; + } + } + } + } else { + var $required = $schema; + } + } + if ($isData || $required.length) { + var $currentErrorPath = it.errorPath, + $loopRequired = $isData || $required.length >= it.opts.loopRequired, + $ownProperties = it.opts.ownProperties; + if ($breakOnError) { + out += ' var missing' + ($lvl) + '; '; + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + out += ' var ' + ($valid) + ' = true; '; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; + } + out += '; if (!' + ($valid) + ') break; } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } else { + out += ' if ( '; + var arr2 = $required; + if (arr2) { + var $propertyKey, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $propertyKey = arr2[$i += 1]; + if ($i) { + out += ' || '; + } + var $prop = it.util.getProperty($propertyKey), + $useData = $data + $prop; + out += ' ( ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; + } + } + out += ') { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } + } else { + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + if ($isData) { + out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { '; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; + if ($isData) { + out += ' } '; + } + } else { + var arr3 = $required; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $prop = it.util.getProperty($propertyKey), + $missingProperty = it.util.escapeQuotes($propertyKey), + $useData = $data + $prop; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } + } + } + } + it.errorPath = $currentErrorPath; + } else if ($breakOnError) { + out += ' if (true) {'; + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/uniqueItems.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/uniqueItems.js new file mode 100644 index 0000000000000000000000000000000000000000..0736a0ed2333c6d700df13dc3c1d0e3c758d8d5b --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/uniqueItems.js @@ -0,0 +1,86 @@ +'use strict'; +module.exports = function generate_uniqueItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (($schema || $isData) && it.opts.uniqueItems !== false) { + if ($isData) { + out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { '; + } + out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { '; + var $itemType = it.schema.items && it.schema.items.type, + $typeIsArray = Array.isArray($itemType); + if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) { + out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } '; + } else { + out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; '; + var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); + out += ' if (' + (it.util[$method]($itemType, 'item', it.opts.strictNumbers, true)) + ') continue; '; + if ($typeIsArray) { + out += ' if (typeof item == \'string\') item = \'"\' + item; '; + } + out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } '; + } + out += ' } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/validate.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/validate.js new file mode 100644 index 0000000000000000000000000000000000000000..f295824b9325af95bb2ab066eacdf4bb476fdb21 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/dotjs/validate.js @@ -0,0 +1,482 @@ +'use strict'; +module.exports = function generate_validate(it, $keyword, $ruleType) { + var out = ''; + var $async = it.schema.$async === true, + $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'), + $id = it.self._getId(it.schema); + if (it.opts.strictKeywords) { + var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords); + if ($unknownKwd) { + var $keywordsMsg = 'unknown keyword: ' + $unknownKwd; + if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg); + else throw new Error($keywordsMsg); + } + } + if (it.isTop) { + out += ' var validate = '; + if ($async) { + it.async = true; + out += 'async '; + } + out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; '; + if ($id && (it.opts.sourceCode || it.opts.processCode)) { + out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' '; + } + } + if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) { + var $keyword = 'false schema'; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + if (it.schema === false) { + if (it.isTop) { + $breakOnError = true; + } else { + out += ' var ' + ($valid) + ' = false; '; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'boolean schema is false\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } else { + if (it.isTop) { + if ($async) { + out += ' return data; '; + } else { + out += ' validate.errors = null; return true; '; + } + } else { + out += ' var ' + ($valid) + ' = true; '; + } + } + if (it.isTop) { + out += ' }; return validate; '; + } + return out; + } + if (it.isTop) { + var $top = it.isTop, + $lvl = it.level = 0, + $dataLvl = it.dataLevel = 0, + $data = 'data'; + it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); + it.baseId = it.baseId || it.rootId; + delete it.isTop; + it.dataPathArr = [""]; + if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored in the schema root'; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + out += ' var vErrors = null; '; + out += ' var errors = 0; '; + out += ' if (rootData === undefined) rootData = data; '; + } else { + var $lvl = it.level, + $dataLvl = it.dataLevel, + $data = 'data' + ($dataLvl || ''); + if ($id) it.baseId = it.resolve.url(it.baseId, $id); + if ($async && !it.async) throw new Error('async schema in sync schema'); + out += ' var errs_' + ($lvl) + ' = errors;'; + } + var $valid = 'valid' + $lvl, + $breakOnError = !it.opts.allErrors, + $closingBraces1 = '', + $closingBraces2 = ''; + var $errorKeyword; + var $typeSchema = it.schema.type, + $typeIsArray = Array.isArray($typeSchema); + if ($typeSchema && it.opts.nullable && it.schema.nullable === true) { + if ($typeIsArray) { + if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null'); + } else if ($typeSchema != 'null') { + $typeSchema = [$typeSchema, 'null']; + $typeIsArray = true; + } + } + if ($typeIsArray && $typeSchema.length == 1) { + $typeSchema = $typeSchema[0]; + $typeIsArray = false; + } + if (it.schema.$ref && $refKeywords) { + if (it.opts.extendRefs == 'fail') { + throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); + } else if (it.opts.extendRefs !== true) { + $refKeywords = false; + it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); + } + } + if (it.schema.$comment && it.opts.$comment) { + out += ' ' + (it.RULES.all.$comment.code(it, '$comment')); + } + if ($typeSchema) { + if (it.opts.coerceTypes) { + var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); + } + var $rulesGroup = it.RULES.types[$typeSchema]; + if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) { + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type', + $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; + out += ' if (' + (it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true)) + ') { '; + if ($coerceToTypes) { + var $dataType = 'dataType' + $lvl, + $coerced = 'coerced' + $lvl; + out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; var ' + ($coerced) + ' = undefined; '; + if (it.opts.coerceTypes == 'array') { + out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ') && ' + ($data) + '.length == 1) { ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; if (' + (it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)) + ') ' + ($coerced) + ' = ' + ($data) + '; } '; + } + out += ' if (' + ($coerced) + ' !== undefined) ; '; + var arr1 = $coerceToTypes; + if (arr1) { + var $type, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $type = arr1[$i += 1]; + if ($type == 'string') { + out += ' else if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; '; + } else if ($type == 'number' || $type == 'integer') { + out += ' else if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' '; + if ($type == 'integer') { + out += ' && !(' + ($data) + ' % 1)'; + } + out += ')) ' + ($coerced) + ' = +' + ($data) + '; '; + } else if ($type == 'boolean') { + out += ' else if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; '; + } else if ($type == 'null') { + out += ' else if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; '; + } else if (it.opts.coerceTypes == 'array' && $type == 'array') { + out += ' else if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; '; + } + } + } + out += ' else { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } if (' + ($coerced) + ' !== undefined) { '; + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' ' + ($data) + ' = ' + ($coerced) + '; '; + if (!$dataLvl) { + out += 'if (' + ($parentData) + ' !== undefined)'; + } + out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } '; + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } + out += ' } '; + } + } + if (it.schema.$ref && !$refKeywords) { + out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' '; + if ($breakOnError) { + out += ' } if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } else { + var arr2 = it.RULES; + if (arr2) { + var $rulesGroup, i2 = -1, + l2 = arr2.length - 1; + while (i2 < l2) { + $rulesGroup = arr2[i2 += 1]; + if ($shouldUseGroup($rulesGroup)) { + if ($rulesGroup.type) { + out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers)) + ') { '; + } + if (it.opts.useDefaults) { + if ($rulesGroup.type == 'object' && it.schema.properties) { + var $schema = it.schema.properties, + $schemaKeys = Object.keys($schema); + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ($sch.default !== undefined) { + var $passData = $data + it.util.getProperty($propertyKey); + if (it.compositeRule) { + if (it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored for: ' + $passData; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + } else { + out += ' if (' + ($passData) + ' === undefined '; + if (it.opts.useDefaults == 'empty') { + out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; + } + out += ' ) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } + } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) { + var arr4 = it.schema.items; + if (arr4) { + var $sch, $i = -1, + l4 = arr4.length - 1; + while ($i < l4) { + $sch = arr4[$i += 1]; + if ($sch.default !== undefined) { + var $passData = $data + '[' + $i + ']'; + if (it.compositeRule) { + if (it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored for: ' + $passData; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + } else { + out += ' if (' + ($passData) + ' === undefined '; + if (it.opts.useDefaults == 'empty') { + out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; + } + out += ' ) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } + } + } + var arr5 = $rulesGroup.rules; + if (arr5) { + var $rule, i5 = -1, + l5 = arr5.length - 1; + while (i5 < l5) { + $rule = arr5[i5 += 1]; + if ($shouldUseRule($rule)) { + var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); + if ($code) { + out += ' ' + ($code) + ' '; + if ($breakOnError) { + $closingBraces1 += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces1) + ' '; + $closingBraces1 = ''; + } + if ($rulesGroup.type) { + out += ' } '; + if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { + out += ' else { '; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + } + } + if ($breakOnError) { + out += ' if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces2) + ' '; + } + if ($top) { + if ($async) { + out += ' if (errors === 0) return data; '; + out += ' else throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; '; + out += ' return errors === 0; '; + } + out += ' }; return validate;'; + } else { + out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';'; + } + + function $shouldUseGroup($rulesGroup) { + var rules = $rulesGroup.rules; + for (var i = 0; i < rules.length; i++) + if ($shouldUseRule(rules[i])) return true; + } + + function $shouldUseRule($rule) { + return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule)); + } + + function $ruleImplementsSomeKeyword($rule) { + var impl = $rule.implements; + for (var i = 0; i < impl.length; i++) + if (it.schema[impl[i]] !== undefined) return true; + } + return out; +} diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/lib/keyword.js b/tools/ui/node_modules/eslint/node_modules/ajv/lib/keyword.js new file mode 100644 index 0000000000000000000000000000000000000000..06da9a2dfbe5cc59f86b6bd5fc062ca8f20b2762 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/lib/keyword.js @@ -0,0 +1,146 @@ +'use strict'; + +var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i; +var customRuleCode = require('./dotjs/custom'); +var definitionSchema = require('./definition_schema'); + +module.exports = { + add: addKeyword, + get: getKeyword, + remove: removeKeyword, + validate: validateKeyword +}; + + +/** + * Define custom keyword + * @this Ajv + * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords). + * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. + * @return {Ajv} this for method chaining + */ +function addKeyword(keyword, definition) { + /* jshint validthis: true */ + /* eslint no-shadow: 0 */ + var RULES = this.RULES; + if (RULES.keywords[keyword]) + throw new Error('Keyword ' + keyword + ' is already defined'); + + if (!IDENTIFIER.test(keyword)) + throw new Error('Keyword ' + keyword + ' is not a valid identifier'); + + if (definition) { + this.validateKeyword(definition, true); + + var dataType = definition.type; + if (Array.isArray(dataType)) { + for (var i=0; i ../ajv-dist/bower.json + cd ../ajv-dist + + if [[ `git status --porcelain` ]]; then + echo "Changes detected. Updating master branch..." + git add -A + git commit -m "updated by travis build #$TRAVIS_BUILD_NUMBER" + git push --quiet origin master > /dev/null 2>&1 + fi + + echo "Publishing tag..." + + git tag $TRAVIS_TAG + git push --tags > /dev/null 2>&1 + + echo "Done" +fi diff --git a/tools/ui/node_modules/eslint/node_modules/ajv/scripts/travis-gh-pages b/tools/ui/node_modules/eslint/node_modules/ajv/scripts/travis-gh-pages new file mode 100644 index 0000000000000000000000000000000000000000..b3d4f3d0f489d462bd97d7c00f6677f446b8f6f8 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/ajv/scripts/travis-gh-pages @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +set -e + +if [[ "$TRAVIS_BRANCH" == "master" && "$TRAVIS_PULL_REQUEST" == "false" && $TRAVIS_JOB_NUMBER =~ ".3" ]]; then + git diff --name-only $TRAVIS_COMMIT_RANGE | grep -qE '\.md$|^LICENSE$|travis-gh-pages$' && { + rm -rf ../gh-pages + git clone -b gh-pages --single-branch https://${GITHUB_TOKEN}@github.com/ajv-validator/ajv.git ../gh-pages + mkdir -p ../gh-pages/_source + cp *.md ../gh-pages/_source + cp LICENSE ../gh-pages/_source + currentDir=$(pwd) + cd ../gh-pages + $currentDir/node_modules/.bin/gh-pages-generator + # remove logo from README + sed -i -E "s/]+ajv_logo[^>]+>//" index.md + git config user.email "$GIT_USER_EMAIL" + git config user.name "$GIT_USER_NAME" + git add . + git commit -am "updated by travis build #$TRAVIS_BUILD_NUMBER" + git push --quiet origin gh-pages > /dev/null 2>&1 + } +fi diff --git a/tools/ui/node_modules/eslint/node_modules/json-schema-traverse/.eslintrc.yml b/tools/ui/node_modules/eslint/node_modules/json-schema-traverse/.eslintrc.yml new file mode 100644 index 0000000000000000000000000000000000000000..ab1762da9c119e9136ea914209716dd949648d8b --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/json-schema-traverse/.eslintrc.yml @@ -0,0 +1,27 @@ +extends: eslint:recommended +env: + node: true + browser: true +rules: + block-scoped-var: 2 + complexity: [2, 13] + curly: [2, multi-or-nest, consistent] + dot-location: [2, property] + dot-notation: 2 + indent: [2, 2, SwitchCase: 1] + linebreak-style: [2, unix] + new-cap: 2 + no-console: [2, allow: [warn, error]] + no-else-return: 2 + no-eq-null: 2 + no-fallthrough: 2 + no-invalid-this: 2 + no-return-assign: 2 + no-shadow: 1 + no-trailing-spaces: 2 + no-use-before-define: [2, nofunc] + quotes: [2, single, avoid-escape] + semi: [2, always] + strict: [2, global] + valid-jsdoc: [2, requireReturn: false] + no-control-regex: 0 diff --git a/tools/ui/node_modules/eslint/node_modules/json-schema-traverse/.travis.yml b/tools/ui/node_modules/eslint/node_modules/json-schema-traverse/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..7ddce74b841994f44f2b986f6ffd6f676c141469 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/json-schema-traverse/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +node_js: + - "4" + - "6" + - "7" + - "8" +after_script: + - coveralls < coverage/lcov.info diff --git a/tools/ui/node_modules/eslint/node_modules/json-schema-traverse/LICENSE b/tools/ui/node_modules/eslint/node_modules/json-schema-traverse/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7f1543566f6abbbf75914db32651cf89919cabed --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/json-schema-traverse/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Evgeny Poberezkin + +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/tools/ui/node_modules/eslint/node_modules/json-schema-traverse/README.md b/tools/ui/node_modules/eslint/node_modules/json-schema-traverse/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d5ccaf450a2a2bb88e5ae0778ce05712ef25c763 --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/json-schema-traverse/README.md @@ -0,0 +1,83 @@ +# json-schema-traverse +Traverse JSON Schema passing each schema object to callback + +[![Build Status](https://travis-ci.org/epoberezkin/json-schema-traverse.svg?branch=master)](https://travis-ci.org/epoberezkin/json-schema-traverse) +[![npm version](https://badge.fury.io/js/json-schema-traverse.svg)](https://www.npmjs.com/package/json-schema-traverse) +[![Coverage Status](https://coveralls.io/repos/github/epoberezkin/json-schema-traverse/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master) + + +## Install + +``` +npm install json-schema-traverse +``` + + +## Usage + +```javascript +const traverse = require('json-schema-traverse'); +const schema = { + properties: { + foo: {type: 'string'}, + bar: {type: 'integer'} + } +}; + +traverse(schema, {cb}); +// cb is called 3 times with: +// 1. root schema +// 2. {type: 'string'} +// 3. {type: 'integer'} + +// Or: + +traverse(schema, {cb: {pre, post}}); +// pre is called 3 times with: +// 1. root schema +// 2. {type: 'string'} +// 3. {type: 'integer'} +// +// post is called 3 times with: +// 1. {type: 'string'} +// 2. {type: 'integer'} +// 3. root schema + +``` + +Callback function `cb` is called for each schema object (not including draft-06 boolean schemas), including the root schema, in pre-order traversal. Schema references ($ref) are not resolved, they are passed as is. Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` will be called before traversing child elements, and `post` will be called after all child elements have been traversed. + +Callback is passed these parameters: + +- _schema_: the current schema object +- _JSON pointer_: from the root schema to the current schema object +- _root schema_: the schema passed to `traverse` object +- _parent JSON pointer_: from the root schema to the parent schema object (see below) +- _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.) +- _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema +- _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'` + + +## Traverse objects in all unknown keywords + +```javascript +const traverse = require('json-schema-traverse'); +const schema = { + mySchema: { + minimum: 1, + maximum: 2 + } +}; + +traverse(schema, {allKeys: true, cb}); +// cb is called 2 times with: +// 1. root schema +// 2. mySchema +``` + +Without option `allKeys: true` callback will be called only with root schema. + + +## License + +[MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE) diff --git a/tools/ui/node_modules/eslint/node_modules/json-schema-traverse/index.js b/tools/ui/node_modules/eslint/node_modules/json-schema-traverse/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d4a18dfc7b1c5381b32f62db6aa54ba9251d604a --- /dev/null +++ b/tools/ui/node_modules/eslint/node_modules/json-schema-traverse/index.js @@ -0,0 +1,89 @@ +'use strict'; + +var traverse = module.exports = function (schema, opts, cb) { + // Legacy support for v0.3.1 and earlier. + if (typeof opts == 'function') { + cb = opts; + opts = {}; + } + + cb = opts.cb || cb; + var pre = (typeof cb == 'function') ? cb : cb.pre || function() {}; + var post = cb.post || function() {}; + + _traverse(opts, pre, post, schema, '', schema); +}; + + +traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true +}; + +traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true +}; + +traverse.propsKeywords = { + definitions: true, + properties: true, + patternProperties: true, + dependencies: true +}; + +traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true +}; + + +function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == 'object' && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) { + for (var i=0; i", + "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", + "lint": "trunk check --no-fix --ignore=docs/**/*.js -a --filter=eslint && trunk check --no-fix --ignore=docs/**/*.js", + "lint:docs:js": "trunk check --no-fix --ignore=** --ignore=!docs/**/*.js -a --filter=eslint && trunk check --no-fix --ignore=** --ignore=!docs/**/*.js", + "lint:docs:rule-examples": "node Makefile.js checkRuleExamples", + "lint:unused": "knip", + "lint:fix": "trunk check -y --ignore=docs/**/*.js -a --filter=eslint && trunk check -y --ignore=docs/**/*.js", + "lint:fix:docs:js": "trunk check -y --ignore=** --ignore=!docs/**/*.js -a --filter=eslint && trunk check -y --ignore=** --ignore=!docs/**/*.js", + "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: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" + }, + "gitHooks": { + "pre-commit": "lint-staged" + }, + "lint-staged": { + "*": "trunk check --fix", + "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" + ] + }, + "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.1", + "@eslint/config-array": "^0.21.2", + "@eslint/config-helpers": "^0.4.2", + "@eslint/core": "^0.17.0", + "@eslint/eslintrc": "^3.3.5", + "@eslint/js": "9.39.4", + "@eslint/plugin-kit": "^0.4.1", + "@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", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.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", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.5", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.18.0", + "@babel/core": "^7.4.3", + "@babel/preset-env": "^7.4.3", + "@cypress/webpack-preprocessor": "^6.0.2", + "@eslint/json": "^0.13.2", + "@trunkio/launcher": "^1.3.4", + "@types/esquery": "^1.5.4", + "@types/node": "^22.13.14", + "@typescript-eslint/parser": "^8.4.0", + "babel-loader": "^8.0.5", + "c8": "^7.12.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": "^6.0.0", + "eslint-plugin-expect-type": "^0.6.0", + "eslint-plugin-yml": "^1.14.0", + "eslint-release": "^3.3.0", + "eslint-rule-composer": "^0.3.0", + "eslump": "^3.0.0", + "esprima": "^4.0.1", + "fast-glob": "^3.2.11", + "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", + "jiti-v2.0": "npm:jiti@2.0.x", + "jiti-v2.1": "npm:jiti@2.1.x", + "knip": "^5.60.2", + "lint-staged": "^11.0.0", + "markdown-it": "^12.2.0", + "markdown-it-container": "^3.0.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", + "pirates": "^4.0.5", + "progress": "^2.0.3", + "proxyquire": "^2.0.1", + "recast": "^0.23.0", + "regenerator-runtime": "^0.14.0", + "semver": "^7.5.3", + "shelljs": "^0.10.0", + "sinon": "^11.0.0", + "typescript": "^5.3.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": "^18.18.0 || ^20.9.0 || >=21.1.0" + } +}