eslint 8.57.0 → 9.2.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.
Files changed (156) hide show
  1. package/README.md +31 -28
  2. package/bin/eslint.js +4 -3
  3. package/conf/ecma-version.js +16 -0
  4. package/conf/globals.js +1 -0
  5. package/conf/rule-type-list.json +3 -1
  6. package/lib/api.js +7 -11
  7. package/lib/cli-engine/cli-engine.js +14 -3
  8. package/lib/cli-engine/formatters/formatters-meta.json +1 -29
  9. package/lib/cli-engine/lint-result-cache.js +2 -2
  10. package/lib/cli.js +115 -36
  11. package/lib/config/default-config.js +3 -0
  12. package/lib/config/flat-config-array.js +110 -24
  13. package/lib/config/flat-config-helpers.js +41 -20
  14. package/lib/config/flat-config-schema.js +1 -7
  15. package/lib/config/rule-validator.js +42 -6
  16. package/lib/eslint/eslint-helpers.js +116 -58
  17. package/lib/eslint/eslint.js +892 -377
  18. package/lib/eslint/index.js +2 -2
  19. package/lib/eslint/legacy-eslint.js +728 -0
  20. package/lib/linter/apply-disable-directives.js +59 -31
  21. package/lib/linter/code-path-analysis/code-path-analyzer.js +0 -1
  22. package/lib/linter/code-path-analysis/code-path.js +32 -30
  23. package/lib/linter/code-path-analysis/fork-context.js +1 -1
  24. package/lib/linter/config-comment-parser.js +8 -11
  25. package/lib/linter/index.js +1 -3
  26. package/lib/linter/interpolate.js +24 -2
  27. package/lib/linter/linter.js +428 -207
  28. package/lib/linter/report-translator.js +3 -3
  29. package/lib/linter/rules.js +6 -15
  30. package/lib/linter/source-code-fixer.js +1 -1
  31. package/lib/linter/timing.js +16 -8
  32. package/lib/options.js +35 -3
  33. package/lib/rule-tester/index.js +3 -1
  34. package/lib/rule-tester/rule-tester.js +424 -347
  35. package/lib/rules/array-bracket-newline.js +1 -1
  36. package/lib/rules/array-bracket-spacing.js +1 -1
  37. package/lib/rules/block-scoped-var.js +1 -1
  38. package/lib/rules/callback-return.js +2 -2
  39. package/lib/rules/camelcase.js +3 -5
  40. package/lib/rules/capitalized-comments.js +10 -7
  41. package/lib/rules/comma-dangle.js +1 -1
  42. package/lib/rules/comma-style.js +2 -2
  43. package/lib/rules/complexity.js +14 -1
  44. package/lib/rules/constructor-super.js +99 -100
  45. package/lib/rules/default-case.js +1 -1
  46. package/lib/rules/eol-last.js +2 -2
  47. package/lib/rules/function-paren-newline.js +2 -2
  48. package/lib/rules/indent-legacy.js +5 -5
  49. package/lib/rules/indent.js +5 -5
  50. package/lib/rules/index.js +1 -2
  51. package/lib/rules/key-spacing.js +2 -2
  52. package/lib/rules/line-comment-position.js +1 -1
  53. package/lib/rules/lines-around-directive.js +2 -2
  54. package/lib/rules/max-depth.js +1 -1
  55. package/lib/rules/max-len.js +3 -3
  56. package/lib/rules/max-lines.js +3 -3
  57. package/lib/rules/max-nested-callbacks.js +1 -1
  58. package/lib/rules/max-params.js +1 -1
  59. package/lib/rules/max-statements.js +1 -1
  60. package/lib/rules/multiline-comment-style.js +7 -7
  61. package/lib/rules/new-cap.js +1 -1
  62. package/lib/rules/newline-after-var.js +1 -1
  63. package/lib/rules/newline-before-return.js +1 -1
  64. package/lib/rules/no-case-declarations.js +13 -1
  65. package/lib/rules/no-constant-binary-expression.js +7 -8
  66. package/lib/rules/no-constant-condition.js +18 -7
  67. package/lib/rules/no-constructor-return.js +2 -2
  68. package/lib/rules/no-dupe-class-members.js +2 -2
  69. package/lib/rules/no-else-return.js +1 -1
  70. package/lib/rules/no-empty-function.js +2 -2
  71. package/lib/rules/no-empty-static-block.js +1 -1
  72. package/lib/rules/no-extend-native.js +1 -2
  73. package/lib/rules/no-extra-semi.js +1 -1
  74. package/lib/rules/no-fallthrough.js +41 -16
  75. package/lib/rules/no-implicit-coercion.js +66 -24
  76. package/lib/rules/no-inner-declarations.js +23 -2
  77. package/lib/rules/no-invalid-regexp.js +1 -1
  78. package/lib/rules/no-invalid-this.js +1 -1
  79. package/lib/rules/no-lone-blocks.js +3 -3
  80. package/lib/rules/no-loss-of-precision.js +1 -1
  81. package/lib/rules/no-misleading-character-class.js +225 -69
  82. package/lib/rules/no-mixed-spaces-and-tabs.js +1 -1
  83. package/lib/rules/no-multiple-empty-lines.js +1 -1
  84. package/lib/rules/no-new-native-nonconstructor.js +1 -1
  85. package/lib/rules/no-new-symbol.js +8 -1
  86. package/lib/rules/no-restricted-globals.js +1 -1
  87. package/lib/rules/no-restricted-imports.js +186 -40
  88. package/lib/rules/no-restricted-modules.js +2 -2
  89. package/lib/rules/no-return-await.js +1 -1
  90. package/lib/rules/no-sequences.js +1 -0
  91. package/lib/rules/no-this-before-super.js +45 -13
  92. package/lib/rules/no-trailing-spaces.js +2 -3
  93. package/lib/rules/no-unneeded-ternary.js +1 -1
  94. package/lib/rules/no-unsafe-optional-chaining.js +1 -1
  95. package/lib/rules/no-unused-private-class-members.js +1 -1
  96. package/lib/rules/no-unused-vars.js +197 -36
  97. package/lib/rules/no-useless-assignment.js +566 -0
  98. package/lib/rules/no-useless-backreference.js +1 -1
  99. package/lib/rules/no-useless-computed-key.js +2 -2
  100. package/lib/rules/no-useless-return.js +7 -2
  101. package/lib/rules/object-curly-spacing.js +3 -3
  102. package/lib/rules/object-property-newline.js +1 -1
  103. package/lib/rules/one-var.js +5 -5
  104. package/lib/rules/padded-blocks.js +7 -7
  105. package/lib/rules/prefer-arrow-callback.js +3 -3
  106. package/lib/rules/prefer-reflect.js +1 -1
  107. package/lib/rules/prefer-regex-literals.js +1 -1
  108. package/lib/rules/prefer-template.js +1 -1
  109. package/lib/rules/radix.js +2 -2
  110. package/lib/rules/semi-style.js +1 -1
  111. package/lib/rules/sort-imports.js +1 -1
  112. package/lib/rules/sort-keys.js +1 -1
  113. package/lib/rules/sort-vars.js +1 -1
  114. package/lib/rules/space-unary-ops.js +1 -1
  115. package/lib/rules/strict.js +1 -1
  116. package/lib/rules/use-isnan.js +101 -7
  117. package/lib/rules/utils/ast-utils.js +16 -7
  118. package/lib/rules/utils/char-source.js +240 -0
  119. package/lib/rules/utils/lazy-loading-rule-map.js +1 -1
  120. package/lib/rules/utils/unicode/index.js +9 -4
  121. package/lib/rules/yield-star-spacing.js +1 -1
  122. package/lib/shared/runtime-info.js +1 -0
  123. package/lib/shared/serialization.js +55 -0
  124. package/lib/shared/stats.js +30 -0
  125. package/lib/shared/string-utils.js +9 -11
  126. package/lib/shared/types.js +35 -1
  127. package/lib/source-code/index.js +3 -1
  128. package/lib/source-code/source-code.js +299 -85
  129. package/lib/source-code/token-store/backward-token-cursor.js +3 -3
  130. package/lib/source-code/token-store/cursors.js +4 -2
  131. package/lib/source-code/token-store/forward-token-comment-cursor.js +3 -3
  132. package/lib/source-code/token-store/forward-token-cursor.js +3 -3
  133. package/lib/source-code/token-store/index.js +2 -2
  134. package/lib/unsupported-api.js +3 -5
  135. package/messages/no-config-found.js +1 -1
  136. package/messages/plugin-conflict.js +1 -1
  137. package/messages/plugin-invalid.js +1 -1
  138. package/messages/plugin-missing.js +1 -1
  139. package/package.json +32 -29
  140. package/conf/config-schema.js +0 -93
  141. package/lib/cli-engine/formatters/checkstyle.js +0 -60
  142. package/lib/cli-engine/formatters/compact.js +0 -60
  143. package/lib/cli-engine/formatters/jslint-xml.js +0 -41
  144. package/lib/cli-engine/formatters/junit.js +0 -82
  145. package/lib/cli-engine/formatters/tap.js +0 -95
  146. package/lib/cli-engine/formatters/unix.js +0 -58
  147. package/lib/cli-engine/formatters/visualstudio.js +0 -63
  148. package/lib/cli-engine/xml-escape.js +0 -34
  149. package/lib/eslint/flat-eslint.js +0 -1155
  150. package/lib/rule-tester/flat-rule-tester.js +0 -1131
  151. package/lib/rules/require-jsdoc.js +0 -122
  152. package/lib/rules/utils/patterns/letters.js +0 -36
  153. package/lib/rules/valid-jsdoc.js +0 -516
  154. package/lib/shared/config-validator.js +0 -347
  155. package/lib/shared/deprecation-warnings.js +0 -58
  156. package/lib/shared/relative-module-resolver.js +0 -50
@@ -1,7 +1,6 @@
1
1
  /**
2
- * @fileoverview Main API Class
3
- * @author Kai Cataldo
4
- * @author Toru Nagashima
2
+ * @fileoverview Main class using flat config
3
+ * @author Nicholas C. Zakas
5
4
  */
6
5
 
7
6
  "use strict";
@@ -10,39 +9,61 @@
10
9
  // Requirements
11
10
  //------------------------------------------------------------------------------
12
11
 
12
+ // Note: Node.js 12 does not support fs/promises.
13
+ const fs = require("fs").promises;
14
+ const { existsSync } = require("fs");
13
15
  const path = require("path");
14
- const fs = require("fs");
15
- const { promisify } = require("util");
16
- const { CLIEngine, getCLIEngineInternalSlots } = require("../cli-engine/cli-engine");
17
- const BuiltinRules = require("../rules");
16
+ const findUp = require("find-up");
17
+ const { version } = require("../../package.json");
18
+ const { Linter } = require("../linter");
19
+ const { getRuleFromConfig } = require("../config/flat-config-helpers");
18
20
  const {
19
21
  Legacy: {
20
22
  ConfigOps: {
21
23
  getRuleSeverity
22
- }
24
+ },
25
+ ModuleResolver,
26
+ naming
23
27
  }
24
28
  } = require("@eslint/eslintrc");
25
- const { version } = require("../../package.json");
29
+
30
+ const {
31
+ findFiles,
32
+ getCacheFile,
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
+ const LintResultCache = require("../cli-engine/lint-result-cache");
45
+ const { Retrier } = require("@humanwhocodes/retry");
46
+
47
+ /*
48
+ * This is necessary to allow overwriting writeFile for testing purposes.
49
+ * We can just use fs/promises once we drop Node.js 12 support.
50
+ */
26
51
 
27
52
  //------------------------------------------------------------------------------
28
53
  // Typedefs
29
54
  //------------------------------------------------------------------------------
30
55
 
31
- /** @typedef {import("../cli-engine/cli-engine").LintReport} CLIEngineLintReport */
32
- /** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */
56
+ // For VSCode IntelliSense
33
57
  /** @typedef {import("../shared/types").ConfigData} ConfigData */
58
+ /** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */
34
59
  /** @typedef {import("../shared/types").LintMessage} LintMessage */
35
- /** @typedef {import("../shared/types").SuppressedLintMessage} SuppressedLintMessage */
36
- /** @typedef {import("../shared/types").Plugin} Plugin */
37
- /** @typedef {import("../shared/types").Rule} Rule */
38
60
  /** @typedef {import("../shared/types").LintResult} LintResult */
61
+ /** @typedef {import("../shared/types").ParserOptions} ParserOptions */
62
+ /** @typedef {import("../shared/types").Plugin} Plugin */
39
63
  /** @typedef {import("../shared/types").ResultsMeta} ResultsMeta */
40
-
41
- /**
42
- * The main formatter object.
43
- * @typedef LoadedFormatter
44
- * @property {(results: LintResult[], resultsMeta: ResultsMeta) => string | Promise<string>} format format function.
45
- */
64
+ /** @typedef {import("../shared/types").RuleConf} RuleConf */
65
+ /** @typedef {import("../shared/types").Rule} Rule */
66
+ /** @typedef {ReturnType<ConfigArray.extractConfig>} ExtractedConfig */
46
67
 
47
68
  /**
48
69
  * The options with which to configure the ESLint instance.
@@ -54,270 +75,80 @@ const { version } = require("../../package.json");
54
75
  * @property {"metadata" | "content"} [cacheStrategy] The strategy used to detect changed files.
55
76
  * @property {string} [cwd] The value to use for the current working directory.
56
77
  * @property {boolean} [errorOnUnmatchedPattern] If `false` then `ESLint#lintFiles()` doesn't throw even if no target files found. Defaults to `true`.
57
- * @property {string[]} [extensions] An array of file extensions to check.
58
78
  * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean.
59
79
  * @property {string[]} [fixTypes] Array of rule types to apply fixes for.
60
80
  * @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.
61
- * @property {boolean} [ignore] False disables use of .eslintignore.
62
- * @property {string} [ignorePath] The ignore file to use instead of .eslintignore.
81
+ * @property {boolean} [ignore] False disables all ignore patterns except for the default ones.
82
+ * @property {string[]} [ignorePatterns] Ignore file patterns to use in addition to config ignores. These patterns are relative to `cwd`.
63
83
  * @property {ConfigData} [overrideConfig] Override config object, overrides all configs used with this instance
64
- * @property {string} [overrideConfigFile] The configuration file to use.
65
- * @property {Record<string,Plugin>|null} [plugins] Preloaded plugins. This is a map-like object, keys are plugin IDs and each value is implementation.
66
- * @property {"error" | "warn" | "off"} [reportUnusedDisableDirectives] the severity to report unused eslint-disable directives.
67
- * @property {string} [resolvePluginsRelativeTo] The folder where plugins should be resolved from, defaulting to the CWD.
68
- * @property {string[]} [rulePaths] An array of directories to load custom rules from.
69
- * @property {boolean} [useEslintrc] False disables looking for .eslintrc.* files.
70
- */
71
-
72
- /**
73
- * A rules metadata object.
74
- * @typedef {Object} RulesMeta
75
- * @property {string} id The plugin ID.
76
- * @property {Object} definition The plugin definition.
77
- */
78
-
79
- /**
80
- * Private members for the `ESLint` instance.
81
- * @typedef {Object} ESLintPrivateMembers
82
- * @property {CLIEngine} cliEngine The wrapped CLIEngine instance.
83
- * @property {ESLintOptions} options The options used to instantiate the ESLint instance.
84
+ * @property {boolean|string} [overrideConfigFile] Searches for default config file when falsy;
85
+ * doesn't do any config file lookup when `true`; considered to be a config filename
86
+ * when a string.
87
+ * @property {Record<string,Plugin>} [plugins] An array of plugin implementations.
88
+ * @property {boolean} [stats] True enables added statistics on lint results.
89
+ * @property {boolean} warnIgnored Show warnings when the file list includes ignored files
90
+ * @property {boolean} [passOnNoPatterns=false] When set to true, missing patterns cause
91
+ * the linting operation to short circuit and not report any failures.
84
92
  */
85
93
 
86
94
  //------------------------------------------------------------------------------
87
95
  // Helpers
88
96
  //------------------------------------------------------------------------------
89
97
 
90
- const writeFile = promisify(fs.writeFile);
91
-
92
- /**
93
- * The map with which to store private class members.
94
- * @type {WeakMap<ESLint, ESLintPrivateMembers>}
95
- */
96
- const privateMembersMap = new WeakMap();
97
-
98
- /**
99
- * Check if a given value is a non-empty string or not.
100
- * @param {any} x The value to check.
101
- * @returns {boolean} `true` if `x` is a non-empty string.
102
- */
103
- function isNonEmptyString(x) {
104
- return typeof x === "string" && x.trim() !== "";
105
- }
106
-
107
- /**
108
- * Check if a given value is an array of non-empty strings or not.
109
- * @param {any} x The value to check.
110
- * @returns {boolean} `true` if `x` is an array of non-empty strings.
111
- */
112
- function isArrayOfNonEmptyString(x) {
113
- return Array.isArray(x) && x.every(isNonEmptyString);
114
- }
115
-
116
- /**
117
- * Check if a given value is a valid fix type or not.
118
- * @param {any} x The value to check.
119
- * @returns {boolean} `true` if `x` is valid fix type.
120
- */
121
- function isFixType(x) {
122
- return x === "directive" || x === "problem" || x === "suggestion" || x === "layout";
123
- }
124
-
125
- /**
126
- * Check if a given value is an array of fix types or not.
127
- * @param {any} x The value to check.
128
- * @returns {boolean} `true` if `x` is an array of fix types.
129
- */
130
- function isFixTypeArray(x) {
131
- return Array.isArray(x) && x.every(isFixType);
132
- }
133
-
134
- /**
135
- * The error for invalid options.
136
- */
137
- class ESLintInvalidOptionsError extends Error {
138
- constructor(messages) {
139
- super(`Invalid Options:\n- ${messages.join("\n- ")}`);
140
- this.code = "ESLINT_INVALID_OPTIONS";
141
- Error.captureStackTrace(this, ESLintInvalidOptionsError);
142
- }
143
- }
98
+ const FLAT_CONFIG_FILENAMES = [
99
+ "eslint.config.js",
100
+ "eslint.config.mjs",
101
+ "eslint.config.cjs"
102
+ ];
103
+ const debug = require("debug")("eslint:eslint");
104
+ const privateMembers = new WeakMap();
105
+ const importedConfigFileModificationTime = new Map();
106
+ const removedFormatters = new Set([
107
+ "checkstyle",
108
+ "codeframe",
109
+ "compact",
110
+ "jslint-xml",
111
+ "junit",
112
+ "table",
113
+ "tap",
114
+ "unix",
115
+ "visualstudio"
116
+ ]);
144
117
 
145
118
  /**
146
- * Validates and normalizes options for the wrapped CLIEngine instance.
147
- * @param {ESLintOptions} options The options to process.
148
- * @throws {ESLintInvalidOptionsError} If of any of a variety of type errors.
149
- * @returns {ESLintOptions} The normalized options.
119
+ * It will calculate the error and warning count for collection of messages per file
120
+ * @param {LintMessage[]} messages Collection of messages
121
+ * @returns {Object} Contains the stats
122
+ * @private
150
123
  */
151
- function processOptions({
152
- allowInlineConfig = true, // ← we cannot use `overrideConfig.noInlineConfig` instead because `allowInlineConfig` has side-effect that suppress warnings that show inline configs are ignored.
153
- baseConfig = null,
154
- cache = false,
155
- cacheLocation = ".eslintcache",
156
- cacheStrategy = "metadata",
157
- cwd = process.cwd(),
158
- errorOnUnmatchedPattern = true,
159
- extensions = null, // ← should be null by default because if it's an array then it suppresses RFC20 feature.
160
- fix = false,
161
- fixTypes = null, // ← should be null by default because if it's an array then it suppresses rules that don't have the `meta.type` property.
162
- globInputPaths = true,
163
- ignore = true,
164
- ignorePath = null, // ← should be null by default because if it's a string then it may throw ENOENT.
165
- overrideConfig = null,
166
- overrideConfigFile = null,
167
- plugins = {},
168
- reportUnusedDisableDirectives = null, // ← should be null by default because if it's a string then it overrides the 'reportUnusedDisableDirectives' setting in config files. And we cannot use `overrideConfig.reportUnusedDisableDirectives` instead because we cannot configure the `error` severity with that.
169
- resolvePluginsRelativeTo = null, // ← should be null by default because if it's a string then it suppresses RFC47 feature.
170
- rulePaths = [],
171
- useEslintrc = true,
172
- ...unknownOptions
173
- }) {
174
- const errors = [];
175
- const unknownOptionKeys = Object.keys(unknownOptions);
176
-
177
- if (unknownOptionKeys.length >= 1) {
178
- errors.push(`Unknown options: ${unknownOptionKeys.join(", ")}`);
179
- if (unknownOptionKeys.includes("cacheFile")) {
180
- errors.push("'cacheFile' has been removed. Please use the 'cacheLocation' option instead.");
181
- }
182
- if (unknownOptionKeys.includes("configFile")) {
183
- errors.push("'configFile' has been removed. Please use the 'overrideConfigFile' option instead.");
184
- }
185
- if (unknownOptionKeys.includes("envs")) {
186
- errors.push("'envs' has been removed. Please use the 'overrideConfig.env' option instead.");
187
- }
188
- if (unknownOptionKeys.includes("globals")) {
189
- errors.push("'globals' has been removed. Please use the 'overrideConfig.globals' option instead.");
190
- }
191
- if (unknownOptionKeys.includes("ignorePattern")) {
192
- errors.push("'ignorePattern' has been removed. Please use the 'overrideConfig.ignorePatterns' option instead.");
193
- }
194
- if (unknownOptionKeys.includes("parser")) {
195
- errors.push("'parser' has been removed. Please use the 'overrideConfig.parser' option instead.");
196
- }
197
- if (unknownOptionKeys.includes("parserOptions")) {
198
- errors.push("'parserOptions' has been removed. Please use the 'overrideConfig.parserOptions' option instead.");
199
- }
200
- if (unknownOptionKeys.includes("rules")) {
201
- errors.push("'rules' has been removed. Please use the 'overrideConfig.rules' option instead.");
202
- }
203
- }
204
- if (typeof allowInlineConfig !== "boolean") {
205
- errors.push("'allowInlineConfig' must be a boolean.");
206
- }
207
- if (typeof baseConfig !== "object") {
208
- errors.push("'baseConfig' must be an object or null.");
209
- }
210
- if (typeof cache !== "boolean") {
211
- errors.push("'cache' must be a boolean.");
212
- }
213
- if (!isNonEmptyString(cacheLocation)) {
214
- errors.push("'cacheLocation' must be a non-empty string.");
215
- }
216
- if (
217
- cacheStrategy !== "metadata" &&
218
- cacheStrategy !== "content"
219
- ) {
220
- errors.push("'cacheStrategy' must be any of \"metadata\", \"content\".");
221
- }
222
- if (!isNonEmptyString(cwd) || !path.isAbsolute(cwd)) {
223
- errors.push("'cwd' must be an absolute path.");
224
- }
225
- if (typeof errorOnUnmatchedPattern !== "boolean") {
226
- errors.push("'errorOnUnmatchedPattern' must be a boolean.");
227
- }
228
- if (!isArrayOfNonEmptyString(extensions) && extensions !== null) {
229
- errors.push("'extensions' must be an array of non-empty strings or null.");
230
- }
231
- if (typeof fix !== "boolean" && typeof fix !== "function") {
232
- errors.push("'fix' must be a boolean or a function.");
233
- }
234
- if (fixTypes !== null && !isFixTypeArray(fixTypes)) {
235
- errors.push("'fixTypes' must be an array of any of \"directive\", \"problem\", \"suggestion\", and \"layout\".");
236
- }
237
- if (typeof globInputPaths !== "boolean") {
238
- errors.push("'globInputPaths' must be a boolean.");
239
- }
240
- if (typeof ignore !== "boolean") {
241
- errors.push("'ignore' must be a boolean.");
242
- }
243
- if (!isNonEmptyString(ignorePath) && ignorePath !== null) {
244
- errors.push("'ignorePath' must be a non-empty string or null.");
245
- }
246
- if (typeof overrideConfig !== "object") {
247
- errors.push("'overrideConfig' must be an object or null.");
248
- }
249
- if (!isNonEmptyString(overrideConfigFile) && overrideConfigFile !== null) {
250
- errors.push("'overrideConfigFile' must be a non-empty string or null.");
251
- }
252
- if (typeof plugins !== "object") {
253
- errors.push("'plugins' must be an object or null.");
254
- } else if (plugins !== null && Object.keys(plugins).includes("")) {
255
- errors.push("'plugins' must not include an empty string.");
256
- }
257
- if (Array.isArray(plugins)) {
258
- errors.push("'plugins' doesn't add plugins to configuration to load. Please use the 'overrideConfig.plugins' option instead.");
259
- }
260
- if (
261
- reportUnusedDisableDirectives !== "error" &&
262
- reportUnusedDisableDirectives !== "warn" &&
263
- reportUnusedDisableDirectives !== "off" &&
264
- reportUnusedDisableDirectives !== null
265
- ) {
266
- errors.push("'reportUnusedDisableDirectives' must be any of \"error\", \"warn\", \"off\", and null.");
267
- }
268
- if (
269
- !isNonEmptyString(resolvePluginsRelativeTo) &&
270
- resolvePluginsRelativeTo !== null
271
- ) {
272
- errors.push("'resolvePluginsRelativeTo' must be a non-empty string or null.");
273
- }
274
- if (!isArrayOfNonEmptyString(rulePaths)) {
275
- errors.push("'rulePaths' must be an array of non-empty strings.");
276
- }
277
- if (typeof useEslintrc !== "boolean") {
278
- errors.push("'useEslintrc' must be a boolean.");
279
- }
280
-
281
- if (errors.length > 0) {
282
- throw new ESLintInvalidOptionsError(errors);
283
- }
284
-
285
- return {
286
- allowInlineConfig,
287
- baseConfig,
288
- cache,
289
- cacheLocation,
290
- cacheStrategy,
291
- configFile: overrideConfigFile,
292
- cwd: path.normalize(cwd),
293
- errorOnUnmatchedPattern,
294
- extensions,
295
- fix,
296
- fixTypes,
297
- globInputPaths,
298
- ignore,
299
- ignorePath,
300
- reportUnusedDisableDirectives,
301
- resolvePluginsRelativeTo,
302
- rulePaths,
303
- useEslintrc
124
+ function calculateStatsPerFile(messages) {
125
+ const stat = {
126
+ errorCount: 0,
127
+ fatalErrorCount: 0,
128
+ warningCount: 0,
129
+ fixableErrorCount: 0,
130
+ fixableWarningCount: 0
304
131
  };
305
- }
306
132
 
307
- /**
308
- * Check if a value has one or more properties and that value is not undefined.
309
- * @param {any} obj The value to check.
310
- * @returns {boolean} `true` if `obj` has one or more properties that that value is not undefined.
311
- */
312
- function hasDefinedProperty(obj) {
313
- if (typeof obj === "object" && obj !== null) {
314
- for (const key in obj) {
315
- if (typeof obj[key] !== "undefined") {
316
- return true;
133
+ for (let i = 0; i < messages.length; i++) {
134
+ const message = messages[i];
135
+
136
+ if (message.fatal || message.severity === 2) {
137
+ stat.errorCount++;
138
+ if (message.fatal) {
139
+ stat.fatalErrorCount++;
140
+ }
141
+ if (message.fix) {
142
+ stat.fixableErrorCount++;
143
+ }
144
+ } else {
145
+ stat.warningCount++;
146
+ if (message.fix) {
147
+ stat.fixableWarningCount++;
317
148
  }
318
149
  }
319
150
  }
320
- return false;
151
+ return stat;
321
152
  }
322
153
 
323
154
  /**
@@ -332,62 +163,73 @@ function createRulesMeta(rules) {
332
163
  }, {});
333
164
  }
334
165
 
166
+ /**
167
+ * Return the absolute path of a file named `"__placeholder__.js"` in a given directory.
168
+ * This is used as a replacement for a missing file path.
169
+ * @param {string} cwd An absolute directory path.
170
+ * @returns {string} The absolute path of a file named `"__placeholder__.js"` in the given directory.
171
+ */
172
+ function getPlaceholderPath(cwd) {
173
+ return path.join(cwd, "__placeholder__.js");
174
+ }
175
+
335
176
  /** @type {WeakMap<ExtractedConfig, DeprecatedRuleInfo[]>} */
336
177
  const usedDeprecatedRulesCache = new WeakMap();
337
178
 
338
179
  /**
339
180
  * Create used deprecated rule list.
340
- * @param {CLIEngine} cliEngine The CLIEngine instance.
181
+ * @param {CLIEngine} eslint The CLIEngine instance.
341
182
  * @param {string} maybeFilePath The absolute path to a lint target file or `"<text>"`.
342
183
  * @returns {DeprecatedRuleInfo[]} The used deprecated rule list.
343
184
  */
344
- function getOrFindUsedDeprecatedRules(cliEngine, maybeFilePath) {
185
+ function getOrFindUsedDeprecatedRules(eslint, maybeFilePath) {
345
186
  const {
346
- configArrayFactory,
187
+ configs,
347
188
  options: { cwd }
348
- } = getCLIEngineInternalSlots(cliEngine);
189
+ } = privateMembers.get(eslint);
349
190
  const filePath = path.isAbsolute(maybeFilePath)
350
191
  ? maybeFilePath
351
- : path.join(cwd, "__placeholder__.js");
352
- const configArray = configArrayFactory.getConfigArrayForFile(filePath);
353
- const config = configArray.extractConfig(filePath);
192
+ : getPlaceholderPath(cwd);
193
+ const config = configs.getConfig(filePath);
354
194
 
355
195
  // Most files use the same config, so cache it.
356
- if (!usedDeprecatedRulesCache.has(config)) {
357
- const pluginRules = configArray.pluginRules;
196
+ if (config && !usedDeprecatedRulesCache.has(config)) {
358
197
  const retv = [];
359
198
 
360
- for (const [ruleId, ruleConf] of Object.entries(config.rules)) {
361
- if (getRuleSeverity(ruleConf) === 0) {
362
- continue;
363
- }
364
- const rule = pluginRules.get(ruleId) || BuiltinRules.get(ruleId);
365
- const meta = rule && rule.meta;
366
-
367
- if (meta && meta.deprecated) {
368
- retv.push({ ruleId, replacedBy: meta.replacedBy || [] });
199
+ if (config.rules) {
200
+ for (const [ruleId, ruleConf] of Object.entries(config.rules)) {
201
+ if (getRuleSeverity(ruleConf) === 0) {
202
+ continue;
203
+ }
204
+ const rule = getRuleFromConfig(ruleId, config);
205
+ const meta = rule && rule.meta;
206
+
207
+ if (meta && meta.deprecated) {
208
+ retv.push({ ruleId, replacedBy: meta.replacedBy || [] });
209
+ }
369
210
  }
370
211
  }
371
212
 
213
+
372
214
  usedDeprecatedRulesCache.set(config, Object.freeze(retv));
373
215
  }
374
216
 
375
- return usedDeprecatedRulesCache.get(config);
217
+ return config ? usedDeprecatedRulesCache.get(config) : Object.freeze([]);
376
218
  }
377
219
 
378
220
  /**
379
221
  * Processes the linting results generated by a CLIEngine linting report to
380
222
  * match the ESLint class's API.
381
- * @param {CLIEngine} cliEngine The CLIEngine instance.
223
+ * @param {CLIEngine} eslint The CLIEngine instance.
382
224
  * @param {CLIEngineLintReport} report The CLIEngine linting report to process.
383
225
  * @returns {LintResult[]} The processed linting results.
384
226
  */
385
- function processCLIEngineLintReport(cliEngine, { results }) {
227
+ function processLintReport(eslint, { results }) {
386
228
  const descriptor = {
387
229
  configurable: true,
388
230
  enumerable: true,
389
231
  get() {
390
- return getOrFindUsedDeprecatedRules(cliEngine, this.filePath);
232
+ return getOrFindUsedDeprecatedRules(eslint, this.filePath);
391
233
  }
392
234
  };
393
235
 
@@ -417,44 +259,385 @@ function compareResultsByFilePath(a, b) {
417
259
  }
418
260
 
419
261
  /**
420
- * Main API.
262
+ * Searches from the current working directory up until finding the
263
+ * given flat config filename.
264
+ * @param {string} cwd The current working directory to search from.
265
+ * @returns {Promise<string|undefined>} The filename if found or `undefined` if not.
266
+ */
267
+ function findFlatConfigFile(cwd) {
268
+ return findUp(
269
+ FLAT_CONFIG_FILENAMES,
270
+ { cwd }
271
+ );
272
+ }
273
+
274
+ /**
275
+ * Load the config array from the given filename.
276
+ * @param {string} filePath The filename to load from.
277
+ * @returns {Promise<any>} The config loaded from the config file.
278
+ */
279
+ async function loadFlatConfigFile(filePath) {
280
+ debug(`Loading config from ${filePath}`);
281
+
282
+ const fileURL = pathToFileURL(filePath);
283
+
284
+ debug(`Config file URL is ${fileURL}`);
285
+
286
+ const mtime = (await fs.stat(filePath)).mtime.getTime();
287
+
288
+ /*
289
+ * Append a query with the config file's modification time (`mtime`) in order
290
+ * to import the current version of the config file. Without the query, `import()` would
291
+ * cache the config file module by the pathname only, and then always return
292
+ * the same version (the one that was actual when the module was imported for the first time).
293
+ *
294
+ * This ensures that the config file module is loaded and executed again
295
+ * if it has been changed since the last time it was imported.
296
+ * If it hasn't been changed, `import()` will just return the cached version.
297
+ *
298
+ * Note that we should not overuse queries (e.g., by appending the current time
299
+ * to always reload the config file module) as that could cause memory leaks
300
+ * because entries are never removed from the import cache.
301
+ */
302
+ fileURL.searchParams.append("mtime", mtime);
303
+
304
+ /*
305
+ * With queries, we can bypass the import cache. However, when import-ing a CJS module,
306
+ * Node.js uses the require infrastructure under the hood. That includes the require cache,
307
+ * which caches the config file module by its file path (queries have no effect).
308
+ * Therefore, we also need to clear the require cache before importing the config file module.
309
+ * In order to get the same behavior with ESM and CJS config files, in particular - to reload
310
+ * the config file only if it has been changed, we track file modification times and clear
311
+ * the require cache only if the file has been changed.
312
+ */
313
+ if (importedConfigFileModificationTime.get(filePath) !== mtime) {
314
+ delete require.cache[filePath];
315
+ }
316
+
317
+ const config = (await import(fileURL)).default;
318
+
319
+ importedConfigFileModificationTime.set(filePath, mtime);
320
+
321
+ return config;
322
+ }
323
+
324
+ /**
325
+ * Determines which config file to use. This is determined by seeing if an
326
+ * override config file was passed, and if so, using it; otherwise, as long
327
+ * as override config file is not explicitly set to `false`, it will search
328
+ * upwards from the cwd for a file named `eslint.config.js`.
329
+ * @param {import("./eslint").ESLintOptions} options The ESLint instance options.
330
+ * @returns {{configFilePath:string|undefined,basePath:string,error:Error|null}} Location information for
331
+ * the config file.
332
+ */
333
+ async function locateConfigFileToUse({ configFile, cwd }) {
334
+
335
+ // determine where to load config file from
336
+ let configFilePath;
337
+ let basePath = cwd;
338
+ let error = null;
339
+
340
+ if (typeof configFile === "string") {
341
+ debug(`Override config file path is ${configFile}`);
342
+ configFilePath = path.resolve(cwd, configFile);
343
+ } else if (configFile !== false) {
344
+ debug("Searching for eslint.config.js");
345
+ configFilePath = await findFlatConfigFile(cwd);
346
+
347
+ if (configFilePath) {
348
+ basePath = path.resolve(path.dirname(configFilePath));
349
+ } else {
350
+ error = new Error("Could not find config file.");
351
+ }
352
+
353
+ }
354
+
355
+ return {
356
+ configFilePath,
357
+ basePath,
358
+ error
359
+ };
360
+
361
+ }
362
+
363
+ /**
364
+ * Calculates the config array for this run based on inputs.
365
+ * @param {ESLint} eslint The instance to create the config array for.
366
+ * @param {import("./eslint").ESLintOptions} options The ESLint instance options.
367
+ * @returns {FlatConfigArray} The config array for `eslint``.
368
+ */
369
+ async function calculateConfigArray(eslint, {
370
+ cwd,
371
+ baseConfig,
372
+ overrideConfig,
373
+ configFile,
374
+ ignore: shouldIgnore,
375
+ ignorePatterns
376
+ }) {
377
+
378
+ // check for cached instance
379
+ const slots = privateMembers.get(eslint);
380
+
381
+ if (slots.configs) {
382
+ return slots.configs;
383
+ }
384
+
385
+ const { configFilePath, basePath, error } = await locateConfigFileToUse({ configFile, cwd });
386
+
387
+ // config file is required to calculate config
388
+ if (error) {
389
+ throw error;
390
+ }
391
+
392
+ const configs = new FlatConfigArray(baseConfig || [], { basePath, shouldIgnore });
393
+
394
+ // load config file
395
+ if (configFilePath) {
396
+ const fileConfig = await loadFlatConfigFile(configFilePath);
397
+
398
+ if (Array.isArray(fileConfig)) {
399
+ configs.push(...fileConfig);
400
+ } else {
401
+ configs.push(fileConfig);
402
+ }
403
+ }
404
+
405
+ // add in any configured defaults
406
+ configs.push(...slots.defaultConfigs);
407
+
408
+ // append command line ignore patterns
409
+ if (ignorePatterns && ignorePatterns.length > 0) {
410
+
411
+ let relativeIgnorePatterns;
412
+
413
+ /*
414
+ * If the config file basePath is different than the cwd, then
415
+ * the ignore patterns won't work correctly. Here, we adjust the
416
+ * ignore pattern to include the correct relative path. Patterns
417
+ * passed as `ignorePatterns` are relative to the cwd, whereas
418
+ * the config file basePath can be an ancestor of the cwd.
419
+ */
420
+ if (basePath === cwd) {
421
+ relativeIgnorePatterns = ignorePatterns;
422
+ } else {
423
+
424
+ const relativeIgnorePath = path.relative(basePath, cwd);
425
+
426
+ relativeIgnorePatterns = ignorePatterns.map(pattern => {
427
+ const negated = pattern.startsWith("!");
428
+ const basePattern = negated ? pattern.slice(1) : pattern;
429
+
430
+ return (negated ? "!" : "") +
431
+ path.posix.join(relativeIgnorePath, basePattern);
432
+ });
433
+ }
434
+
435
+ /*
436
+ * Ignore patterns are added to the end of the config array
437
+ * so they can override default ignores.
438
+ */
439
+ configs.push({
440
+ ignores: relativeIgnorePatterns
441
+ });
442
+ }
443
+
444
+ if (overrideConfig) {
445
+ if (Array.isArray(overrideConfig)) {
446
+ configs.push(...overrideConfig);
447
+ } else {
448
+ configs.push(overrideConfig);
449
+ }
450
+ }
451
+
452
+ await configs.normalize();
453
+
454
+ // cache the config array for this instance
455
+ slots.configs = configs;
456
+
457
+ return configs;
458
+ }
459
+
460
+ /**
461
+ * Processes an source code using ESLint.
462
+ * @param {Object} config The config object.
463
+ * @param {string} config.text The source code to verify.
464
+ * @param {string} config.cwd The path to the current working directory.
465
+ * @param {string|undefined} config.filePath The path to the file of `text`. If this is undefined, it uses `<text>`.
466
+ * @param {FlatConfigArray} config.configs The config.
467
+ * @param {boolean} config.fix If `true` then it does fix.
468
+ * @param {boolean} config.allowInlineConfig If `true` then it uses directive comments.
469
+ * @param {Function} config.ruleFilter A predicate function to filter which rules should be run.
470
+ * @param {boolean} config.stats If `true`, then if reports extra statistics with the lint results.
471
+ * @param {Linter} config.linter The linter instance to verify.
472
+ * @returns {LintResult} The result of linting.
473
+ * @private
474
+ */
475
+ function verifyText({
476
+ text,
477
+ cwd,
478
+ filePath: providedFilePath,
479
+ configs,
480
+ fix,
481
+ allowInlineConfig,
482
+ ruleFilter,
483
+ stats,
484
+ linter
485
+ }) {
486
+ const filePath = providedFilePath || "<text>";
487
+
488
+ debug(`Lint ${filePath}`);
489
+
490
+ /*
491
+ * Verify.
492
+ * `config.extractConfig(filePath)` requires an absolute path, but `linter`
493
+ * doesn't know CWD, so it gives `linter` an absolute path always.
494
+ */
495
+ const filePathToVerify = filePath === "<text>" ? getPlaceholderPath(cwd) : filePath;
496
+ const { fixed, messages, output } = linter.verifyAndFix(
497
+ text,
498
+ configs,
499
+ {
500
+ allowInlineConfig,
501
+ filename: filePathToVerify,
502
+ fix,
503
+ ruleFilter,
504
+ stats,
505
+
506
+ /**
507
+ * Check if the linter should adopt a given code block or not.
508
+ * @param {string} blockFilename The virtual filename of a code block.
509
+ * @returns {boolean} `true` if the linter should adopt the code block.
510
+ */
511
+ filterCodeBlock(blockFilename) {
512
+ return configs.isExplicitMatch(blockFilename);
513
+ }
514
+ }
515
+ );
516
+
517
+ // Tweak and return.
518
+ const result = {
519
+ filePath: filePath === "<text>" ? filePath : path.resolve(filePath),
520
+ messages,
521
+ suppressedMessages: linter.getSuppressedMessages(),
522
+ ...calculateStatsPerFile(messages)
523
+ };
524
+
525
+ if (fixed) {
526
+ result.output = output;
527
+ }
528
+
529
+ if (
530
+ result.errorCount + result.warningCount > 0 &&
531
+ typeof result.output === "undefined"
532
+ ) {
533
+ result.source = text;
534
+ }
535
+
536
+ if (stats) {
537
+ result.stats = {
538
+ times: linter.getTimes(),
539
+ fixPasses: linter.getFixPassCount()
540
+ };
541
+ }
542
+
543
+ return result;
544
+ }
545
+
546
+ /**
547
+ * Checks whether a message's rule type should be fixed.
548
+ * @param {LintMessage} message The message to check.
549
+ * @param {FlatConfig} config The config for the file that generated the message.
550
+ * @param {string[]} fixTypes An array of fix types to check.
551
+ * @returns {boolean} Whether the message should be fixed.
552
+ */
553
+ function shouldMessageBeFixed(message, config, fixTypes) {
554
+ if (!message.ruleId) {
555
+ return fixTypes.has("directive");
556
+ }
557
+
558
+ const rule = message.ruleId && getRuleFromConfig(message.ruleId, config);
559
+
560
+ return Boolean(rule && rule.meta && fixTypes.has(rule.meta.type));
561
+ }
562
+
563
+ /**
564
+ * Creates an error to be thrown when an array of results passed to `getRulesMetaForResults` was not created by the current engine.
565
+ * @returns {TypeError} An error object.
566
+ */
567
+ function createExtraneousResultsError() {
568
+ return new TypeError("Results object was not created from this ESLint instance.");
569
+ }
570
+
571
+ //-----------------------------------------------------------------------------
572
+ // Main API
573
+ //-----------------------------------------------------------------------------
574
+
575
+ /**
576
+ * Primary Node.js API for ESLint.
421
577
  */
422
578
  class ESLint {
423
579
 
580
+ /**
581
+ * The type of configuration used by this class.
582
+ * @type {string}
583
+ */
584
+ static configType = "flat";
585
+
424
586
  /**
425
587
  * Creates a new instance of the main ESLint API.
426
588
  * @param {ESLintOptions} options The options for this instance.
427
589
  */
428
590
  constructor(options = {}) {
591
+
592
+ const defaultConfigs = [];
429
593
  const processedOptions = processOptions(options);
430
- const cliEngine = new CLIEngine(processedOptions, { preloadedPlugins: options.plugins });
431
- const {
432
- configArrayFactory,
433
- lastConfigArrays
434
- } = getCLIEngineInternalSlots(cliEngine);
435
- let updated = false;
594
+ const linter = new Linter({
595
+ cwd: processedOptions.cwd,
596
+ configType: "flat"
597
+ });
436
598
 
437
- /*
438
- * Address `overrideConfig` to set override config.
439
- * Operate the `configArrayFactory` internal slot directly because this
440
- * functionality doesn't exist as the public API of CLIEngine.
599
+ const cacheFilePath = getCacheFile(
600
+ processedOptions.cacheLocation,
601
+ processedOptions.cwd
602
+ );
603
+
604
+ const lintResultCache = processedOptions.cache
605
+ ? new LintResultCache(cacheFilePath, processedOptions.cacheStrategy)
606
+ : null;
607
+
608
+ privateMembers.set(this, {
609
+ options: processedOptions,
610
+ linter,
611
+ cacheFilePath,
612
+ lintResultCache,
613
+ defaultConfigs,
614
+ configs: null
615
+ });
616
+
617
+ /**
618
+ * If additional plugins are passed in, add that to the default
619
+ * configs for this instance.
441
620
  */
442
- if (hasDefinedProperty(options.overrideConfig)) {
443
- configArrayFactory.setOverrideConfig(options.overrideConfig);
444
- updated = true;
445
- }
621
+ if (options.plugins) {
622
+
623
+ const plugins = {};
446
624
 
447
- // Update caches.
448
- if (updated) {
449
- configArrayFactory.clearCache();
450
- lastConfigArrays[0] = configArrayFactory.getConfigArrayForFile();
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
+ });
451
632
  }
452
633
 
453
- // Initialize private properties.
454
- privateMembersMap.set(this, {
455
- cliEngine,
456
- options: processedOptions
457
- });
634
+ // Check for the .eslintignore file, and warn if it's present.
635
+ if (existsSync(path.resolve(processedOptions.cwd, ".eslintignore"))) {
636
+ process.emitWarning(
637
+ "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",
638
+ "ESLintIgnoreWarning"
639
+ );
640
+ }
458
641
  }
459
642
 
460
643
  /**
@@ -486,7 +669,7 @@ class ESLint {
486
669
  path.isAbsolute(result.filePath)
487
670
  );
488
671
  })
489
- .map(r => writeFile(r.filePath, r.output))
672
+ .map(r => fs.writeFile(r.filePath, r.output))
490
673
  );
491
674
  }
492
675
 
@@ -496,60 +679,297 @@ class ESLint {
496
679
  * @returns {LintResult[]} The filtered results.
497
680
  */
498
681
  static getErrorResults(results) {
499
- return CLIEngine.getErrorResults(results);
682
+ const filtered = [];
683
+
684
+ results.forEach(result => {
685
+ const filteredMessages = result.messages.filter(isErrorMessage);
686
+ const filteredSuppressedMessages = result.suppressedMessages.filter(isErrorMessage);
687
+
688
+ if (filteredMessages.length > 0) {
689
+ filtered.push({
690
+ ...result,
691
+ messages: filteredMessages,
692
+ suppressedMessages: filteredSuppressedMessages,
693
+ errorCount: filteredMessages.length,
694
+ warningCount: 0,
695
+ fixableErrorCount: result.fixableErrorCount,
696
+ fixableWarningCount: 0
697
+ });
698
+ }
699
+ });
700
+
701
+ return filtered;
500
702
  }
501
703
 
502
704
  /**
503
705
  * Returns meta objects for each rule represented in the lint results.
504
706
  * @param {LintResult[]} results The results to fetch rules meta for.
505
707
  * @returns {Object} A mapping of ruleIds to rule meta objects.
708
+ * @throws {TypeError} When the results object wasn't created from this ESLint instance.
709
+ * @throws {TypeError} When a plugin or rule is missing.
506
710
  */
507
711
  getRulesMetaForResults(results) {
508
712
 
509
- const resultRuleIds = new Set();
713
+ // short-circuit simple case
714
+ if (results.length === 0) {
715
+ return {};
716
+ }
510
717
 
511
- // first gather all ruleIds from all results
718
+ const resultRules = new Map();
719
+ const {
720
+ configs,
721
+ options: { cwd }
722
+ } = privateMembers.get(this);
512
723
 
513
- for (const result of results) {
514
- for (const { ruleId } of result.messages) {
515
- resultRuleIds.add(ruleId);
516
- }
517
- for (const { ruleId } of result.suppressedMessages) {
518
- resultRuleIds.add(ruleId);
519
- }
724
+ /*
725
+ * We can only accurately return rules meta information for linting results if the
726
+ * results were created by this instance. Otherwise, the necessary rules data is
727
+ * not available. So if the config array doesn't already exist, just throw an error
728
+ * to let the user know we can't do anything here.
729
+ */
730
+ if (!configs) {
731
+ throw createExtraneousResultsError();
520
732
  }
521
733
 
522
- // create a map of all rules in the results
523
-
524
- const { cliEngine } = privateMembersMap.get(this);
525
- const rules = cliEngine.getRules();
526
- const resultRules = new Map();
734
+ for (const result of results) {
527
735
 
528
- for (const [ruleId, rule] of rules) {
529
- if (resultRuleIds.has(ruleId)) {
530
- resultRules.set(ruleId, rule);
736
+ /*
737
+ * Normalize filename for <text>.
738
+ */
739
+ const filePath = result.filePath === "<text>"
740
+ ? getPlaceholderPath(cwd) : result.filePath;
741
+ const allMessages = result.messages.concat(result.suppressedMessages);
742
+
743
+ for (const { ruleId } of allMessages) {
744
+ if (!ruleId) {
745
+ continue;
746
+ }
747
+
748
+ /*
749
+ * All of the plugin and rule information is contained within the
750
+ * calculated config for the given file.
751
+ */
752
+ const config = configs.getConfig(filePath);
753
+
754
+ if (!config) {
755
+ throw createExtraneousResultsError();
756
+ }
757
+ const rule = getRuleFromConfig(ruleId, config);
758
+
759
+ // ignore unknown rules
760
+ if (rule) {
761
+ resultRules.set(ruleId, rule);
762
+ }
531
763
  }
532
764
  }
533
765
 
534
766
  return createRulesMeta(resultRules);
535
-
536
767
  }
537
768
 
538
769
  /**
539
770
  * Executes the current configuration on an array of file and directory names.
540
- * @param {string[]} patterns An array of file and directory names.
771
+ * @param {string|string[]} patterns An array of file and directory names.
541
772
  * @returns {Promise<LintResult[]>} The results of linting the file patterns given.
542
773
  */
543
774
  async lintFiles(patterns) {
544
- if (!isNonEmptyString(patterns) && !isArrayOfNonEmptyString(patterns)) {
545
- throw new Error("'patterns' must be a non-empty string or an array of non-empty strings");
775
+
776
+ let normalizedPatterns = patterns;
777
+ const {
778
+ cacheFilePath,
779
+ lintResultCache,
780
+ linter,
781
+ options: eslintOptions
782
+ } = privateMembers.get(this);
783
+
784
+ /*
785
+ * Special cases:
786
+ * 1. `patterns` is an empty string
787
+ * 2. `patterns` is an empty array
788
+ *
789
+ * In both cases, we use the cwd as the directory to lint.
790
+ */
791
+ if (patterns === "" || Array.isArray(patterns) && patterns.length === 0) {
792
+
793
+ /*
794
+ * Special case: If `passOnNoPatterns` is true, then we just exit
795
+ * without doing any work.
796
+ */
797
+ if (eslintOptions.passOnNoPatterns) {
798
+ return [];
799
+ }
800
+
801
+ normalizedPatterns = ["."];
802
+ } else {
803
+
804
+ if (!isNonEmptyString(patterns) && !isArrayOfNonEmptyString(patterns)) {
805
+ throw new Error("'patterns' must be a non-empty string or an array of non-empty strings");
806
+ }
807
+
808
+ if (typeof patterns === "string") {
809
+ normalizedPatterns = [patterns];
810
+ }
811
+ }
812
+
813
+ debug(`Using file patterns: ${normalizedPatterns}`);
814
+
815
+ const configs = await calculateConfigArray(this, eslintOptions);
816
+ const {
817
+ allowInlineConfig,
818
+ cache,
819
+ cwd,
820
+ fix,
821
+ fixTypes,
822
+ ruleFilter,
823
+ stats,
824
+ globInputPaths,
825
+ errorOnUnmatchedPattern,
826
+ warnIgnored
827
+ } = eslintOptions;
828
+ const startTime = Date.now();
829
+ const fixTypesSet = fixTypes ? new Set(fixTypes) : null;
830
+
831
+ // Delete cache file; should this be done here?
832
+ if (!cache && cacheFilePath) {
833
+ debug(`Deleting cache file at ${cacheFilePath}`);
834
+
835
+ try {
836
+ await fs.unlink(cacheFilePath);
837
+ } catch (error) {
838
+ const errorCode = error && error.code;
839
+
840
+ // Ignore errors when no such file exists or file system is read only (and cache file does not exist)
841
+ if (errorCode !== "ENOENT" && !(errorCode === "EROFS" && !existsSync(cacheFilePath))) {
842
+ throw error;
843
+ }
844
+ }
546
845
  }
547
- const { cliEngine } = privateMembersMap.get(this);
548
846
 
549
- return processCLIEngineLintReport(
550
- cliEngine,
551
- cliEngine.executeOnFiles(patterns)
847
+ const filePaths = await findFiles({
848
+ patterns: normalizedPatterns,
849
+ cwd,
850
+ globInputPaths,
851
+ configs,
852
+ errorOnUnmatchedPattern
853
+ });
854
+ const controller = new AbortController();
855
+ const retryCodes = new Set(["ENFILE", "EMFILE"]);
856
+ const retrier = new Retrier(error => retryCodes.has(error.code));
857
+
858
+ debug(`${filePaths.length} files found in: ${Date.now() - startTime}ms`);
859
+
860
+ /*
861
+ * Because we need to process multiple files, including reading from disk,
862
+ * it is most efficient to start by reading each file via promises so that
863
+ * they can be done in parallel. Then, we can lint the returned text. This
864
+ * ensures we are waiting the minimum amount of time in between lints.
865
+ */
866
+ const results = await Promise.all(
867
+
868
+ filePaths.map(({ filePath, ignored }) => {
869
+
870
+ /*
871
+ * If a filename was entered that matches an ignore
872
+ * pattern, then notify the user.
873
+ */
874
+ if (ignored) {
875
+ if (warnIgnored) {
876
+ return createIgnoreResult(filePath, cwd);
877
+ }
878
+
879
+ return void 0;
880
+ }
881
+
882
+ const config = configs.getConfig(filePath);
883
+
884
+ /*
885
+ * Sometimes a file found through a glob pattern will
886
+ * be ignored. In this case, `config` will be undefined
887
+ * and we just silently ignore the file.
888
+ */
889
+ if (!config) {
890
+ return void 0;
891
+ }
892
+
893
+ // Skip if there is cached result.
894
+ if (lintResultCache) {
895
+ const cachedResult =
896
+ lintResultCache.getCachedLintResults(filePath, config);
897
+
898
+ if (cachedResult) {
899
+ const hadMessages =
900
+ cachedResult.messages &&
901
+ cachedResult.messages.length > 0;
902
+
903
+ if (hadMessages && fix) {
904
+ debug(`Reprocessing cached file to allow autofix: ${filePath}`);
905
+ } else {
906
+ debug(`Skipping file since it hasn't changed: ${filePath}`);
907
+ return cachedResult;
908
+ }
909
+ }
910
+ }
911
+
912
+
913
+ // set up fixer for fixTypes if necessary
914
+ let fixer = fix;
915
+
916
+ if (fix && fixTypesSet) {
917
+
918
+ // save original value of options.fix in case it's a function
919
+ const originalFix = (typeof fix === "function")
920
+ ? fix : () => true;
921
+
922
+ fixer = message => shouldMessageBeFixed(message, config, fixTypesSet) && originalFix(message);
923
+ }
924
+
925
+ return retrier.retry(() => fs.readFile(filePath, { encoding: "utf8", signal: controller.signal })
926
+ .then(text => {
927
+
928
+ // fail immediately if an error occurred in another file
929
+ controller.signal.throwIfAborted();
930
+
931
+ // do the linting
932
+ const result = verifyText({
933
+ text,
934
+ filePath,
935
+ configs,
936
+ cwd,
937
+ fix: fixer,
938
+ allowInlineConfig,
939
+ ruleFilter,
940
+ stats,
941
+ linter
942
+ });
943
+
944
+ /*
945
+ * Store the lint result in the LintResultCache.
946
+ * NOTE: The LintResultCache will remove the file source and any
947
+ * other properties that are difficult to serialize, and will
948
+ * hydrate those properties back in on future lint runs.
949
+ */
950
+ if (lintResultCache) {
951
+ lintResultCache.setCachedLintResults(filePath, config, result);
952
+ }
953
+
954
+ return result;
955
+ }))
956
+ .catch(error => {
957
+ controller.abort(error);
958
+ throw error;
959
+ });
960
+ })
552
961
  );
962
+
963
+ // Persist the cache to disk.
964
+ if (lintResultCache) {
965
+ lintResultCache.reconcile();
966
+ }
967
+
968
+ const finalResults = results.filter(result => !!result);
969
+
970
+ return processLintReport(this, {
971
+ results: finalResults
972
+ });
553
973
  }
554
974
 
555
975
  /**
@@ -561,15 +981,22 @@ class ESLint {
561
981
  * @returns {Promise<LintResult[]>} The results of linting the string of code given.
562
982
  */
563
983
  async lintText(code, options = {}) {
984
+
985
+ // Parameter validation
986
+
564
987
  if (typeof code !== "string") {
565
988
  throw new Error("'code' must be a string");
566
989
  }
990
+
567
991
  if (typeof options !== "object") {
568
992
  throw new Error("'options' must be an object, null, or undefined");
569
993
  }
994
+
995
+ // Options validation
996
+
570
997
  const {
571
998
  filePath,
572
- warnIgnored = false,
999
+ warnIgnored,
573
1000
  ...unknownOptions
574
1001
  } = options || {};
575
1002
 
@@ -582,16 +1009,59 @@ class ESLint {
582
1009
  if (filePath !== void 0 && !isNonEmptyString(filePath)) {
583
1010
  throw new Error("'options.filePath' must be a non-empty string or undefined");
584
1011
  }
585
- if (typeof warnIgnored !== "boolean") {
1012
+
1013
+ if (typeof warnIgnored !== "boolean" && typeof warnIgnored !== "undefined") {
586
1014
  throw new Error("'options.warnIgnored' must be a boolean or undefined");
587
1015
  }
588
1016
 
589
- const { cliEngine } = privateMembersMap.get(this);
1017
+ // Now we can get down to linting
1018
+
1019
+ const {
1020
+ linter,
1021
+ options: eslintOptions
1022
+ } = privateMembers.get(this);
1023
+ const configs = await calculateConfigArray(this, eslintOptions);
1024
+ const {
1025
+ allowInlineConfig,
1026
+ cwd,
1027
+ fix,
1028
+ warnIgnored: constructorWarnIgnored,
1029
+ ruleFilter,
1030
+ stats
1031
+ } = eslintOptions;
1032
+ const results = [];
1033
+ const startTime = Date.now();
1034
+ const resolvedFilename = path.resolve(cwd, filePath || "__placeholder__.js");
1035
+
1036
+ // Clear the last used config arrays.
1037
+ if (resolvedFilename && await this.isPathIgnored(resolvedFilename)) {
1038
+ const shouldWarnIgnored = typeof warnIgnored === "boolean" ? warnIgnored : constructorWarnIgnored;
1039
+
1040
+ if (shouldWarnIgnored) {
1041
+ results.push(createIgnoreResult(resolvedFilename, cwd));
1042
+ }
1043
+ } else {
1044
+
1045
+ // Do lint.
1046
+ results.push(verifyText({
1047
+ text: code,
1048
+ filePath: resolvedFilename.endsWith("__placeholder__.js") ? "<text>" : resolvedFilename,
1049
+ configs,
1050
+ cwd,
1051
+ fix,
1052
+ allowInlineConfig,
1053
+ ruleFilter,
1054
+ stats,
1055
+ linter
1056
+ }));
1057
+ }
1058
+
1059
+ debug(`Linting complete in: ${Date.now() - startTime}ms`);
1060
+
1061
+ return processLintReport(this, {
1062
+ results
1063
+ });
590
1064
 
591
- return processCLIEngineLintReport(
592
- cliEngine,
593
- cliEngine.executeOnText(code, filePath, warnIgnored)
594
- );
595
1065
  }
596
1066
 
597
1067
  /**
@@ -605,7 +1075,7 @@ class ESLint {
605
1075
  * - `@foo` → `@foo/eslint-formatter`
606
1076
  * - `@foo/bar` → `@foo/eslint-formatter-bar`
607
1077
  * - A file path ... Load the file.
608
- * @returns {Promise<LoadedFormatter>} A promise resolving to the formatter object.
1078
+ * @returns {Promise<Formatter>} A promise resolving to the formatter object.
609
1079
  * This promise will be rejected if the given formatter was not found or not
610
1080
  * a function.
611
1081
  */
@@ -614,20 +1084,60 @@ class ESLint {
614
1084
  throw new Error("'name' must be a string");
615
1085
  }
616
1086
 
617
- const { cliEngine, options } = privateMembersMap.get(this);
618
- const formatter = cliEngine.getFormatter(name);
1087
+ // replace \ with / for Windows compatibility
1088
+ const normalizedFormatName = name.replace(/\\/gu, "/");
1089
+ const namespace = naming.getNamespaceFromTerm(normalizedFormatName);
1090
+
1091
+ // grab our options
1092
+ const { cwd } = privateMembers.get(this).options;
1093
+
1094
+
1095
+ let formatterPath;
1096
+
1097
+ // if there's a slash, then it's a file (TODO: this check seems dubious for scoped npm packages)
1098
+ if (!namespace && normalizedFormatName.includes("/")) {
1099
+ formatterPath = path.resolve(cwd, normalizedFormatName);
1100
+ } else {
1101
+ try {
1102
+ const npmFormat = naming.normalizePackageName(normalizedFormatName, "eslint-formatter");
1103
+
1104
+ // TODO: This is pretty dirty...would be nice to clean up at some point.
1105
+ formatterPath = ModuleResolver.resolve(npmFormat, getPlaceholderPath(cwd));
1106
+ } catch {
1107
+ formatterPath = path.resolve(__dirname, "../", "cli-engine", "formatters", `${normalizedFormatName}.js`);
1108
+ }
1109
+ }
1110
+
1111
+ let formatter;
1112
+
1113
+ try {
1114
+ formatter = (await import(pathToFileURL(formatterPath))).default;
1115
+ } catch (ex) {
1116
+
1117
+ // check for formatters that have been removed
1118
+ if (removedFormatters.has(name)) {
1119
+ ex.message = `The ${name} formatter is no longer part of core ESLint. Install it manually with \`npm install -D eslint-formatter-${name}\``;
1120
+ } else {
1121
+ ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`;
1122
+ }
1123
+
1124
+ throw ex;
1125
+ }
1126
+
619
1127
 
620
1128
  if (typeof formatter !== "function") {
621
- throw new Error(`Formatter must be a function, but got a ${typeof formatter}.`);
1129
+ throw new TypeError(`Formatter must be a function, but got a ${typeof formatter}.`);
622
1130
  }
623
1131
 
1132
+ const eslint = this;
1133
+
624
1134
  return {
625
1135
 
626
1136
  /**
627
1137
  * The main formatter method.
628
- * @param {LintResult[]} results The lint results to format.
1138
+ * @param {LintResults[]} results The lint results to format.
629
1139
  * @param {ResultsMeta} resultsMeta Warning count and max threshold.
630
- * @returns {string | Promise<string>} The formatted lint results.
1140
+ * @returns {string} The formatted lint results.
631
1141
  */
632
1142
  format(results, resultsMeta) {
633
1143
  let rulesMeta = null;
@@ -636,12 +1146,10 @@ class ESLint {
636
1146
 
637
1147
  return formatter(results, {
638
1148
  ...resultsMeta,
639
- get cwd() {
640
- return options.cwd;
641
- },
1149
+ cwd,
642
1150
  get rulesMeta() {
643
1151
  if (!rulesMeta) {
644
- rulesMeta = createRulesMeta(cliEngine.getRules());
1152
+ rulesMeta = eslint.getRulesMetaForResults(results);
645
1153
  }
646
1154
 
647
1155
  return rulesMeta;
@@ -656,15 +1164,31 @@ class ESLint {
656
1164
  * This is the same logic used by the ESLint CLI executable to determine
657
1165
  * configuration for each file it processes.
658
1166
  * @param {string} filePath The path of the file to retrieve a config object for.
659
- * @returns {Promise<ConfigData>} A configuration object for the file.
1167
+ * @returns {Promise<ConfigData|undefined>} A configuration object for the file
1168
+ * or `undefined` if there is no configuration data for the object.
660
1169
  */
661
1170
  async calculateConfigForFile(filePath) {
662
1171
  if (!isNonEmptyString(filePath)) {
663
1172
  throw new Error("'filePath' must be a non-empty string");
664
1173
  }
665
- const { cliEngine } = privateMembersMap.get(this);
1174
+ const options = privateMembers.get(this).options;
1175
+ const absolutePath = path.resolve(options.cwd, filePath);
1176
+ const configs = await calculateConfigArray(this, options);
666
1177
 
667
- return cliEngine.getConfigForFile(filePath);
1178
+ return configs.getConfig(absolutePath);
1179
+ }
1180
+
1181
+ /**
1182
+ * Finds the config file being used by this instance based on the options
1183
+ * passed to the constructor.
1184
+ * @returns {string|undefined} The path to the config file being used or
1185
+ * `undefined` if no config file is being used.
1186
+ */
1187
+ async findConfigFile() {
1188
+ const options = privateMembers.get(this).options;
1189
+ const { configFilePath } = await locateConfigFileToUse(options);
1190
+
1191
+ return configFilePath;
668
1192
  }
669
1193
 
670
1194
  /**
@@ -673,21 +1197,19 @@ class ESLint {
673
1197
  * @returns {Promise<boolean>} Whether or not the given path is ignored.
674
1198
  */
675
1199
  async isPathIgnored(filePath) {
676
- if (!isNonEmptyString(filePath)) {
677
- throw new Error("'filePath' must be a non-empty string");
678
- }
679
- const { cliEngine } = privateMembersMap.get(this);
1200
+ const config = await this.calculateConfigForFile(filePath);
680
1201
 
681
- return cliEngine.isPathIgnored(filePath);
1202
+ return config === void 0;
682
1203
  }
683
1204
  }
684
1205
 
685
1206
  /**
686
- * The type of configuration used by this class.
687
- * @type {string}
688
- * @static
1207
+ * Returns whether flat config should be used.
1208
+ * @returns {Promise<boolean>} Whether flat config should be used.
689
1209
  */
690
- ESLint.configType = "eslintrc";
1210
+ async function shouldUseFlatConfig() {
1211
+ return (process.env.ESLINT_USE_FLAT_CONFIG !== "false");
1212
+ }
691
1213
 
692
1214
  //------------------------------------------------------------------------------
693
1215
  // Public Interface
@@ -695,13 +1217,6 @@ ESLint.configType = "eslintrc";
695
1217
 
696
1218
  module.exports = {
697
1219
  ESLint,
698
-
699
- /**
700
- * Get the private class members of a given ESLint instance for tests.
701
- * @param {ESLint} instance The ESLint instance to get.
702
- * @returns {ESLintPrivateMembers} The instance's private class members.
703
- */
704
- getESLintPrivateMembers(instance) {
705
- return privateMembersMap.get(instance);
706
- }
1220
+ shouldUseFlatConfig,
1221
+ locateConfigFileToUse
707
1222
  };