eslint 8.18.0 → 8.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -9
- package/lib/config/default-config.js +16 -7
- package/lib/config/flat-config-array.js +41 -2
- package/lib/config/flat-config-helpers.js +9 -1
- package/lib/eslint/eslint-helpers.js +621 -0
- package/lib/eslint/flat-eslint.js +1164 -0
- package/lib/eslint/index.js +3 -1
- package/lib/linter/linter.js +72 -4
- package/lib/rule-tester/flat-rule-tester.js +41 -38
- package/lib/rule-tester/rule-tester.js +42 -0
- package/lib/rules/accessor-pairs.js +1 -1
- package/lib/rules/array-bracket-newline.js +1 -1
- package/lib/rules/array-bracket-spacing.js +1 -1
- package/lib/rules/array-callback-return.js +1 -1
- package/lib/rules/array-element-newline.js +1 -1
- package/lib/rules/arrow-body-style.js +1 -1
- package/lib/rules/arrow-parens.js +1 -1
- package/lib/rules/arrow-spacing.js +1 -1
- package/lib/rules/block-scoped-var.js +1 -1
- package/lib/rules/block-spacing.js +1 -1
- package/lib/rules/brace-style.js +1 -1
- package/lib/rules/callback-return.js +1 -1
- package/lib/rules/camelcase.js +1 -1
- package/lib/rules/capitalized-comments.js +1 -1
- package/lib/rules/class-methods-use-this.js +1 -1
- package/lib/rules/comma-dangle.js +1 -1
- package/lib/rules/comma-spacing.js +36 -42
- package/lib/rules/comma-style.js +1 -1
- package/lib/rules/complexity.js +1 -1
- package/lib/rules/computed-property-spacing.js +1 -1
- package/lib/rules/consistent-return.js +1 -1
- package/lib/rules/consistent-this.js +1 -1
- package/lib/rules/constructor-super.js +1 -1
- package/lib/rules/curly.js +1 -1
- package/lib/rules/default-case-last.js +1 -1
- package/lib/rules/default-case.js +1 -1
- package/lib/rules/default-param-last.js +1 -1
- package/lib/rules/dot-location.js +1 -1
- package/lib/rules/dot-notation.js +1 -1
- package/lib/rules/eol-last.js +1 -1
- package/lib/rules/eqeqeq.js +1 -1
- package/lib/rules/for-direction.js +1 -1
- package/lib/rules/func-call-spacing.js +1 -1
- package/lib/rules/func-name-matching.js +1 -1
- package/lib/rules/func-names.js +1 -1
- package/lib/rules/func-style.js +1 -1
- package/lib/rules/function-call-argument-newline.js +1 -1
- package/lib/rules/function-paren-newline.js +1 -1
- package/lib/rules/generator-star-spacing.js +1 -1
- package/lib/rules/getter-return.js +1 -1
- package/lib/rules/global-require.js +1 -1
- package/lib/rules/grouped-accessor-pairs.js +1 -1
- package/lib/rules/guard-for-in.js +1 -1
- package/lib/rules/handle-callback-err.js +1 -1
- package/lib/rules/id-blacklist.js +1 -1
- package/lib/rules/id-denylist.js +1 -1
- package/lib/rules/id-length.js +1 -1
- package/lib/rules/id-match.js +1 -1
- package/lib/rules/implicit-arrow-linebreak.js +1 -1
- package/lib/rules/indent-legacy.js +1 -1
- package/lib/rules/indent.js +3 -3
- package/lib/rules/init-declarations.js +1 -1
- package/lib/rules/jsx-quotes.js +1 -1
- package/lib/rules/key-spacing.js +5 -2
- package/lib/rules/keyword-spacing.js +1 -1
- package/lib/rules/line-comment-position.js +1 -1
- package/lib/rules/linebreak-style.js +1 -1
- package/lib/rules/lines-around-comment.js +12 -5
- package/lib/rules/lines-around-directive.js +1 -1
- package/lib/rules/lines-between-class-members.js +1 -1
- package/lib/rules/max-classes-per-file.js +1 -1
- package/lib/rules/max-depth.js +1 -1
- package/lib/rules/max-len.js +1 -1
- package/lib/rules/max-lines-per-function.js +1 -1
- package/lib/rules/max-lines.js +1 -1
- package/lib/rules/max-nested-callbacks.js +1 -1
- package/lib/rules/max-params.js +1 -1
- package/lib/rules/max-statements-per-line.js +1 -1
- package/lib/rules/max-statements.js +1 -1
- package/lib/rules/multiline-comment-style.js +1 -1
- package/lib/rules/multiline-ternary.js +1 -1
- package/lib/rules/new-cap.js +1 -1
- package/lib/rules/new-parens.js +1 -1
- package/lib/rules/newline-after-var.js +1 -1
- package/lib/rules/newline-before-return.js +1 -1
- package/lib/rules/newline-per-chained-call.js +1 -1
- package/lib/rules/no-alert.js +1 -1
- package/lib/rules/no-array-constructor.js +1 -1
- package/lib/rules/no-async-promise-executor.js +1 -1
- package/lib/rules/no-await-in-loop.js +1 -1
- package/lib/rules/no-bitwise.js +1 -1
- package/lib/rules/no-buffer-constructor.js +1 -1
- package/lib/rules/no-caller.js +1 -1
- package/lib/rules/no-case-declarations.js +1 -1
- package/lib/rules/no-catch-shadow.js +1 -1
- package/lib/rules/no-class-assign.js +1 -1
- package/lib/rules/no-compare-neg-zero.js +1 -1
- package/lib/rules/no-cond-assign.js +1 -1
- package/lib/rules/no-confusing-arrow.js +1 -1
- package/lib/rules/no-console.js +1 -1
- package/lib/rules/no-const-assign.js +1 -1
- package/lib/rules/no-constant-binary-expression.js +1 -1
- package/lib/rules/no-constant-condition.js +1 -1
- package/lib/rules/no-constructor-return.js +1 -1
- package/lib/rules/no-continue.js +1 -1
- package/lib/rules/no-control-regex.js +1 -1
- package/lib/rules/no-debugger.js +1 -1
- package/lib/rules/no-delete-var.js +1 -1
- package/lib/rules/no-div-regex.js +1 -1
- package/lib/rules/no-dupe-args.js +1 -1
- package/lib/rules/no-dupe-class-members.js +1 -1
- package/lib/rules/no-dupe-else-if.js +1 -1
- package/lib/rules/no-dupe-keys.js +1 -1
- package/lib/rules/no-duplicate-case.js +1 -1
- package/lib/rules/no-duplicate-imports.js +1 -1
- package/lib/rules/no-else-return.js +1 -1
- package/lib/rules/no-empty-character-class.js +1 -1
- package/lib/rules/no-empty-function.js +1 -1
- package/lib/rules/no-empty-pattern.js +1 -1
- package/lib/rules/no-empty.js +1 -1
- package/lib/rules/no-eq-null.js +1 -1
- package/lib/rules/no-eval.js +1 -1
- package/lib/rules/no-ex-assign.js +1 -1
- package/lib/rules/no-extend-native.js +1 -1
- package/lib/rules/no-extra-bind.js +1 -1
- package/lib/rules/no-extra-boolean-cast.js +1 -1
- package/lib/rules/no-extra-label.js +1 -1
- package/lib/rules/no-extra-parens.js +1 -1
- package/lib/rules/no-extra-semi.js +1 -1
- package/lib/rules/no-fallthrough.js +1 -1
- package/lib/rules/no-floating-decimal.js +1 -1
- package/lib/rules/no-func-assign.js +1 -1
- package/lib/rules/no-global-assign.js +1 -1
- package/lib/rules/no-implicit-coercion.js +1 -1
- package/lib/rules/no-implicit-globals.js +1 -1
- package/lib/rules/no-implied-eval.js +1 -1
- package/lib/rules/no-import-assign.js +1 -1
- package/lib/rules/no-inline-comments.js +1 -1
- package/lib/rules/no-inner-declarations.js +1 -1
- package/lib/rules/no-invalid-regexp.js +1 -1
- package/lib/rules/no-invalid-this.js +1 -1
- package/lib/rules/no-irregular-whitespace.js +1 -1
- package/lib/rules/no-iterator.js +1 -1
- package/lib/rules/no-label-var.js +1 -1
- package/lib/rules/no-labels.js +1 -1
- package/lib/rules/no-lone-blocks.js +1 -1
- package/lib/rules/no-lonely-if.js +1 -1
- package/lib/rules/no-loop-func.js +1 -1
- package/lib/rules/no-loss-of-precision.js +1 -1
- package/lib/rules/no-magic-numbers.js +1 -1
- package/lib/rules/no-misleading-character-class.js +1 -1
- package/lib/rules/no-mixed-operators.js +1 -1
- package/lib/rules/no-mixed-requires.js +1 -1
- package/lib/rules/no-mixed-spaces-and-tabs.js +1 -1
- package/lib/rules/no-multi-assign.js +1 -1
- package/lib/rules/no-multi-spaces.js +1 -1
- package/lib/rules/no-multi-str.js +1 -1
- package/lib/rules/no-multiple-empty-lines.js +1 -1
- package/lib/rules/no-native-reassign.js +1 -1
- package/lib/rules/no-negated-condition.js +1 -1
- package/lib/rules/no-negated-in-lhs.js +1 -1
- package/lib/rules/no-nested-ternary.js +1 -1
- package/lib/rules/no-new-func.js +1 -1
- package/lib/rules/no-new-object.js +1 -1
- package/lib/rules/no-new-require.js +1 -1
- package/lib/rules/no-new-symbol.js +1 -1
- package/lib/rules/no-new-wrappers.js +1 -1
- package/lib/rules/no-new.js +1 -1
- package/lib/rules/no-nonoctal-decimal-escape.js +1 -1
- package/lib/rules/no-obj-calls.js +1 -1
- package/lib/rules/no-octal-escape.js +1 -1
- package/lib/rules/no-octal.js +1 -1
- package/lib/rules/no-param-reassign.js +1 -1
- package/lib/rules/no-path-concat.js +1 -1
- package/lib/rules/no-plusplus.js +1 -1
- package/lib/rules/no-process-env.js +1 -1
- package/lib/rules/no-process-exit.js +1 -1
- package/lib/rules/no-promise-executor-return.js +1 -1
- package/lib/rules/no-proto.js +1 -1
- package/lib/rules/no-prototype-builtins.js +1 -1
- package/lib/rules/no-redeclare.js +1 -1
- package/lib/rules/no-regex-spaces.js +1 -1
- package/lib/rules/no-restricted-exports.js +1 -1
- package/lib/rules/no-restricted-globals.js +1 -1
- package/lib/rules/no-restricted-imports.js +77 -12
- package/lib/rules/no-restricted-modules.js +1 -1
- package/lib/rules/no-restricted-properties.js +1 -1
- package/lib/rules/no-restricted-syntax.js +1 -1
- package/lib/rules/no-return-assign.js +1 -1
- package/lib/rules/no-return-await.js +1 -1
- package/lib/rules/no-script-url.js +1 -1
- package/lib/rules/no-self-assign.js +1 -1
- package/lib/rules/no-self-compare.js +1 -1
- package/lib/rules/no-sequences.js +1 -1
- package/lib/rules/no-setter-return.js +1 -1
- package/lib/rules/no-shadow-restricted-names.js +1 -1
- package/lib/rules/no-shadow.js +1 -1
- package/lib/rules/no-spaced-func.js +1 -1
- package/lib/rules/no-sparse-arrays.js +1 -1
- package/lib/rules/no-sync.js +1 -1
- package/lib/rules/no-tabs.js +1 -1
- package/lib/rules/no-template-curly-in-string.js +1 -1
- package/lib/rules/no-ternary.js +1 -1
- package/lib/rules/no-this-before-super.js +1 -1
- package/lib/rules/no-throw-literal.js +1 -1
- package/lib/rules/no-trailing-spaces.js +1 -1
- package/lib/rules/no-undef-init.js +1 -1
- package/lib/rules/no-undef.js +1 -1
- package/lib/rules/no-undefined.js +1 -1
- package/lib/rules/no-underscore-dangle.js +1 -1
- package/lib/rules/no-unexpected-multiline.js +1 -1
- package/lib/rules/no-unmodified-loop-condition.js +1 -1
- package/lib/rules/no-unneeded-ternary.js +1 -1
- package/lib/rules/no-unreachable-loop.js +1 -1
- package/lib/rules/no-unreachable.js +1 -1
- package/lib/rules/no-unsafe-finally.js +1 -1
- package/lib/rules/no-unsafe-negation.js +1 -1
- package/lib/rules/no-unsafe-optional-chaining.js +1 -1
- package/lib/rules/no-unused-expressions.js +1 -1
- package/lib/rules/no-unused-labels.js +1 -1
- package/lib/rules/no-unused-private-class-members.js +1 -1
- package/lib/rules/no-unused-vars.js +1 -1
- package/lib/rules/no-use-before-define.js +1 -1
- package/lib/rules/no-useless-backreference.js +1 -1
- package/lib/rules/no-useless-call.js +1 -1
- package/lib/rules/no-useless-catch.js +1 -1
- package/lib/rules/no-useless-computed-key.js +1 -1
- package/lib/rules/no-useless-concat.js +1 -1
- package/lib/rules/no-useless-constructor.js +1 -1
- package/lib/rules/no-useless-escape.js +1 -1
- package/lib/rules/no-useless-rename.js +1 -1
- package/lib/rules/no-useless-return.js +1 -1
- package/lib/rules/no-var.js +1 -1
- package/lib/rules/no-void.js +1 -1
- package/lib/rules/no-warning-comments.js +27 -41
- package/lib/rules/no-whitespace-before-property.js +1 -1
- package/lib/rules/no-with.js +1 -1
- package/lib/rules/nonblock-statement-body-position.js +1 -1
- package/lib/rules/object-curly-newline.js +1 -1
- package/lib/rules/object-curly-spacing.js +1 -1
- package/lib/rules/object-property-newline.js +1 -1
- package/lib/rules/object-shorthand.js +1 -1
- package/lib/rules/one-var-declaration-per-line.js +1 -1
- package/lib/rules/one-var.js +1 -1
- package/lib/rules/operator-assignment.js +1 -1
- package/lib/rules/operator-linebreak.js +1 -1
- package/lib/rules/padded-blocks.js +1 -1
- package/lib/rules/padding-line-between-statements.js +1 -1
- package/lib/rules/prefer-arrow-callback.js +1 -1
- package/lib/rules/prefer-const.js +1 -1
- package/lib/rules/prefer-destructuring.js +1 -1
- package/lib/rules/prefer-exponentiation-operator.js +1 -1
- package/lib/rules/prefer-named-capture-group.js +1 -1
- package/lib/rules/prefer-numeric-literals.js +1 -1
- package/lib/rules/prefer-object-has-own.js +1 -1
- package/lib/rules/prefer-object-spread.js +1 -1
- package/lib/rules/prefer-promise-reject-errors.js +1 -1
- package/lib/rules/prefer-reflect.js +1 -1
- package/lib/rules/prefer-regex-literals.js +1 -1
- package/lib/rules/prefer-rest-params.js +1 -1
- package/lib/rules/prefer-spread.js +1 -1
- package/lib/rules/prefer-template.js +1 -1
- package/lib/rules/quote-props.js +1 -1
- package/lib/rules/quotes.js +1 -1
- package/lib/rules/radix.js +1 -1
- package/lib/rules/require-atomic-updates.js +1 -1
- package/lib/rules/require-await.js +1 -1
- package/lib/rules/require-jsdoc.js +1 -1
- package/lib/rules/require-unicode-regexp.js +1 -1
- package/lib/rules/require-yield.js +1 -1
- package/lib/rules/rest-spread-spacing.js +1 -1
- package/lib/rules/semi-spacing.js +1 -1
- package/lib/rules/semi-style.js +1 -1
- package/lib/rules/semi.js +1 -1
- package/lib/rules/sort-imports.js +1 -1
- package/lib/rules/sort-keys.js +44 -1
- package/lib/rules/sort-vars.js +1 -1
- package/lib/rules/space-before-blocks.js +1 -1
- package/lib/rules/space-before-function-paren.js +1 -1
- package/lib/rules/space-in-parens.js +1 -1
- package/lib/rules/space-infix-ops.js +1 -1
- package/lib/rules/space-unary-ops.js +1 -1
- package/lib/rules/spaced-comment.js +1 -1
- package/lib/rules/strict.js +1 -1
- package/lib/rules/switch-colon-spacing.js +1 -1
- package/lib/rules/symbol-description.js +1 -1
- package/lib/rules/template-curly-spacing.js +1 -1
- package/lib/rules/template-tag-spacing.js +1 -1
- package/lib/rules/unicode-bom.js +1 -1
- package/lib/rules/use-isnan.js +1 -1
- package/lib/rules/valid-jsdoc.js +1 -1
- package/lib/rules/valid-typeof.js +1 -1
- package/lib/rules/vars-on-top.js +1 -1
- package/lib/rules/wrap-iife.js +1 -1
- package/lib/rules/wrap-regex.js +1 -1
- package/lib/rules/yield-star-spacing.js +1 -1
- package/lib/rules/yoda.js +1 -1
- package/lib/unsupported-api.js +4 -0
- package/package.json +13 -10
@@ -0,0 +1,1164 @@
|
|
1
|
+
/**
|
2
|
+
* @fileoverview Main class using flat config
|
3
|
+
* @author Nicholas C. Zakas
|
4
|
+
*/
|
5
|
+
|
6
|
+
"use strict";
|
7
|
+
|
8
|
+
//------------------------------------------------------------------------------
|
9
|
+
// Requirements
|
10
|
+
//------------------------------------------------------------------------------
|
11
|
+
|
12
|
+
// Note: Node.js 12 does not support fs/promises.
|
13
|
+
const fs = require("fs").promises;
|
14
|
+
const path = require("path");
|
15
|
+
const findUp = require("find-up");
|
16
|
+
const { version } = require("../../package.json");
|
17
|
+
const { Linter } = require("../linter");
|
18
|
+
const { getRuleFromConfig } = require("../config/flat-config-helpers");
|
19
|
+
const { gitignoreToMinimatch } = require("@humanwhocodes/gitignore-to-minimatch");
|
20
|
+
const {
|
21
|
+
Legacy: {
|
22
|
+
ConfigOps: {
|
23
|
+
getRuleSeverity
|
24
|
+
},
|
25
|
+
ModuleResolver,
|
26
|
+
naming
|
27
|
+
}
|
28
|
+
} = require("@eslint/eslintrc");
|
29
|
+
|
30
|
+
const {
|
31
|
+
fileExists,
|
32
|
+
findFiles,
|
33
|
+
|
34
|
+
isNonEmptyString,
|
35
|
+
isArrayOfNonEmptyString,
|
36
|
+
|
37
|
+
createIgnoreResult,
|
38
|
+
isErrorMessage,
|
39
|
+
|
40
|
+
processOptions
|
41
|
+
} = require("./eslint-helpers");
|
42
|
+
const { pathToFileURL } = require("url");
|
43
|
+
const { FlatConfigArray } = require("../config/flat-config-array");
|
44
|
+
|
45
|
+
/*
|
46
|
+
* This is necessary to allow overwriting writeFile for testing purposes.
|
47
|
+
* We can just use fs/promises once we drop Node.js 12 support.
|
48
|
+
*/
|
49
|
+
|
50
|
+
//------------------------------------------------------------------------------
|
51
|
+
// Typedefs
|
52
|
+
//------------------------------------------------------------------------------
|
53
|
+
|
54
|
+
// For VSCode IntelliSense
|
55
|
+
/** @typedef {import("../shared/types").ConfigData} ConfigData */
|
56
|
+
/** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */
|
57
|
+
/** @typedef {import("../shared/types").LintMessage} LintMessage */
|
58
|
+
/** @typedef {import("../shared/types").ParserOptions} ParserOptions */
|
59
|
+
/** @typedef {import("../shared/types").Plugin} Plugin */
|
60
|
+
/** @typedef {import("../shared/types").RuleConf} RuleConf */
|
61
|
+
/** @typedef {import("../shared/types").Rule} Rule */
|
62
|
+
/** @typedef {ReturnType<ConfigArray.extractConfig>} ExtractedConfig */
|
63
|
+
|
64
|
+
/**
|
65
|
+
* The options with which to configure the ESLint instance.
|
66
|
+
* @typedef {Object} FlatESLintOptions
|
67
|
+
* @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments.
|
68
|
+
* @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this instance
|
69
|
+
* @property {boolean} [cache] Enable result caching.
|
70
|
+
* @property {string} [cacheLocation] The cache file to use instead of .eslintcache.
|
71
|
+
* @property {"metadata" | "content"} [cacheStrategy] The strategy used to detect changed files.
|
72
|
+
* @property {string} [cwd] The value to use for the current working directory.
|
73
|
+
* @property {boolean} [errorOnUnmatchedPattern] If `false` then `ESLint#lintFiles()` doesn't throw even if no target files found. Defaults to `true`.
|
74
|
+
* @property {string[]} [extensions] An array of file extensions to check.
|
75
|
+
* @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean.
|
76
|
+
* @property {string[]} [fixTypes] Array of rule types to apply fixes for.
|
77
|
+
* @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file.
|
78
|
+
* @property {boolean} [ignore] False disables use of .eslintignore.
|
79
|
+
* @property {string} [ignorePath] The ignore file to use instead of .eslintignore.
|
80
|
+
* @property {string[]} [ignorePatterns] Ignore file patterns to use in addition to .eslintignore.
|
81
|
+
* @property {ConfigData} [overrideConfig] Override config object, overrides all configs used with this instance
|
82
|
+
* @property {boolean|string} [overrideConfigFile] Searches for default config file when falsy;
|
83
|
+
* doesn't do any config file lookup when `true`; considered to be a config filename
|
84
|
+
* when a string.
|
85
|
+
* @property {Record<string,Plugin>} [plugins] An array of plugin implementations.
|
86
|
+
* @property {"error" | "warn" | "off"} [reportUnusedDisableDirectives] the severity to report unused eslint-disable directives.
|
87
|
+
*/
|
88
|
+
|
89
|
+
//------------------------------------------------------------------------------
|
90
|
+
// Helpers
|
91
|
+
//------------------------------------------------------------------------------
|
92
|
+
|
93
|
+
const FLAT_CONFIG_FILENAME = "eslint.config.js";
|
94
|
+
const debug = require("debug")("eslint:flat-eslint");
|
95
|
+
const removedFormatters = new Set(["table", "codeframe"]);
|
96
|
+
const privateMembers = new WeakMap();
|
97
|
+
|
98
|
+
/**
|
99
|
+
* It will calculate the error and warning count for collection of messages per file
|
100
|
+
* @param {LintMessage[]} messages Collection of messages
|
101
|
+
* @returns {Object} Contains the stats
|
102
|
+
* @private
|
103
|
+
*/
|
104
|
+
function calculateStatsPerFile(messages) {
|
105
|
+
return messages.reduce((stat, message) => {
|
106
|
+
if (message.fatal || message.severity === 2) {
|
107
|
+
stat.errorCount++;
|
108
|
+
if (message.fatal) {
|
109
|
+
stat.fatalErrorCount++;
|
110
|
+
}
|
111
|
+
if (message.fix) {
|
112
|
+
stat.fixableErrorCount++;
|
113
|
+
}
|
114
|
+
} else {
|
115
|
+
stat.warningCount++;
|
116
|
+
if (message.fix) {
|
117
|
+
stat.fixableWarningCount++;
|
118
|
+
}
|
119
|
+
}
|
120
|
+
return stat;
|
121
|
+
}, {
|
122
|
+
errorCount: 0,
|
123
|
+
fatalErrorCount: 0,
|
124
|
+
warningCount: 0,
|
125
|
+
fixableErrorCount: 0,
|
126
|
+
fixableWarningCount: 0
|
127
|
+
});
|
128
|
+
}
|
129
|
+
|
130
|
+
/**
|
131
|
+
* It will calculate the error and warning count for collection of results from all files
|
132
|
+
* @param {LintResult[]} results Collection of messages from all the files
|
133
|
+
* @returns {Object} Contains the stats
|
134
|
+
* @private
|
135
|
+
*/
|
136
|
+
function calculateStatsPerRun(results) {
|
137
|
+
return results.reduce((stat, result) => {
|
138
|
+
stat.errorCount += result.errorCount;
|
139
|
+
stat.fatalErrorCount += result.fatalErrorCount;
|
140
|
+
stat.warningCount += result.warningCount;
|
141
|
+
stat.fixableErrorCount += result.fixableErrorCount;
|
142
|
+
stat.fixableWarningCount += result.fixableWarningCount;
|
143
|
+
return stat;
|
144
|
+
}, {
|
145
|
+
errorCount: 0,
|
146
|
+
fatalErrorCount: 0,
|
147
|
+
warningCount: 0,
|
148
|
+
fixableErrorCount: 0,
|
149
|
+
fixableWarningCount: 0
|
150
|
+
});
|
151
|
+
}
|
152
|
+
|
153
|
+
/**
|
154
|
+
* Loads global ignore patterns from an ignore file (usually .eslintignore).
|
155
|
+
* @param {string} filePath The filename to load.
|
156
|
+
* @returns {ignore} A function encapsulating the ignore patterns.
|
157
|
+
* @throws {Error} If the file cannot be read.
|
158
|
+
* @private
|
159
|
+
*/
|
160
|
+
async function loadIgnoreFilePatterns(filePath) {
|
161
|
+
debug(`Loading ignore file: ${filePath}`);
|
162
|
+
|
163
|
+
try {
|
164
|
+
const ignoreFileText = await fs.readFile(filePath, { encoding: "utf8" });
|
165
|
+
|
166
|
+
return ignoreFileText
|
167
|
+
.split(/\r?\n/gu)
|
168
|
+
.filter(line => line.trim() !== "" && !line.startsWith("#"));
|
169
|
+
|
170
|
+
} catch (e) {
|
171
|
+
debug(`Error reading ignore file: ${filePath}`);
|
172
|
+
e.message = `Cannot read ignore file: ${filePath}\nError: ${e.message}`;
|
173
|
+
throw e;
|
174
|
+
}
|
175
|
+
}
|
176
|
+
|
177
|
+
/**
|
178
|
+
* Create rulesMeta object.
|
179
|
+
* @param {Map<string,Rule>} rules a map of rules from which to generate the object.
|
180
|
+
* @returns {Object} metadata for all enabled rules.
|
181
|
+
*/
|
182
|
+
function createRulesMeta(rules) {
|
183
|
+
return Array.from(rules).reduce((retVal, [id, rule]) => {
|
184
|
+
retVal[id] = rule.meta;
|
185
|
+
return retVal;
|
186
|
+
}, {});
|
187
|
+
}
|
188
|
+
|
189
|
+
/** @type {WeakMap<ExtractedConfig, DeprecatedRuleInfo[]>} */
|
190
|
+
const usedDeprecatedRulesCache = new WeakMap();
|
191
|
+
|
192
|
+
/**
|
193
|
+
* Create used deprecated rule list.
|
194
|
+
* @param {CLIEngine} eslint The CLIEngine instance.
|
195
|
+
* @param {string} maybeFilePath The absolute path to a lint target file or `"<text>"`.
|
196
|
+
* @returns {DeprecatedRuleInfo[]} The used deprecated rule list.
|
197
|
+
*/
|
198
|
+
function getOrFindUsedDeprecatedRules(eslint, maybeFilePath) {
|
199
|
+
const {
|
200
|
+
configs,
|
201
|
+
options: { cwd }
|
202
|
+
} = privateMembers.get(eslint);
|
203
|
+
const filePath = path.isAbsolute(maybeFilePath)
|
204
|
+
? maybeFilePath
|
205
|
+
: path.join(cwd, "__placeholder__.js");
|
206
|
+
const config = configs.getConfig(filePath);
|
207
|
+
|
208
|
+
// Most files use the same config, so cache it.
|
209
|
+
if (config && !usedDeprecatedRulesCache.has(config)) {
|
210
|
+
const retv = [];
|
211
|
+
|
212
|
+
if (config.rules) {
|
213
|
+
for (const [ruleId, ruleConf] of Object.entries(config.rules)) {
|
214
|
+
if (getRuleSeverity(ruleConf) === 0) {
|
215
|
+
continue;
|
216
|
+
}
|
217
|
+
const rule = getRuleFromConfig(ruleId, config);
|
218
|
+
const meta = rule && rule.meta;
|
219
|
+
|
220
|
+
if (meta && meta.deprecated) {
|
221
|
+
retv.push({ ruleId, replacedBy: meta.replacedBy || [] });
|
222
|
+
}
|
223
|
+
}
|
224
|
+
}
|
225
|
+
|
226
|
+
|
227
|
+
usedDeprecatedRulesCache.set(config, Object.freeze(retv));
|
228
|
+
}
|
229
|
+
|
230
|
+
return config ? usedDeprecatedRulesCache.get(config) : Object.freeze([]);
|
231
|
+
}
|
232
|
+
|
233
|
+
/**
|
234
|
+
* Processes the linting results generated by a CLIEngine linting report to
|
235
|
+
* match the ESLint class's API.
|
236
|
+
* @param {CLIEngine} eslint The CLIEngine instance.
|
237
|
+
* @param {CLIEngineLintReport} report The CLIEngine linting report to process.
|
238
|
+
* @returns {LintResult[]} The processed linting results.
|
239
|
+
*/
|
240
|
+
function processLintReport(eslint, { results }) {
|
241
|
+
const descriptor = {
|
242
|
+
configurable: true,
|
243
|
+
enumerable: true,
|
244
|
+
get() {
|
245
|
+
return getOrFindUsedDeprecatedRules(eslint, this.filePath);
|
246
|
+
}
|
247
|
+
};
|
248
|
+
|
249
|
+
for (const result of results) {
|
250
|
+
Object.defineProperty(result, "usedDeprecatedRules", descriptor);
|
251
|
+
}
|
252
|
+
|
253
|
+
return results;
|
254
|
+
}
|
255
|
+
|
256
|
+
/**
|
257
|
+
* An Array.prototype.sort() compatible compare function to order results by their file path.
|
258
|
+
* @param {LintResult} a The first lint result.
|
259
|
+
* @param {LintResult} b The second lint result.
|
260
|
+
* @returns {number} An integer representing the order in which the two results should occur.
|
261
|
+
*/
|
262
|
+
function compareResultsByFilePath(a, b) {
|
263
|
+
if (a.filePath < b.filePath) {
|
264
|
+
return -1;
|
265
|
+
}
|
266
|
+
|
267
|
+
if (a.filePath > b.filePath) {
|
268
|
+
return 1;
|
269
|
+
}
|
270
|
+
|
271
|
+
return 0;
|
272
|
+
}
|
273
|
+
|
274
|
+
/**
|
275
|
+
* Searches from the current working directory up until finding the
|
276
|
+
* given flat config filename.
|
277
|
+
* @param {string} cwd The current working directory to search from.
|
278
|
+
* @returns {Promise<string|null>} The filename if found or `null` if not.
|
279
|
+
*/
|
280
|
+
function findFlatConfigFile(cwd) {
|
281
|
+
return findUp(
|
282
|
+
FLAT_CONFIG_FILENAME,
|
283
|
+
{ cwd }
|
284
|
+
);
|
285
|
+
}
|
286
|
+
|
287
|
+
/**
|
288
|
+
* Load the config array from the given filename.
|
289
|
+
* @param {string} filePath The filename to load from.
|
290
|
+
* @param {Object} options Options to help load the config file.
|
291
|
+
* @param {string} options.basePath The base path for the config array.
|
292
|
+
* @param {boolean} options.shouldIgnore Whether to honor ignore patterns.
|
293
|
+
* @returns {Promise<FlatConfigArray>} The config array loaded from the config file.
|
294
|
+
*/
|
295
|
+
async function loadFlatConfigFile(filePath, { basePath, shouldIgnore }) {
|
296
|
+
debug(`Loading config from ${filePath}`);
|
297
|
+
|
298
|
+
const fileURL = pathToFileURL(filePath);
|
299
|
+
|
300
|
+
debug(`Config file URL is ${fileURL}`);
|
301
|
+
|
302
|
+
const module = await import(fileURL);
|
303
|
+
|
304
|
+
return new FlatConfigArray(module.default, {
|
305
|
+
basePath,
|
306
|
+
shouldIgnore
|
307
|
+
});
|
308
|
+
}
|
309
|
+
|
310
|
+
/**
|
311
|
+
* Calculates the config array for this run based on inputs.
|
312
|
+
* @param {FlatESLint} eslint The instance to create the config array for.
|
313
|
+
* @param {import("./eslint").ESLintOptions} options The ESLint instance options.
|
314
|
+
* @returns {FlatConfigArray} The config array for `eslint``.
|
315
|
+
*/
|
316
|
+
async function calculateConfigArray(eslint, {
|
317
|
+
cwd,
|
318
|
+
overrideConfig,
|
319
|
+
configFile,
|
320
|
+
ignore: shouldIgnore,
|
321
|
+
ignorePath,
|
322
|
+
ignorePatterns,
|
323
|
+
extensions
|
324
|
+
}) {
|
325
|
+
|
326
|
+
// check for cached instance
|
327
|
+
const slots = privateMembers.get(eslint);
|
328
|
+
|
329
|
+
if (slots.configs) {
|
330
|
+
return slots.configs;
|
331
|
+
}
|
332
|
+
|
333
|
+
// determine where to load config file from
|
334
|
+
let configFilePath;
|
335
|
+
let basePath = cwd;
|
336
|
+
|
337
|
+
if (typeof configFile === "string") {
|
338
|
+
debug(`Override config file path is ${configFile}`);
|
339
|
+
configFilePath = path.resolve(cwd, configFile);
|
340
|
+
} else if (configFile !== false) {
|
341
|
+
debug("Searching for eslint.config.js");
|
342
|
+
configFilePath = await findFlatConfigFile(cwd);
|
343
|
+
|
344
|
+
if (!configFilePath) {
|
345
|
+
throw new Error("Could not find config file.");
|
346
|
+
}
|
347
|
+
|
348
|
+
basePath = path.resolve(path.dirname(configFilePath));
|
349
|
+
}
|
350
|
+
|
351
|
+
// load config array
|
352
|
+
let configs;
|
353
|
+
|
354
|
+
if (configFilePath) {
|
355
|
+
configs = await loadFlatConfigFile(configFilePath, {
|
356
|
+
basePath,
|
357
|
+
shouldIgnore
|
358
|
+
});
|
359
|
+
} else {
|
360
|
+
configs = new FlatConfigArray([], { basePath, shouldIgnore });
|
361
|
+
}
|
362
|
+
|
363
|
+
// add in any configured defaults
|
364
|
+
configs.push(...slots.defaultConfigs);
|
365
|
+
|
366
|
+
// if there are any extensions, create configs for them for easier matching
|
367
|
+
if (extensions && extensions.length) {
|
368
|
+
configs.push({
|
369
|
+
files: extensions.map(ext => `**/*${ext}`)
|
370
|
+
});
|
371
|
+
}
|
372
|
+
|
373
|
+
let allIgnorePatterns = [];
|
374
|
+
let ignoreFilePath;
|
375
|
+
|
376
|
+
// load ignore file if necessary
|
377
|
+
if (shouldIgnore) {
|
378
|
+
if (ignorePath) {
|
379
|
+
ignoreFilePath = path.resolve(cwd, ignorePath);
|
380
|
+
allIgnorePatterns = await loadIgnoreFilePatterns(ignoreFilePath);
|
381
|
+
} else {
|
382
|
+
ignoreFilePath = path.resolve(cwd, ".eslintignore");
|
383
|
+
|
384
|
+
// no error if .eslintignore doesn't exist`
|
385
|
+
if (fileExists(ignoreFilePath)) {
|
386
|
+
allIgnorePatterns = await loadIgnoreFilePatterns(ignoreFilePath);
|
387
|
+
}
|
388
|
+
}
|
389
|
+
}
|
390
|
+
|
391
|
+
// append command line ignore patterns
|
392
|
+
if (ignorePatterns) {
|
393
|
+
if (typeof ignorePatterns === "string") {
|
394
|
+
allIgnorePatterns.push(ignorePatterns);
|
395
|
+
} else {
|
396
|
+
allIgnorePatterns.push(...ignorePatterns);
|
397
|
+
}
|
398
|
+
}
|
399
|
+
|
400
|
+
/*
|
401
|
+
* If the config file basePath is different than the cwd, then
|
402
|
+
* the ignore patterns won't work correctly. Here, we adjust the
|
403
|
+
* ignore pattern to include the correct relative path. Patterns
|
404
|
+
* loaded from ignore files are always relative to the cwd, whereas
|
405
|
+
* the config file basePath can be an ancestor of the cwd.
|
406
|
+
*/
|
407
|
+
if (basePath !== cwd && allIgnorePatterns.length) {
|
408
|
+
|
409
|
+
const relativeIgnorePath = path.relative(basePath, cwd);
|
410
|
+
|
411
|
+
allIgnorePatterns = allIgnorePatterns.map(pattern => {
|
412
|
+
const negated = pattern.startsWith("!");
|
413
|
+
const basePattern = negated ? pattern.slice(1) : pattern;
|
414
|
+
|
415
|
+
/*
|
416
|
+
* Ignore patterns are considered relative to a directory
|
417
|
+
* when the pattern contains a slash in a position other
|
418
|
+
* than the last character. If that's the case, we need to
|
419
|
+
* add the relative ignore path to the current pattern to
|
420
|
+
* get the correct behavior. Otherwise, no change is needed.
|
421
|
+
*/
|
422
|
+
if (!basePattern.includes("/") || basePattern.endsWith("/")) {
|
423
|
+
return pattern;
|
424
|
+
}
|
425
|
+
|
426
|
+
return (negated ? "!" : "") +
|
427
|
+
path.posix.join(relativeIgnorePath, basePattern);
|
428
|
+
});
|
429
|
+
}
|
430
|
+
|
431
|
+
if (allIgnorePatterns.length) {
|
432
|
+
|
433
|
+
/*
|
434
|
+
* Ignore patterns are added to the end of the config array
|
435
|
+
* so they can override default ignores.
|
436
|
+
*/
|
437
|
+
configs.push({
|
438
|
+
ignores: allIgnorePatterns.map(gitignoreToMinimatch)
|
439
|
+
});
|
440
|
+
}
|
441
|
+
|
442
|
+
if (overrideConfig) {
|
443
|
+
if (Array.isArray(overrideConfig)) {
|
444
|
+
configs.push(...overrideConfig);
|
445
|
+
} else {
|
446
|
+
configs.push(overrideConfig);
|
447
|
+
}
|
448
|
+
}
|
449
|
+
|
450
|
+
await configs.normalize();
|
451
|
+
|
452
|
+
// cache the config array for this instance
|
453
|
+
slots.configs = configs;
|
454
|
+
|
455
|
+
return configs;
|
456
|
+
}
|
457
|
+
|
458
|
+
/**
|
459
|
+
* Processes an source code using ESLint.
|
460
|
+
* @param {Object} config The config object.
|
461
|
+
* @param {string} config.text The source code to verify.
|
462
|
+
* @param {string} config.cwd The path to the current working directory.
|
463
|
+
* @param {string|undefined} config.filePath The path to the file of `text`. If this is undefined, it uses `<text>`.
|
464
|
+
* @param {FlatConfigArray} config.configs The config.
|
465
|
+
* @param {boolean} config.fix If `true` then it does fix.
|
466
|
+
* @param {boolean} config.allowInlineConfig If `true` then it uses directive comments.
|
467
|
+
* @param {boolean} config.reportUnusedDisableDirectives If `true` then it reports unused `eslint-disable` comments.
|
468
|
+
* @param {Linter} config.linter The linter instance to verify.
|
469
|
+
* @returns {LintResult} The result of linting.
|
470
|
+
* @private
|
471
|
+
*/
|
472
|
+
function verifyText({
|
473
|
+
text,
|
474
|
+
cwd,
|
475
|
+
filePath: providedFilePath,
|
476
|
+
configs,
|
477
|
+
fix,
|
478
|
+
allowInlineConfig,
|
479
|
+
reportUnusedDisableDirectives,
|
480
|
+
linter
|
481
|
+
}) {
|
482
|
+
const filePath = providedFilePath || "<text>";
|
483
|
+
|
484
|
+
debug(`Lint ${filePath}`);
|
485
|
+
|
486
|
+
/*
|
487
|
+
* Verify.
|
488
|
+
* `config.extractConfig(filePath)` requires an absolute path, but `linter`
|
489
|
+
* doesn't know CWD, so it gives `linter` an absolute path always.
|
490
|
+
*/
|
491
|
+
const filePathToVerify = filePath === "<text>" ? path.join(cwd, "__placeholder__.js") : filePath;
|
492
|
+
const { fixed, messages, output } = linter.verifyAndFix(
|
493
|
+
text,
|
494
|
+
configs,
|
495
|
+
{
|
496
|
+
allowInlineConfig,
|
497
|
+
filename: filePathToVerify,
|
498
|
+
fix,
|
499
|
+
reportUnusedDisableDirectives,
|
500
|
+
|
501
|
+
/**
|
502
|
+
* Check if the linter should adopt a given code block or not.
|
503
|
+
* @param {string} blockFilename The virtual filename of a code block.
|
504
|
+
* @returns {boolean} `true` if the linter should adopt the code block.
|
505
|
+
*/
|
506
|
+
filterCodeBlock(blockFilename) {
|
507
|
+
return configs.isExplicitMatch(blockFilename);
|
508
|
+
}
|
509
|
+
}
|
510
|
+
);
|
511
|
+
|
512
|
+
// Tweak and return.
|
513
|
+
const result = {
|
514
|
+
filePath: filePath === "<text>" ? filePath : path.resolve(filePath),
|
515
|
+
messages,
|
516
|
+
...calculateStatsPerFile(messages)
|
517
|
+
};
|
518
|
+
|
519
|
+
if (fixed) {
|
520
|
+
result.output = output;
|
521
|
+
}
|
522
|
+
|
523
|
+
if (
|
524
|
+
result.errorCount + result.warningCount > 0 &&
|
525
|
+
typeof result.output === "undefined"
|
526
|
+
) {
|
527
|
+
result.source = text;
|
528
|
+
}
|
529
|
+
|
530
|
+
return result;
|
531
|
+
}
|
532
|
+
|
533
|
+
/**
|
534
|
+
* Checks whether a message's rule type should be fixed.
|
535
|
+
* @param {LintMessage} message The message to check.
|
536
|
+
* @param {FlatConfig} config The config for the file that generated the message.
|
537
|
+
* @param {string[]} fixTypes An array of fix types to check.
|
538
|
+
* @returns {boolean} Whether the message should be fixed.
|
539
|
+
*/
|
540
|
+
function shouldMessageBeFixed(message, config, fixTypes) {
|
541
|
+
if (!message.ruleId) {
|
542
|
+
return fixTypes.has("directive");
|
543
|
+
}
|
544
|
+
|
545
|
+
const rule = message.ruleId && getRuleFromConfig(message.ruleId, config);
|
546
|
+
|
547
|
+
return Boolean(rule && rule.meta && fixTypes.has(rule.meta.type));
|
548
|
+
}
|
549
|
+
|
550
|
+
/**
|
551
|
+
* Collect used deprecated rules.
|
552
|
+
* @param {Array<FlatConfig>} configs The configs to evaluate.
|
553
|
+
* @returns {IterableIterator<DeprecatedRuleInfo>} Used deprecated rules.
|
554
|
+
*/
|
555
|
+
function *iterateRuleDeprecationWarnings(configs) {
|
556
|
+
const processedRuleIds = new Set();
|
557
|
+
|
558
|
+
for (const config of configs) {
|
559
|
+
for (const [ruleId, ruleConfig] of Object.entries(config.rules)) {
|
560
|
+
|
561
|
+
// Skip if it was processed.
|
562
|
+
if (processedRuleIds.has(ruleId)) {
|
563
|
+
continue;
|
564
|
+
}
|
565
|
+
processedRuleIds.add(ruleId);
|
566
|
+
|
567
|
+
// Skip if it's not used.
|
568
|
+
if (!getRuleSeverity(ruleConfig)) {
|
569
|
+
continue;
|
570
|
+
}
|
571
|
+
const rule = getRuleFromConfig(ruleId, config);
|
572
|
+
|
573
|
+
// Skip if it's not deprecated.
|
574
|
+
if (!(rule && rule.meta && rule.meta.deprecated)) {
|
575
|
+
continue;
|
576
|
+
}
|
577
|
+
|
578
|
+
// This rule was used and deprecated.
|
579
|
+
yield {
|
580
|
+
ruleId,
|
581
|
+
replacedBy: rule.meta.replacedBy || []
|
582
|
+
};
|
583
|
+
}
|
584
|
+
}
|
585
|
+
}
|
586
|
+
|
587
|
+
//-----------------------------------------------------------------------------
|
588
|
+
// Main API
|
589
|
+
//-----------------------------------------------------------------------------
|
590
|
+
|
591
|
+
/**
|
592
|
+
* Primary Node.js API for ESLint.
|
593
|
+
*/
|
594
|
+
class FlatESLint {
|
595
|
+
|
596
|
+
/**
|
597
|
+
* Creates a new instance of the main ESLint API.
|
598
|
+
* @param {FlatESLintOptions} options The options for this instance.
|
599
|
+
*/
|
600
|
+
constructor(options = {}) {
|
601
|
+
|
602
|
+
const defaultConfigs = [];
|
603
|
+
const processedOptions = processOptions(options);
|
604
|
+
const linter = new Linter({
|
605
|
+
cwd: processedOptions.cwd,
|
606
|
+
configType: "flat"
|
607
|
+
});
|
608
|
+
|
609
|
+
privateMembers.set(this, {
|
610
|
+
options: processedOptions,
|
611
|
+
linter,
|
612
|
+
defaultConfigs,
|
613
|
+
defaultIgnores: () => false,
|
614
|
+
configs: null
|
615
|
+
});
|
616
|
+
|
617
|
+
/**
|
618
|
+
* If additional plugins are passed in, add that to the default
|
619
|
+
* configs for this instance.
|
620
|
+
*/
|
621
|
+
if (options.plugins) {
|
622
|
+
|
623
|
+
const plugins = {};
|
624
|
+
|
625
|
+
for (const [pluginName, plugin] of Object.entries(options.plugins)) {
|
626
|
+
plugins[naming.getShorthandName(pluginName, "eslint-plugin")] = plugin;
|
627
|
+
}
|
628
|
+
|
629
|
+
defaultConfigs.push({
|
630
|
+
plugins
|
631
|
+
});
|
632
|
+
}
|
633
|
+
|
634
|
+
}
|
635
|
+
|
636
|
+
/**
|
637
|
+
* The version text.
|
638
|
+
* @type {string}
|
639
|
+
*/
|
640
|
+
static get version() {
|
641
|
+
return version;
|
642
|
+
}
|
643
|
+
|
644
|
+
/**
|
645
|
+
* Outputs fixes from the given results to files.
|
646
|
+
* @param {LintResult[]} results The lint results.
|
647
|
+
* @returns {Promise<void>} Returns a promise that is used to track side effects.
|
648
|
+
*/
|
649
|
+
static async outputFixes(results) {
|
650
|
+
if (!Array.isArray(results)) {
|
651
|
+
throw new Error("'results' must be an array");
|
652
|
+
}
|
653
|
+
|
654
|
+
await Promise.all(
|
655
|
+
results
|
656
|
+
.filter(result => {
|
657
|
+
if (typeof result !== "object" || result === null) {
|
658
|
+
throw new Error("'results' must include only objects");
|
659
|
+
}
|
660
|
+
return (
|
661
|
+
typeof result.output === "string" &&
|
662
|
+
path.isAbsolute(result.filePath)
|
663
|
+
);
|
664
|
+
})
|
665
|
+
.map(r => fs.writeFile(r.filePath, r.output))
|
666
|
+
);
|
667
|
+
}
|
668
|
+
|
669
|
+
/**
|
670
|
+
* Returns results that only contains errors.
|
671
|
+
* @param {LintResult[]} results The results to filter.
|
672
|
+
* @returns {LintResult[]} The filtered results.
|
673
|
+
*/
|
674
|
+
static getErrorResults(results) {
|
675
|
+
const filtered = [];
|
676
|
+
|
677
|
+
results.forEach(result => {
|
678
|
+
const filteredMessages = result.messages.filter(isErrorMessage);
|
679
|
+
|
680
|
+
if (filteredMessages.length > 0) {
|
681
|
+
filtered.push({
|
682
|
+
...result,
|
683
|
+
messages: filteredMessages,
|
684
|
+
errorCount: filteredMessages.length,
|
685
|
+
warningCount: 0,
|
686
|
+
fixableErrorCount: result.fixableErrorCount,
|
687
|
+
fixableWarningCount: 0
|
688
|
+
});
|
689
|
+
}
|
690
|
+
});
|
691
|
+
|
692
|
+
return filtered;
|
693
|
+
}
|
694
|
+
|
695
|
+
/**
|
696
|
+
* Returns meta objects for each rule represented in the lint results.
|
697
|
+
* @param {LintResult[]} results The results to fetch rules meta for.
|
698
|
+
* @returns {Object} A mapping of ruleIds to rule meta objects.
|
699
|
+
* @throws {TypeError} When the results object wasn't created from this ESLint instance.
|
700
|
+
* @throws {TypeError} When a plugin or rule is missing.
|
701
|
+
*/
|
702
|
+
getRulesMetaForResults(results) {
|
703
|
+
|
704
|
+
const resultRules = new Map();
|
705
|
+
|
706
|
+
// short-circuit simple case
|
707
|
+
if (results.length === 0) {
|
708
|
+
return resultRules;
|
709
|
+
}
|
710
|
+
|
711
|
+
const { configs } = privateMembers.get(this);
|
712
|
+
|
713
|
+
/*
|
714
|
+
* We can only accurately return rules meta information for linting results if the
|
715
|
+
* results were created by this instance. Otherwise, the necessary rules data is
|
716
|
+
* not available. So if the config array doesn't already exist, just throw an error
|
717
|
+
* to let the user know we can't do anything here.
|
718
|
+
*/
|
719
|
+
if (!configs) {
|
720
|
+
throw new TypeError("Results object was not created from this ESLint instance.");
|
721
|
+
}
|
722
|
+
|
723
|
+
for (const result of results) {
|
724
|
+
|
725
|
+
/*
|
726
|
+
* Normalize filename for <text>.
|
727
|
+
*/
|
728
|
+
const filePath = result.filePath === "<text>"
|
729
|
+
? "__placeholder__.js" : result.filePath;
|
730
|
+
|
731
|
+
/*
|
732
|
+
* All of the plugin and rule information is contained within the
|
733
|
+
* calculated config for the given file.
|
734
|
+
*/
|
735
|
+
const config = configs.getConfig(filePath);
|
736
|
+
|
737
|
+
for (const { ruleId } of result.messages) {
|
738
|
+
const rule = getRuleFromConfig(ruleId, config);
|
739
|
+
|
740
|
+
// ensure the rule exists exists
|
741
|
+
if (!rule) {
|
742
|
+
throw new TypeError(`Could not find the rule "${ruleId}".`);
|
743
|
+
}
|
744
|
+
|
745
|
+
resultRules.set(ruleId, rule);
|
746
|
+
}
|
747
|
+
}
|
748
|
+
|
749
|
+
return createRulesMeta(resultRules);
|
750
|
+
}
|
751
|
+
|
752
|
+
/**
|
753
|
+
* Executes the current configuration on an array of file and directory names.
|
754
|
+
* @param {string|string[]} patterns An array of file and directory names.
|
755
|
+
* @returns {Promise<LintResult[]>} The results of linting the file patterns given.
|
756
|
+
*/
|
757
|
+
async lintFiles(patterns) {
|
758
|
+
if (!isNonEmptyString(patterns) && !isArrayOfNonEmptyString(patterns)) {
|
759
|
+
throw new Error("'patterns' must be a non-empty string or an array of non-empty strings");
|
760
|
+
}
|
761
|
+
|
762
|
+
const {
|
763
|
+
cacheFilePath,
|
764
|
+
lintResultCache,
|
765
|
+
linter,
|
766
|
+
options: eslintOptions
|
767
|
+
} = privateMembers.get(this);
|
768
|
+
const configs = await calculateConfigArray(this, eslintOptions);
|
769
|
+
const {
|
770
|
+
allowInlineConfig,
|
771
|
+
cache,
|
772
|
+
cwd,
|
773
|
+
fix,
|
774
|
+
fixTypes,
|
775
|
+
reportUnusedDisableDirectives,
|
776
|
+
extensions,
|
777
|
+
globInputPaths
|
778
|
+
} = eslintOptions;
|
779
|
+
const startTime = Date.now();
|
780
|
+
const usedConfigs = [];
|
781
|
+
const fixTypesSet = fixTypes ? new Set(fixTypes) : null;
|
782
|
+
|
783
|
+
// Delete cache file; should this be done here?
|
784
|
+
if (!cache && cacheFilePath) {
|
785
|
+
try {
|
786
|
+
await fs.unlink(cacheFilePath);
|
787
|
+
} catch (error) {
|
788
|
+
const errorCode = error && error.code;
|
789
|
+
|
790
|
+
// Ignore errors when no such file exists or file system is read only (and cache file does not exist)
|
791
|
+
if (errorCode !== "ENOENT" && !(errorCode === "EROFS" && !(await fs.exists(cacheFilePath)))) {
|
792
|
+
throw error;
|
793
|
+
}
|
794
|
+
}
|
795
|
+
}
|
796
|
+
|
797
|
+
const filePaths = await findFiles({
|
798
|
+
patterns: typeof patterns === "string" ? [patterns] : patterns,
|
799
|
+
cwd,
|
800
|
+
extensions,
|
801
|
+
globInputPaths,
|
802
|
+
configs
|
803
|
+
});
|
804
|
+
|
805
|
+
debug(`${filePaths.length} files found in: ${Date.now() - startTime}ms`);
|
806
|
+
|
807
|
+
/*
|
808
|
+
* Because we need to process multiple files, including reading from disk,
|
809
|
+
* it is most efficient to start by reading each file via promises so that
|
810
|
+
* they can be done in parallel. Then, we can lint the returned text. This
|
811
|
+
* ensures we are waiting the minimum amount of time in between lints.
|
812
|
+
*/
|
813
|
+
const results = await Promise.all(
|
814
|
+
|
815
|
+
filePaths.map(({ filePath, ignored }) => {
|
816
|
+
|
817
|
+
/*
|
818
|
+
* If a filename was entered that matches an ignore
|
819
|
+
* pattern, then notify the user.
|
820
|
+
*/
|
821
|
+
if (ignored) {
|
822
|
+
return createIgnoreResult(filePath, cwd);
|
823
|
+
}
|
824
|
+
|
825
|
+
const config = configs.getConfig(filePath);
|
826
|
+
|
827
|
+
/*
|
828
|
+
* Sometimes a file found through a glob pattern will
|
829
|
+
* be ignored. In this case, `config` will be undefined
|
830
|
+
* and we just silently ignore the file.
|
831
|
+
*/
|
832
|
+
if (!config) {
|
833
|
+
return void 0;
|
834
|
+
}
|
835
|
+
|
836
|
+
/*
|
837
|
+
* Store used configs for:
|
838
|
+
* - this method uses to collect used deprecated rules.
|
839
|
+
* - `--fix-type` option uses to get the loaded rule's meta data.
|
840
|
+
*/
|
841
|
+
if (!usedConfigs.includes(config)) {
|
842
|
+
usedConfigs.push(config);
|
843
|
+
}
|
844
|
+
|
845
|
+
// Skip if there is cached result.
|
846
|
+
if (lintResultCache) {
|
847
|
+
const cachedResult =
|
848
|
+
lintResultCache.getCachedLintResults(filePath, config);
|
849
|
+
|
850
|
+
if (cachedResult) {
|
851
|
+
const hadMessages =
|
852
|
+
cachedResult.messages &&
|
853
|
+
cachedResult.messages.length > 0;
|
854
|
+
|
855
|
+
if (hadMessages && fix) {
|
856
|
+
debug(`Reprocessing cached file to allow autofix: ${filePath}`);
|
857
|
+
} else {
|
858
|
+
debug(`Skipping file since it hasn't changed: ${filePath}`);
|
859
|
+
return cachedResult;
|
860
|
+
}
|
861
|
+
}
|
862
|
+
}
|
863
|
+
|
864
|
+
|
865
|
+
// set up fixer for fixtypes if necessary
|
866
|
+
let fixer = fix;
|
867
|
+
|
868
|
+
if (fix && fixTypesSet) {
|
869
|
+
|
870
|
+
// save original value of options.fix in case it's a function
|
871
|
+
const originalFix = (typeof fix === "function")
|
872
|
+
? fix : () => true;
|
873
|
+
|
874
|
+
fixer = message => shouldMessageBeFixed(message, config, fixTypesSet) && originalFix(message);
|
875
|
+
}
|
876
|
+
|
877
|
+
return fs.readFile(filePath, "utf8")
|
878
|
+
.then(text => {
|
879
|
+
|
880
|
+
// do the linting
|
881
|
+
const result = verifyText({
|
882
|
+
text,
|
883
|
+
filePath,
|
884
|
+
configs,
|
885
|
+
cwd,
|
886
|
+
fix: fixer,
|
887
|
+
allowInlineConfig,
|
888
|
+
reportUnusedDisableDirectives,
|
889
|
+
linter
|
890
|
+
});
|
891
|
+
|
892
|
+
/*
|
893
|
+
* Store the lint result in the LintResultCache.
|
894
|
+
* NOTE: The LintResultCache will remove the file source and any
|
895
|
+
* other properties that are difficult to serialize, and will
|
896
|
+
* hydrate those properties back in on future lint runs.
|
897
|
+
*/
|
898
|
+
if (lintResultCache) {
|
899
|
+
lintResultCache.setCachedLintResults(filePath, config, result);
|
900
|
+
}
|
901
|
+
|
902
|
+
return result;
|
903
|
+
});
|
904
|
+
|
905
|
+
})
|
906
|
+
);
|
907
|
+
|
908
|
+
// Persist the cache to disk.
|
909
|
+
if (lintResultCache) {
|
910
|
+
lintResultCache.reconcile();
|
911
|
+
}
|
912
|
+
|
913
|
+
let usedDeprecatedRules;
|
914
|
+
const finalResults = results.filter(result => !!result);
|
915
|
+
|
916
|
+
return processLintReport(this, {
|
917
|
+
results: finalResults,
|
918
|
+
...calculateStatsPerRun(finalResults),
|
919
|
+
|
920
|
+
// Initialize it lazily because CLI and `ESLint` API don't use it.
|
921
|
+
get usedDeprecatedRules() {
|
922
|
+
if (!usedDeprecatedRules) {
|
923
|
+
usedDeprecatedRules = Array.from(
|
924
|
+
iterateRuleDeprecationWarnings(usedConfigs)
|
925
|
+
);
|
926
|
+
}
|
927
|
+
return usedDeprecatedRules;
|
928
|
+
}
|
929
|
+
});
|
930
|
+
}
|
931
|
+
|
932
|
+
/**
|
933
|
+
* Executes the current configuration on text.
|
934
|
+
* @param {string} code A string of JavaScript code to lint.
|
935
|
+
* @param {Object} [options] The options.
|
936
|
+
* @param {string} [options.filePath] The path to the file of the source code.
|
937
|
+
* @param {boolean} [options.warnIgnored] When set to true, warn if given filePath is an ignored path.
|
938
|
+
* @returns {Promise<LintResult[]>} The results of linting the string of code given.
|
939
|
+
*/
|
940
|
+
async lintText(code, options = {}) {
|
941
|
+
|
942
|
+
// Parameter validation
|
943
|
+
|
944
|
+
if (typeof code !== "string") {
|
945
|
+
throw new Error("'code' must be a string");
|
946
|
+
}
|
947
|
+
|
948
|
+
if (typeof options !== "object") {
|
949
|
+
throw new Error("'options' must be an object, null, or undefined");
|
950
|
+
}
|
951
|
+
|
952
|
+
// Options validation
|
953
|
+
|
954
|
+
const {
|
955
|
+
filePath,
|
956
|
+
warnIgnored = false,
|
957
|
+
...unknownOptions
|
958
|
+
} = options || {};
|
959
|
+
|
960
|
+
const unknownOptionKeys = Object.keys(unknownOptions);
|
961
|
+
|
962
|
+
if (unknownOptionKeys.length > 0) {
|
963
|
+
throw new Error(`'options' must not include the unknown option(s): ${unknownOptionKeys.join(", ")}`);
|
964
|
+
}
|
965
|
+
|
966
|
+
if (filePath !== void 0 && !isNonEmptyString(filePath)) {
|
967
|
+
throw new Error("'options.filePath' must be a non-empty string or undefined");
|
968
|
+
}
|
969
|
+
|
970
|
+
if (typeof warnIgnored !== "boolean") {
|
971
|
+
throw new Error("'options.warnIgnored' must be a boolean or undefined");
|
972
|
+
}
|
973
|
+
|
974
|
+
// Now we can get down to linting
|
975
|
+
|
976
|
+
const {
|
977
|
+
linter,
|
978
|
+
options: eslintOptions
|
979
|
+
} = privateMembers.get(this);
|
980
|
+
const configs = await calculateConfigArray(this, eslintOptions);
|
981
|
+
const {
|
982
|
+
allowInlineConfig,
|
983
|
+
cwd,
|
984
|
+
fix,
|
985
|
+
reportUnusedDisableDirectives
|
986
|
+
} = eslintOptions;
|
987
|
+
const results = [];
|
988
|
+
const startTime = Date.now();
|
989
|
+
const resolvedFilename = path.resolve(cwd, filePath || "__placeholder__.js");
|
990
|
+
let config;
|
991
|
+
|
992
|
+
// Clear the last used config arrays.
|
993
|
+
if (resolvedFilename && await this.isPathIgnored(resolvedFilename)) {
|
994
|
+
if (warnIgnored) {
|
995
|
+
results.push(createIgnoreResult(resolvedFilename, cwd));
|
996
|
+
}
|
997
|
+
} else {
|
998
|
+
|
999
|
+
// TODO: Needed?
|
1000
|
+
config = configs.getConfig(resolvedFilename);
|
1001
|
+
|
1002
|
+
// Do lint.
|
1003
|
+
results.push(verifyText({
|
1004
|
+
text: code,
|
1005
|
+
filePath: resolvedFilename.endsWith("__placeholder__.js") ? "<text>" : resolvedFilename,
|
1006
|
+
configs,
|
1007
|
+
cwd,
|
1008
|
+
fix,
|
1009
|
+
allowInlineConfig,
|
1010
|
+
reportUnusedDisableDirectives,
|
1011
|
+
linter
|
1012
|
+
}));
|
1013
|
+
}
|
1014
|
+
|
1015
|
+
debug(`Linting complete in: ${Date.now() - startTime}ms`);
|
1016
|
+
let usedDeprecatedRules;
|
1017
|
+
|
1018
|
+
return processLintReport(this, {
|
1019
|
+
results,
|
1020
|
+
...calculateStatsPerRun(results),
|
1021
|
+
|
1022
|
+
// Initialize it lazily because CLI and `ESLint` API don't use it.
|
1023
|
+
get usedDeprecatedRules() {
|
1024
|
+
if (!usedDeprecatedRules) {
|
1025
|
+
usedDeprecatedRules = Array.from(
|
1026
|
+
iterateRuleDeprecationWarnings(config)
|
1027
|
+
);
|
1028
|
+
}
|
1029
|
+
return usedDeprecatedRules;
|
1030
|
+
}
|
1031
|
+
});
|
1032
|
+
|
1033
|
+
}
|
1034
|
+
|
1035
|
+
/**
|
1036
|
+
* Returns the formatter representing the given formatter name.
|
1037
|
+
* @param {string} [name] The name of the formatter to load.
|
1038
|
+
* The following values are allowed:
|
1039
|
+
* - `undefined` ... Load `stylish` builtin formatter.
|
1040
|
+
* - A builtin formatter name ... Load the builtin formatter.
|
1041
|
+
* - A thirdparty formatter name:
|
1042
|
+
* - `foo` → `eslint-formatter-foo`
|
1043
|
+
* - `@foo` → `@foo/eslint-formatter`
|
1044
|
+
* - `@foo/bar` → `@foo/eslint-formatter-bar`
|
1045
|
+
* - A file path ... Load the file.
|
1046
|
+
* @returns {Promise<Formatter>} A promise resolving to the formatter object.
|
1047
|
+
* This promise will be rejected if the given formatter was not found or not
|
1048
|
+
* a function.
|
1049
|
+
*/
|
1050
|
+
async loadFormatter(name = "stylish") {
|
1051
|
+
if (typeof name !== "string") {
|
1052
|
+
throw new Error("'name' must be a string");
|
1053
|
+
}
|
1054
|
+
|
1055
|
+
// replace \ with / for Windows compatibility
|
1056
|
+
const normalizedFormatName = name.replace(/\\/gu, "/");
|
1057
|
+
const namespace = naming.getNamespaceFromTerm(normalizedFormatName);
|
1058
|
+
|
1059
|
+
// grab our options
|
1060
|
+
const { cwd } = privateMembers.get(this).options;
|
1061
|
+
|
1062
|
+
|
1063
|
+
let formatterPath;
|
1064
|
+
|
1065
|
+
// if there's a slash, then it's a file (TODO: this check seems dubious for scoped npm packages)
|
1066
|
+
if (!namespace && normalizedFormatName.includes("/")) {
|
1067
|
+
formatterPath = path.resolve(cwd, normalizedFormatName);
|
1068
|
+
} else {
|
1069
|
+
try {
|
1070
|
+
const npmFormat = naming.normalizePackageName(normalizedFormatName, "eslint-formatter");
|
1071
|
+
|
1072
|
+
// TODO: This is pretty dirty...would be nice to clean up at some point.
|
1073
|
+
formatterPath = ModuleResolver.resolve(npmFormat, path.join(cwd, "__placeholder__.js"));
|
1074
|
+
} catch {
|
1075
|
+
formatterPath = path.resolve(__dirname, "../", "cli-engine", "formatters", `${normalizedFormatName}.js`);
|
1076
|
+
}
|
1077
|
+
}
|
1078
|
+
|
1079
|
+
let formatter;
|
1080
|
+
|
1081
|
+
try {
|
1082
|
+
formatter = (await import(pathToFileURL(formatterPath))).default;
|
1083
|
+
} catch (ex) {
|
1084
|
+
|
1085
|
+
// check for formatters that have been removed
|
1086
|
+
if (removedFormatters.has(name)) {
|
1087
|
+
ex.message = `The ${name} formatter is no longer part of core ESLint. Install it manually with \`npm install -D eslint-formatter-${name}\``;
|
1088
|
+
} else {
|
1089
|
+
ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`;
|
1090
|
+
}
|
1091
|
+
|
1092
|
+
throw ex;
|
1093
|
+
}
|
1094
|
+
|
1095
|
+
|
1096
|
+
if (typeof formatter !== "function") {
|
1097
|
+
throw new TypeError(`Formatter must be a function, but got a ${typeof formatter}.`);
|
1098
|
+
}
|
1099
|
+
|
1100
|
+
const eslint = this;
|
1101
|
+
|
1102
|
+
return {
|
1103
|
+
|
1104
|
+
/**
|
1105
|
+
* The main formatter method.
|
1106
|
+
* @param {LintResults[]} results The lint results to format.
|
1107
|
+
* @returns {string} The formatted lint results.
|
1108
|
+
*/
|
1109
|
+
format(results) {
|
1110
|
+
let rulesMeta = null;
|
1111
|
+
|
1112
|
+
results.sort(compareResultsByFilePath);
|
1113
|
+
|
1114
|
+
return formatter(results, {
|
1115
|
+
get rulesMeta() {
|
1116
|
+
if (!rulesMeta) {
|
1117
|
+
rulesMeta = eslint.getRulesMetaForResults(results);
|
1118
|
+
}
|
1119
|
+
|
1120
|
+
return rulesMeta;
|
1121
|
+
}
|
1122
|
+
});
|
1123
|
+
}
|
1124
|
+
};
|
1125
|
+
}
|
1126
|
+
|
1127
|
+
/**
|
1128
|
+
* Returns a configuration object for the given file based on the CLI options.
|
1129
|
+
* This is the same logic used by the ESLint CLI executable to determine
|
1130
|
+
* configuration for each file it processes.
|
1131
|
+
* @param {string} filePath The path of the file to retrieve a config object for.
|
1132
|
+
* @returns {Promise<ConfigData|undefined>} A configuration object for the file
|
1133
|
+
* or `undefined` if there is no configuration data for the object.
|
1134
|
+
*/
|
1135
|
+
async calculateConfigForFile(filePath) {
|
1136
|
+
if (!isNonEmptyString(filePath)) {
|
1137
|
+
throw new Error("'filePath' must be a non-empty string");
|
1138
|
+
}
|
1139
|
+
const options = privateMembers.get(this).options;
|
1140
|
+
const absolutePath = path.resolve(options.cwd, filePath);
|
1141
|
+
const configs = await calculateConfigArray(this, options);
|
1142
|
+
|
1143
|
+
return configs.getConfig(absolutePath);
|
1144
|
+
}
|
1145
|
+
|
1146
|
+
/**
|
1147
|
+
* Checks if a given path is ignored by ESLint.
|
1148
|
+
* @param {string} filePath The path of the file to check.
|
1149
|
+
* @returns {Promise<boolean>} Whether or not the given path is ignored.
|
1150
|
+
*/
|
1151
|
+
async isPathIgnored(filePath) {
|
1152
|
+
const config = await this.calculateConfigForFile(filePath);
|
1153
|
+
|
1154
|
+
return config === void 0;
|
1155
|
+
}
|
1156
|
+
}
|
1157
|
+
|
1158
|
+
//------------------------------------------------------------------------------
|
1159
|
+
// Public Interface
|
1160
|
+
//------------------------------------------------------------------------------
|
1161
|
+
|
1162
|
+
module.exports = {
|
1163
|
+
FlatESLint
|
1164
|
+
};
|