ADAPT-Chase commited on
Commit
e79b50e
·
verified ·
1 Parent(s): faaafad

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/cli-engine.js +1078 -0
  2. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/file-enumerator.js +547 -0
  3. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/checkstyle.js +60 -0
  4. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/compact.js +60 -0
  5. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/formatters-meta.json +46 -0
  6. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/html.js +351 -0
  7. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/jslint-xml.js +41 -0
  8. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/json-with-metadata.js +16 -0
  9. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/json.js +13 -0
  10. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/junit.js +82 -0
  11. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/stylish.js +101 -0
  12. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/tap.js +95 -0
  13. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/unix.js +58 -0
  14. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/visualstudio.js +63 -0
  15. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/hash.js +35 -0
  16. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/index.js +7 -0
  17. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/lint-result-cache.js +203 -0
  18. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/load-rules.js +46 -0
  19. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/xml-escape.js +34 -0
  20. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/config/default-config.js +67 -0
  21. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/config/flat-config-array.js +380 -0
  22. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/config/flat-config-helpers.js +111 -0
  23. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/config/flat-config-schema.js +598 -0
  24. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/config/rule-validator.js +158 -0
  25. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/eslint/eslint-helpers.js +932 -0
  26. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/eslint/eslint.js +707 -0
  27. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/eslint/flat-eslint.js +1159 -0
  28. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/eslint/index.js +9 -0
  29. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/apply-disable-directives.js +465 -0
  30. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js +852 -0
  31. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/code-path-analysis/code-path-segment.js +263 -0
  32. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/code-path-analysis/code-path-state.js +2348 -0
  33. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/code-path-analysis/code-path.js +342 -0
  34. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/code-path-analysis/debug-helpers.js +203 -0
  35. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/code-path-analysis/fork-context.js +349 -0
  36. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/code-path-analysis/id-generator.js +45 -0
  37. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/config-comment-parser.js +185 -0
  38. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/index.js +13 -0
  39. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/interpolate.js +28 -0
  40. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/linter.js +2119 -0
  41. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/node-event-generator.js +354 -0
  42. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/report-translator.js +369 -0
  43. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/rule-fixer.js +140 -0
  44. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/rules.js +80 -0
  45. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/safe-emitter.js +52 -0
  46. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/source-code-fixer.js +152 -0
  47. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/timing.js +161 -0
  48. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/rule-tester/flat-rule-tester.js +1131 -0
  49. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/rule-tester/index.js +5 -0
  50. novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/rule-tester/rule-tester.js +1206 -0
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/cli-engine.js ADDED
@@ -0,0 +1,1078 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Main CLI object.
3
+ * @author Nicholas C. Zakas
4
+ */
5
+
6
+ "use strict";
7
+
8
+ /*
9
+ * The CLI object should *not* call process.exit() directly. It should only return
10
+ * exit codes. This allows other programs to use the CLI object and still control
11
+ * when the program exits.
12
+ */
13
+
14
+ //------------------------------------------------------------------------------
15
+ // Requirements
16
+ //------------------------------------------------------------------------------
17
+
18
+ const fs = require("fs");
19
+ const path = require("path");
20
+ const defaultOptions = require("../../conf/default-cli-options");
21
+ const pkg = require("../../package.json");
22
+
23
+
24
+ const {
25
+ Legacy: {
26
+ ConfigOps,
27
+ naming,
28
+ CascadingConfigArrayFactory,
29
+ IgnorePattern,
30
+ getUsedExtractedConfigs,
31
+ ModuleResolver
32
+ }
33
+ } = require("@eslint/eslintrc");
34
+
35
+ const { FileEnumerator } = require("./file-enumerator");
36
+
37
+ const { Linter } = require("../linter");
38
+ const builtInRules = require("../rules");
39
+ const loadRules = require("./load-rules");
40
+ const hash = require("./hash");
41
+ const LintResultCache = require("./lint-result-cache");
42
+
43
+ const debug = require("debug")("eslint:cli-engine");
44
+ const validFixTypes = new Set(["directive", "problem", "suggestion", "layout"]);
45
+
46
+ //------------------------------------------------------------------------------
47
+ // Typedefs
48
+ //------------------------------------------------------------------------------
49
+
50
+ // For VSCode IntelliSense
51
+ /** @typedef {import("../shared/types").ConfigData} ConfigData */
52
+ /** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */
53
+ /** @typedef {import("../shared/types").LintMessage} LintMessage */
54
+ /** @typedef {import("../shared/types").SuppressedLintMessage} SuppressedLintMessage */
55
+ /** @typedef {import("../shared/types").ParserOptions} ParserOptions */
56
+ /** @typedef {import("../shared/types").Plugin} Plugin */
57
+ /** @typedef {import("../shared/types").RuleConf} RuleConf */
58
+ /** @typedef {import("../shared/types").Rule} Rule */
59
+ /** @typedef {import("../shared/types").FormatterFunction} FormatterFunction */
60
+ /** @typedef {ReturnType<CascadingConfigArrayFactory.getConfigArrayForFile>} ConfigArray */
61
+ /** @typedef {ReturnType<ConfigArray.extractConfig>} ExtractedConfig */
62
+
63
+ /**
64
+ * The options to configure a CLI engine with.
65
+ * @typedef {Object} CLIEngineOptions
66
+ * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments.
67
+ * @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this CLIEngine instance
68
+ * @property {boolean} [cache] Enable result caching.
69
+ * @property {string} [cacheLocation] The cache file to use instead of .eslintcache.
70
+ * @property {string} [configFile] The configuration file to use.
71
+ * @property {string} [cwd] The value to use for the current working directory.
72
+ * @property {string[]} [envs] An array of environments to load.
73
+ * @property {string[]|null} [extensions] An array of file extensions to check.
74
+ * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean.
75
+ * @property {string[]} [fixTypes] Array of rule types to apply fixes for.
76
+ * @property {string[]} [globals] An array of global variables to declare.
77
+ * @property {boolean} [ignore] False disables use of .eslintignore.
78
+ * @property {string} [ignorePath] The ignore file to use instead of .eslintignore.
79
+ * @property {string|string[]} [ignorePattern] One or more glob patterns to ignore.
80
+ * @property {boolean} [useEslintrc] False disables looking for .eslintrc
81
+ * @property {string} [parser] The name of the parser to use.
82
+ * @property {ParserOptions} [parserOptions] An object of parserOption settings to use.
83
+ * @property {string[]} [plugins] An array of plugins to load.
84
+ * @property {Record<string,RuleConf>} [rules] An object of rules to use.
85
+ * @property {string[]} [rulePaths] An array of directories to load custom rules from.
86
+ * @property {boolean|string} [reportUnusedDisableDirectives] `true`, `"error"` or '"warn"' adds reports for unused eslint-disable directives
87
+ * @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.
88
+ * @property {string} [resolvePluginsRelativeTo] The folder where plugins should be resolved from, defaulting to the CWD
89
+ */
90
+
91
+ /**
92
+ * A linting result.
93
+ * @typedef {Object} LintResult
94
+ * @property {string} filePath The path to the file that was linted.
95
+ * @property {LintMessage[]} messages All of the messages for the result.
96
+ * @property {SuppressedLintMessage[]} suppressedMessages All of the suppressed messages for the result.
97
+ * @property {number} errorCount Number of errors for the result.
98
+ * @property {number} fatalErrorCount Number of fatal errors for the result.
99
+ * @property {number} warningCount Number of warnings for the result.
100
+ * @property {number} fixableErrorCount Number of fixable errors for the result.
101
+ * @property {number} fixableWarningCount Number of fixable warnings for the result.
102
+ * @property {string} [source] The source code of the file that was linted.
103
+ * @property {string} [output] The source code of the file that was linted, with as many fixes applied as possible.
104
+ */
105
+
106
+ /**
107
+ * Linting results.
108
+ * @typedef {Object} LintReport
109
+ * @property {LintResult[]} results All of the result.
110
+ * @property {number} errorCount Number of errors for the result.
111
+ * @property {number} fatalErrorCount Number of fatal errors for the result.
112
+ * @property {number} warningCount Number of warnings for the result.
113
+ * @property {number} fixableErrorCount Number of fixable errors for the result.
114
+ * @property {number} fixableWarningCount Number of fixable warnings for the result.
115
+ * @property {DeprecatedRuleInfo[]} usedDeprecatedRules The list of used deprecated rules.
116
+ */
117
+
118
+ /**
119
+ * Private data for CLIEngine.
120
+ * @typedef {Object} CLIEngineInternalSlots
121
+ * @property {Map<string, Plugin>} additionalPluginPool The map for additional plugins.
122
+ * @property {string} cacheFilePath The path to the cache of lint results.
123
+ * @property {CascadingConfigArrayFactory} configArrayFactory The factory of configs.
124
+ * @property {(filePath: string) => boolean} defaultIgnores The default predicate function to check if a file ignored or not.
125
+ * @property {FileEnumerator} fileEnumerator The file enumerator.
126
+ * @property {ConfigArray[]} lastConfigArrays The list of config arrays that the last `executeOnFiles` or `executeOnText` used.
127
+ * @property {LintResultCache|null} lintResultCache The cache of lint results.
128
+ * @property {Linter} linter The linter instance which has loaded rules.
129
+ * @property {CLIEngineOptions} options The normalized options of this instance.
130
+ */
131
+
132
+ //------------------------------------------------------------------------------
133
+ // Helpers
134
+ //------------------------------------------------------------------------------
135
+
136
+ /** @type {WeakMap<CLIEngine, CLIEngineInternalSlots>} */
137
+ const internalSlotsMap = new WeakMap();
138
+
139
+ /**
140
+ * Determines if each fix type in an array is supported by ESLint and throws
141
+ * an error if not.
142
+ * @param {string[]} fixTypes An array of fix types to check.
143
+ * @returns {void}
144
+ * @throws {Error} If an invalid fix type is found.
145
+ */
146
+ function validateFixTypes(fixTypes) {
147
+ for (const fixType of fixTypes) {
148
+ if (!validFixTypes.has(fixType)) {
149
+ throw new Error(`Invalid fix type "${fixType}" found.`);
150
+ }
151
+ }
152
+ }
153
+
154
+ /**
155
+ * It will calculate the error and warning count for collection of messages per file
156
+ * @param {LintMessage[]} messages Collection of messages
157
+ * @returns {Object} Contains the stats
158
+ * @private
159
+ */
160
+ function calculateStatsPerFile(messages) {
161
+ const stat = {
162
+ errorCount: 0,
163
+ fatalErrorCount: 0,
164
+ warningCount: 0,
165
+ fixableErrorCount: 0,
166
+ fixableWarningCount: 0
167
+ };
168
+
169
+ for (let i = 0; i < messages.length; i++) {
170
+ const message = messages[i];
171
+
172
+ if (message.fatal || message.severity === 2) {
173
+ stat.errorCount++;
174
+ if (message.fatal) {
175
+ stat.fatalErrorCount++;
176
+ }
177
+ if (message.fix) {
178
+ stat.fixableErrorCount++;
179
+ }
180
+ } else {
181
+ stat.warningCount++;
182
+ if (message.fix) {
183
+ stat.fixableWarningCount++;
184
+ }
185
+ }
186
+ }
187
+ return stat;
188
+ }
189
+
190
+ /**
191
+ * It will calculate the error and warning count for collection of results from all files
192
+ * @param {LintResult[]} results Collection of messages from all the files
193
+ * @returns {Object} Contains the stats
194
+ * @private
195
+ */
196
+ function calculateStatsPerRun(results) {
197
+ const stat = {
198
+ errorCount: 0,
199
+ fatalErrorCount: 0,
200
+ warningCount: 0,
201
+ fixableErrorCount: 0,
202
+ fixableWarningCount: 0
203
+ };
204
+
205
+ for (let i = 0; i < results.length; i++) {
206
+ const result = results[i];
207
+
208
+ stat.errorCount += result.errorCount;
209
+ stat.fatalErrorCount += result.fatalErrorCount;
210
+ stat.warningCount += result.warningCount;
211
+ stat.fixableErrorCount += result.fixableErrorCount;
212
+ stat.fixableWarningCount += result.fixableWarningCount;
213
+ }
214
+
215
+ return stat;
216
+ }
217
+
218
+ /**
219
+ * Processes an source code using ESLint.
220
+ * @param {Object} config The config object.
221
+ * @param {string} config.text The source code to verify.
222
+ * @param {string} config.cwd The path to the current working directory.
223
+ * @param {string|undefined} config.filePath The path to the file of `text`. If this is undefined, it uses `<text>`.
224
+ * @param {ConfigArray} config.config The config.
225
+ * @param {boolean} config.fix If `true` then it does fix.
226
+ * @param {boolean} config.allowInlineConfig If `true` then it uses directive comments.
227
+ * @param {boolean|string} config.reportUnusedDisableDirectives If `true`, `"error"` or '"warn"', then it reports unused `eslint-disable` comments.
228
+ * @param {FileEnumerator} config.fileEnumerator The file enumerator to check if a path is a target or not.
229
+ * @param {Linter} config.linter The linter instance to verify.
230
+ * @returns {LintResult} The result of linting.
231
+ * @private
232
+ */
233
+ function verifyText({
234
+ text,
235
+ cwd,
236
+ filePath: providedFilePath,
237
+ config,
238
+ fix,
239
+ allowInlineConfig,
240
+ reportUnusedDisableDirectives,
241
+ fileEnumerator,
242
+ linter
243
+ }) {
244
+ const filePath = providedFilePath || "<text>";
245
+
246
+ debug(`Lint ${filePath}`);
247
+
248
+ /*
249
+ * Verify.
250
+ * `config.extractConfig(filePath)` requires an absolute path, but `linter`
251
+ * doesn't know CWD, so it gives `linter` an absolute path always.
252
+ */
253
+ const filePathToVerify = filePath === "<text>" ? path.join(cwd, filePath) : filePath;
254
+ const { fixed, messages, output } = linter.verifyAndFix(
255
+ text,
256
+ config,
257
+ {
258
+ allowInlineConfig,
259
+ filename: filePathToVerify,
260
+ fix,
261
+ reportUnusedDisableDirectives,
262
+
263
+ /**
264
+ * Check if the linter should adopt a given code block or not.
265
+ * @param {string} blockFilename The virtual filename of a code block.
266
+ * @returns {boolean} `true` if the linter should adopt the code block.
267
+ */
268
+ filterCodeBlock(blockFilename) {
269
+ return fileEnumerator.isTargetPath(blockFilename);
270
+ }
271
+ }
272
+ );
273
+
274
+ // Tweak and return.
275
+ const result = {
276
+ filePath,
277
+ messages,
278
+ suppressedMessages: linter.getSuppressedMessages(),
279
+ ...calculateStatsPerFile(messages)
280
+ };
281
+
282
+ if (fixed) {
283
+ result.output = output;
284
+ }
285
+ if (
286
+ result.errorCount + result.warningCount > 0 &&
287
+ typeof result.output === "undefined"
288
+ ) {
289
+ result.source = text;
290
+ }
291
+
292
+ return result;
293
+ }
294
+
295
+ /**
296
+ * Returns result with warning by ignore settings
297
+ * @param {string} filePath File path of checked code
298
+ * @param {string} baseDir Absolute path of base directory
299
+ * @returns {LintResult} Result with single warning
300
+ * @private
301
+ */
302
+ function createIgnoreResult(filePath, baseDir) {
303
+ let message;
304
+ const isHidden = filePath.split(path.sep)
305
+ .find(segment => /^\./u.test(segment));
306
+ const isInNodeModules = baseDir && path.relative(baseDir, filePath).startsWith("node_modules");
307
+
308
+ if (isHidden) {
309
+ message = "File ignored by default. Use a negated ignore pattern (like \"--ignore-pattern '!<relative/path/to/filename>'\") to override.";
310
+ } else if (isInNodeModules) {
311
+ message = "File ignored by default. Use \"--ignore-pattern '!node_modules/*'\" to override.";
312
+ } else {
313
+ message = "File ignored because of a matching ignore pattern. Use \"--no-ignore\" to override.";
314
+ }
315
+
316
+ return {
317
+ filePath: path.resolve(filePath),
318
+ messages: [
319
+ {
320
+ ruleId: null,
321
+ fatal: false,
322
+ severity: 1,
323
+ message,
324
+ nodeType: null
325
+ }
326
+ ],
327
+ suppressedMessages: [],
328
+ errorCount: 0,
329
+ fatalErrorCount: 0,
330
+ warningCount: 1,
331
+ fixableErrorCount: 0,
332
+ fixableWarningCount: 0
333
+ };
334
+ }
335
+
336
+ /**
337
+ * Get a rule.
338
+ * @param {string} ruleId The rule ID to get.
339
+ * @param {ConfigArray[]} configArrays The config arrays that have plugin rules.
340
+ * @returns {Rule|null} The rule or null.
341
+ */
342
+ function getRule(ruleId, configArrays) {
343
+ for (const configArray of configArrays) {
344
+ const rule = configArray.pluginRules.get(ruleId);
345
+
346
+ if (rule) {
347
+ return rule;
348
+ }
349
+ }
350
+ return builtInRules.get(ruleId) || null;
351
+ }
352
+
353
+ /**
354
+ * Checks whether a message's rule type should be fixed.
355
+ * @param {LintMessage} message The message to check.
356
+ * @param {ConfigArray[]} lastConfigArrays The list of config arrays that the last `executeOnFiles` or `executeOnText` used.
357
+ * @param {string[]} fixTypes An array of fix types to check.
358
+ * @returns {boolean} Whether the message should be fixed.
359
+ */
360
+ function shouldMessageBeFixed(message, lastConfigArrays, fixTypes) {
361
+ if (!message.ruleId) {
362
+ return fixTypes.has("directive");
363
+ }
364
+
365
+ const rule = message.ruleId && getRule(message.ruleId, lastConfigArrays);
366
+
367
+ return Boolean(rule && rule.meta && fixTypes.has(rule.meta.type));
368
+ }
369
+
370
+ /**
371
+ * Collect used deprecated rules.
372
+ * @param {ConfigArray[]} usedConfigArrays The config arrays which were used.
373
+ * @returns {IterableIterator<DeprecatedRuleInfo>} Used deprecated rules.
374
+ */
375
+ function *iterateRuleDeprecationWarnings(usedConfigArrays) {
376
+ const processedRuleIds = new Set();
377
+
378
+ // Flatten used configs.
379
+ /** @type {ExtractedConfig[]} */
380
+ const configs = usedConfigArrays.flatMap(getUsedExtractedConfigs);
381
+
382
+ // Traverse rule configs.
383
+ for (const config of configs) {
384
+ for (const [ruleId, ruleConfig] of Object.entries(config.rules)) {
385
+
386
+ // Skip if it was processed.
387
+ if (processedRuleIds.has(ruleId)) {
388
+ continue;
389
+ }
390
+ processedRuleIds.add(ruleId);
391
+
392
+ // Skip if it's not used.
393
+ if (!ConfigOps.getRuleSeverity(ruleConfig)) {
394
+ continue;
395
+ }
396
+ const rule = getRule(ruleId, usedConfigArrays);
397
+
398
+ // Skip if it's not deprecated.
399
+ if (!(rule && rule.meta && rule.meta.deprecated)) {
400
+ continue;
401
+ }
402
+
403
+ // This rule was used and deprecated.
404
+ yield {
405
+ ruleId,
406
+ replacedBy: rule.meta.replacedBy || []
407
+ };
408
+ }
409
+ }
410
+ }
411
+
412
+ /**
413
+ * Checks if the given message is an error message.
414
+ * @param {LintMessage} message The message to check.
415
+ * @returns {boolean} Whether or not the message is an error message.
416
+ * @private
417
+ */
418
+ function isErrorMessage(message) {
419
+ return message.severity === 2;
420
+ }
421
+
422
+
423
+ /**
424
+ * return the cacheFile to be used by eslint, based on whether the provided parameter is
425
+ * a directory or looks like a directory (ends in `path.sep`), in which case the file
426
+ * name will be the `cacheFile/.cache_hashOfCWD`
427
+ *
428
+ * if cacheFile points to a file or looks like a file then it will just use that file
429
+ * @param {string} cacheFile The name of file to be used to store the cache
430
+ * @param {string} cwd Current working directory
431
+ * @returns {string} the resolved path to the cache file
432
+ */
433
+ function getCacheFile(cacheFile, cwd) {
434
+
435
+ /*
436
+ * make sure the path separators are normalized for the environment/os
437
+ * keeping the trailing path separator if present
438
+ */
439
+ const normalizedCacheFile = path.normalize(cacheFile);
440
+
441
+ const resolvedCacheFile = path.resolve(cwd, normalizedCacheFile);
442
+ const looksLikeADirectory = normalizedCacheFile.slice(-1) === path.sep;
443
+
444
+ /**
445
+ * return the name for the cache file in case the provided parameter is a directory
446
+ * @returns {string} the resolved path to the cacheFile
447
+ */
448
+ function getCacheFileForDirectory() {
449
+ return path.join(resolvedCacheFile, `.cache_${hash(cwd)}`);
450
+ }
451
+
452
+ let fileStats;
453
+
454
+ try {
455
+ fileStats = fs.lstatSync(resolvedCacheFile);
456
+ } catch {
457
+ fileStats = null;
458
+ }
459
+
460
+
461
+ /*
462
+ * in case the file exists we need to verify if the provided path
463
+ * is a directory or a file. If it is a directory we want to create a file
464
+ * inside that directory
465
+ */
466
+ if (fileStats) {
467
+
468
+ /*
469
+ * is a directory or is a file, but the original file the user provided
470
+ * looks like a directory but `path.resolve` removed the `last path.sep`
471
+ * so we need to still treat this like a directory
472
+ */
473
+ if (fileStats.isDirectory() || looksLikeADirectory) {
474
+ return getCacheFileForDirectory();
475
+ }
476
+
477
+ // is file so just use that file
478
+ return resolvedCacheFile;
479
+ }
480
+
481
+ /*
482
+ * here we known the file or directory doesn't exist,
483
+ * so we will try to infer if its a directory if it looks like a directory
484
+ * for the current operating system.
485
+ */
486
+
487
+ // if the last character passed is a path separator we assume is a directory
488
+ if (looksLikeADirectory) {
489
+ return getCacheFileForDirectory();
490
+ }
491
+
492
+ return resolvedCacheFile;
493
+ }
494
+
495
+ /**
496
+ * Convert a string array to a boolean map.
497
+ * @param {string[]|null} keys The keys to assign true.
498
+ * @param {boolean} defaultValue The default value for each property.
499
+ * @param {string} displayName The property name which is used in error message.
500
+ * @throws {Error} Requires array.
501
+ * @returns {Record<string,boolean>} The boolean map.
502
+ */
503
+ function toBooleanMap(keys, defaultValue, displayName) {
504
+ if (keys && !Array.isArray(keys)) {
505
+ throw new Error(`${displayName} must be an array.`);
506
+ }
507
+ if (keys && keys.length > 0) {
508
+ return keys.reduce((map, def) => {
509
+ const [key, value] = def.split(":");
510
+
511
+ if (key !== "__proto__") {
512
+ map[key] = value === void 0
513
+ ? defaultValue
514
+ : value === "true";
515
+ }
516
+
517
+ return map;
518
+ }, {});
519
+ }
520
+ return void 0;
521
+ }
522
+
523
+ /**
524
+ * Create a config data from CLI options.
525
+ * @param {CLIEngineOptions} options The options
526
+ * @returns {ConfigData|null} The created config data.
527
+ */
528
+ function createConfigDataFromOptions(options) {
529
+ const {
530
+ ignorePattern,
531
+ parser,
532
+ parserOptions,
533
+ plugins,
534
+ rules
535
+ } = options;
536
+ const env = toBooleanMap(options.envs, true, "envs");
537
+ const globals = toBooleanMap(options.globals, false, "globals");
538
+
539
+ if (
540
+ env === void 0 &&
541
+ globals === void 0 &&
542
+ (ignorePattern === void 0 || ignorePattern.length === 0) &&
543
+ parser === void 0 &&
544
+ parserOptions === void 0 &&
545
+ plugins === void 0 &&
546
+ rules === void 0
547
+ ) {
548
+ return null;
549
+ }
550
+ return {
551
+ env,
552
+ globals,
553
+ ignorePatterns: ignorePattern,
554
+ parser,
555
+ parserOptions,
556
+ plugins,
557
+ rules
558
+ };
559
+ }
560
+
561
+ /**
562
+ * Checks whether a directory exists at the given location
563
+ * @param {string} resolvedPath A path from the CWD
564
+ * @throws {Error} As thrown by `fs.statSync` or `fs.isDirectory`.
565
+ * @returns {boolean} `true` if a directory exists
566
+ */
567
+ function directoryExists(resolvedPath) {
568
+ try {
569
+ return fs.statSync(resolvedPath).isDirectory();
570
+ } catch (error) {
571
+ if (error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
572
+ return false;
573
+ }
574
+ throw error;
575
+ }
576
+ }
577
+
578
+ //------------------------------------------------------------------------------
579
+ // Public Interface
580
+ //------------------------------------------------------------------------------
581
+
582
+ /**
583
+ * Core CLI.
584
+ */
585
+ class CLIEngine {
586
+
587
+ /**
588
+ * Creates a new instance of the core CLI engine.
589
+ * @param {CLIEngineOptions} providedOptions The options for this instance.
590
+ * @param {Object} [additionalData] Additional settings that are not CLIEngineOptions.
591
+ * @param {Record<string,Plugin>|null} [additionalData.preloadedPlugins] Preloaded plugins.
592
+ */
593
+ constructor(providedOptions, { preloadedPlugins } = {}) {
594
+ const options = Object.assign(
595
+ Object.create(null),
596
+ defaultOptions,
597
+ { cwd: process.cwd() },
598
+ providedOptions
599
+ );
600
+
601
+ if (options.fix === void 0) {
602
+ options.fix = false;
603
+ }
604
+
605
+ const additionalPluginPool = new Map();
606
+
607
+ if (preloadedPlugins) {
608
+ for (const [id, plugin] of Object.entries(preloadedPlugins)) {
609
+ additionalPluginPool.set(id, plugin);
610
+ }
611
+ }
612
+
613
+ const cacheFilePath = getCacheFile(
614
+ options.cacheLocation || options.cacheFile,
615
+ options.cwd
616
+ );
617
+ const configArrayFactory = new CascadingConfigArrayFactory({
618
+ additionalPluginPool,
619
+ baseConfig: options.baseConfig || null,
620
+ cliConfig: createConfigDataFromOptions(options),
621
+ cwd: options.cwd,
622
+ ignorePath: options.ignorePath,
623
+ resolvePluginsRelativeTo: options.resolvePluginsRelativeTo,
624
+ rulePaths: options.rulePaths,
625
+ specificConfigPath: options.configFile,
626
+ useEslintrc: options.useEslintrc,
627
+ builtInRules,
628
+ loadRules,
629
+ getEslintRecommendedConfig: () => require("@eslint/js").configs.recommended,
630
+ getEslintAllConfig: () => require("@eslint/js").configs.all
631
+ });
632
+ const fileEnumerator = new FileEnumerator({
633
+ configArrayFactory,
634
+ cwd: options.cwd,
635
+ extensions: options.extensions,
636
+ globInputPaths: options.globInputPaths,
637
+ errorOnUnmatchedPattern: options.errorOnUnmatchedPattern,
638
+ ignore: options.ignore
639
+ });
640
+ const lintResultCache =
641
+ options.cache ? new LintResultCache(cacheFilePath, options.cacheStrategy) : null;
642
+ const linter = new Linter({ cwd: options.cwd });
643
+
644
+ /** @type {ConfigArray[]} */
645
+ const lastConfigArrays = [configArrayFactory.getConfigArrayForFile()];
646
+
647
+ // Store private data.
648
+ internalSlotsMap.set(this, {
649
+ additionalPluginPool,
650
+ cacheFilePath,
651
+ configArrayFactory,
652
+ defaultIgnores: IgnorePattern.createDefaultIgnore(options.cwd),
653
+ fileEnumerator,
654
+ lastConfigArrays,
655
+ lintResultCache,
656
+ linter,
657
+ options
658
+ });
659
+
660
+ // setup special filter for fixes
661
+ if (options.fix && options.fixTypes && options.fixTypes.length > 0) {
662
+ debug(`Using fix types ${options.fixTypes}`);
663
+
664
+ // throw an error if any invalid fix types are found
665
+ validateFixTypes(options.fixTypes);
666
+
667
+ // convert to Set for faster lookup
668
+ const fixTypes = new Set(options.fixTypes);
669
+
670
+ // save original value of options.fix in case it's a function
671
+ const originalFix = (typeof options.fix === "function")
672
+ ? options.fix : () => true;
673
+
674
+ options.fix = message => shouldMessageBeFixed(message, lastConfigArrays, fixTypes) && originalFix(message);
675
+ }
676
+ }
677
+
678
+ getRules() {
679
+ const { lastConfigArrays } = internalSlotsMap.get(this);
680
+
681
+ return new Map(function *() {
682
+ yield* builtInRules;
683
+
684
+ for (const configArray of lastConfigArrays) {
685
+ yield* configArray.pluginRules;
686
+ }
687
+ }());
688
+ }
689
+
690
+ /**
691
+ * Returns results that only contains errors.
692
+ * @param {LintResult[]} results The results to filter.
693
+ * @returns {LintResult[]} The filtered results.
694
+ */
695
+ static getErrorResults(results) {
696
+ const filtered = [];
697
+
698
+ results.forEach(result => {
699
+ const filteredMessages = result.messages.filter(isErrorMessage);
700
+ const filteredSuppressedMessages = result.suppressedMessages.filter(isErrorMessage);
701
+
702
+ if (filteredMessages.length > 0) {
703
+ filtered.push({
704
+ ...result,
705
+ messages: filteredMessages,
706
+ suppressedMessages: filteredSuppressedMessages,
707
+ errorCount: filteredMessages.length,
708
+ warningCount: 0,
709
+ fixableErrorCount: result.fixableErrorCount,
710
+ fixableWarningCount: 0
711
+ });
712
+ }
713
+ });
714
+
715
+ return filtered;
716
+ }
717
+
718
+ /**
719
+ * Outputs fixes from the given results to files.
720
+ * @param {LintReport} report The report object created by CLIEngine.
721
+ * @returns {void}
722
+ */
723
+ static outputFixes(report) {
724
+ report.results.filter(result => Object.prototype.hasOwnProperty.call(result, "output")).forEach(result => {
725
+ fs.writeFileSync(result.filePath, result.output);
726
+ });
727
+ }
728
+
729
+ /**
730
+ * Resolves the patterns passed into executeOnFiles() into glob-based patterns
731
+ * for easier handling.
732
+ * @param {string[]} patterns The file patterns passed on the command line.
733
+ * @returns {string[]} The equivalent glob patterns.
734
+ */
735
+ resolveFileGlobPatterns(patterns) {
736
+ const { options } = internalSlotsMap.get(this);
737
+
738
+ if (options.globInputPaths === false) {
739
+ return patterns.filter(Boolean);
740
+ }
741
+
742
+ const extensions = (options.extensions || [".js"]).map(ext => ext.replace(/^\./u, ""));
743
+ const dirSuffix = `/**/*.{${extensions.join(",")}}`;
744
+
745
+ return patterns.filter(Boolean).map(pathname => {
746
+ const resolvedPath = path.resolve(options.cwd, pathname);
747
+ const newPath = directoryExists(resolvedPath)
748
+ ? pathname.replace(/[/\\]$/u, "") + dirSuffix
749
+ : pathname;
750
+
751
+ return path.normalize(newPath).replace(/\\/gu, "/");
752
+ });
753
+ }
754
+
755
+ /**
756
+ * Executes the current configuration on an array of file and directory names.
757
+ * @param {string[]} patterns An array of file and directory names.
758
+ * @throws {Error} As may be thrown by `fs.unlinkSync`.
759
+ * @returns {LintReport} The results for all files that were linted.
760
+ */
761
+ executeOnFiles(patterns) {
762
+ const {
763
+ cacheFilePath,
764
+ fileEnumerator,
765
+ lastConfigArrays,
766
+ lintResultCache,
767
+ linter,
768
+ options: {
769
+ allowInlineConfig,
770
+ cache,
771
+ cwd,
772
+ fix,
773
+ reportUnusedDisableDirectives
774
+ }
775
+ } = internalSlotsMap.get(this);
776
+ const results = [];
777
+ const startTime = Date.now();
778
+
779
+ // Clear the last used config arrays.
780
+ lastConfigArrays.length = 0;
781
+
782
+ // Delete cache file; should this do here?
783
+ if (!cache) {
784
+ try {
785
+ fs.unlinkSync(cacheFilePath);
786
+ } catch (error) {
787
+ const errorCode = error && error.code;
788
+
789
+ // Ignore errors when no such file exists or file system is read only (and cache file does not exist)
790
+ if (errorCode !== "ENOENT" && !(errorCode === "EROFS" && !fs.existsSync(cacheFilePath))) {
791
+ throw error;
792
+ }
793
+ }
794
+ }
795
+
796
+ // Iterate source code files.
797
+ for (const { config, filePath, ignored } of fileEnumerator.iterateFiles(patterns)) {
798
+ if (ignored) {
799
+ results.push(createIgnoreResult(filePath, cwd));
800
+ continue;
801
+ }
802
+
803
+ /*
804
+ * Store used configs for:
805
+ * - this method uses to collect used deprecated rules.
806
+ * - `getRules()` method uses to collect all loaded rules.
807
+ * - `--fix-type` option uses to get the loaded rule's meta data.
808
+ */
809
+ if (!lastConfigArrays.includes(config)) {
810
+ lastConfigArrays.push(config);
811
+ }
812
+
813
+ // Skip if there is cached result.
814
+ if (lintResultCache) {
815
+ const cachedResult =
816
+ lintResultCache.getCachedLintResults(filePath, config);
817
+
818
+ if (cachedResult) {
819
+ const hadMessages =
820
+ cachedResult.messages &&
821
+ cachedResult.messages.length > 0;
822
+
823
+ if (hadMessages && fix) {
824
+ debug(`Reprocessing cached file to allow autofix: ${filePath}`);
825
+ } else {
826
+ debug(`Skipping file since it hasn't changed: ${filePath}`);
827
+ results.push(cachedResult);
828
+ continue;
829
+ }
830
+ }
831
+ }
832
+
833
+ // Do lint.
834
+ const result = verifyText({
835
+ text: fs.readFileSync(filePath, "utf8"),
836
+ filePath,
837
+ config,
838
+ cwd,
839
+ fix,
840
+ allowInlineConfig,
841
+ reportUnusedDisableDirectives,
842
+ fileEnumerator,
843
+ linter
844
+ });
845
+
846
+ results.push(result);
847
+
848
+ /*
849
+ * Store the lint result in the LintResultCache.
850
+ * NOTE: The LintResultCache will remove the file source and any
851
+ * other properties that are difficult to serialize, and will
852
+ * hydrate those properties back in on future lint runs.
853
+ */
854
+ if (lintResultCache) {
855
+ lintResultCache.setCachedLintResults(filePath, config, result);
856
+ }
857
+ }
858
+
859
+ // Persist the cache to disk.
860
+ if (lintResultCache) {
861
+ lintResultCache.reconcile();
862
+ }
863
+
864
+ debug(`Linting complete in: ${Date.now() - startTime}ms`);
865
+ let usedDeprecatedRules;
866
+
867
+ return {
868
+ results,
869
+ ...calculateStatsPerRun(results),
870
+
871
+ // Initialize it lazily because CLI and `ESLint` API don't use it.
872
+ get usedDeprecatedRules() {
873
+ if (!usedDeprecatedRules) {
874
+ usedDeprecatedRules = Array.from(
875
+ iterateRuleDeprecationWarnings(lastConfigArrays)
876
+ );
877
+ }
878
+ return usedDeprecatedRules;
879
+ }
880
+ };
881
+ }
882
+
883
+ /**
884
+ * Executes the current configuration on text.
885
+ * @param {string} text A string of JavaScript code to lint.
886
+ * @param {string} [filename] An optional string representing the texts filename.
887
+ * @param {boolean} [warnIgnored] Always warn when a file is ignored
888
+ * @returns {LintReport} The results for the linting.
889
+ */
890
+ executeOnText(text, filename, warnIgnored) {
891
+ const {
892
+ configArrayFactory,
893
+ fileEnumerator,
894
+ lastConfigArrays,
895
+ linter,
896
+ options: {
897
+ allowInlineConfig,
898
+ cwd,
899
+ fix,
900
+ reportUnusedDisableDirectives
901
+ }
902
+ } = internalSlotsMap.get(this);
903
+ const results = [];
904
+ const startTime = Date.now();
905
+ const resolvedFilename = filename && path.resolve(cwd, filename);
906
+
907
+
908
+ // Clear the last used config arrays.
909
+ lastConfigArrays.length = 0;
910
+ if (resolvedFilename && this.isPathIgnored(resolvedFilename)) {
911
+ if (warnIgnored) {
912
+ results.push(createIgnoreResult(resolvedFilename, cwd));
913
+ }
914
+ } else {
915
+ const config = configArrayFactory.getConfigArrayForFile(
916
+ resolvedFilename || "__placeholder__.js"
917
+ );
918
+
919
+ /*
920
+ * Store used configs for:
921
+ * - this method uses to collect used deprecated rules.
922
+ * - `getRules()` method uses to collect all loaded rules.
923
+ * - `--fix-type` option uses to get the loaded rule's meta data.
924
+ */
925
+ lastConfigArrays.push(config);
926
+
927
+ // Do lint.
928
+ results.push(verifyText({
929
+ text,
930
+ filePath: resolvedFilename,
931
+ config,
932
+ cwd,
933
+ fix,
934
+ allowInlineConfig,
935
+ reportUnusedDisableDirectives,
936
+ fileEnumerator,
937
+ linter
938
+ }));
939
+ }
940
+
941
+ debug(`Linting complete in: ${Date.now() - startTime}ms`);
942
+ let usedDeprecatedRules;
943
+
944
+ return {
945
+ results,
946
+ ...calculateStatsPerRun(results),
947
+
948
+ // Initialize it lazily because CLI and `ESLint` API don't use it.
949
+ get usedDeprecatedRules() {
950
+ if (!usedDeprecatedRules) {
951
+ usedDeprecatedRules = Array.from(
952
+ iterateRuleDeprecationWarnings(lastConfigArrays)
953
+ );
954
+ }
955
+ return usedDeprecatedRules;
956
+ }
957
+ };
958
+ }
959
+
960
+ /**
961
+ * Returns a configuration object for the given file based on the CLI options.
962
+ * This is the same logic used by the ESLint CLI executable to determine
963
+ * configuration for each file it processes.
964
+ * @param {string} filePath The path of the file to retrieve a config object for.
965
+ * @throws {Error} If filepath a directory path.
966
+ * @returns {ConfigData} A configuration object for the file.
967
+ */
968
+ getConfigForFile(filePath) {
969
+ const { configArrayFactory, options } = internalSlotsMap.get(this);
970
+ const absolutePath = path.resolve(options.cwd, filePath);
971
+
972
+ if (directoryExists(absolutePath)) {
973
+ throw Object.assign(
974
+ new Error("'filePath' should not be a directory path."),
975
+ { messageTemplate: "print-config-with-directory-path" }
976
+ );
977
+ }
978
+
979
+ return configArrayFactory
980
+ .getConfigArrayForFile(absolutePath)
981
+ .extractConfig(absolutePath)
982
+ .toCompatibleObjectAsConfigFileContent();
983
+ }
984
+
985
+ /**
986
+ * Checks if a given path is ignored by ESLint.
987
+ * @param {string} filePath The path of the file to check.
988
+ * @returns {boolean} Whether or not the given path is ignored.
989
+ */
990
+ isPathIgnored(filePath) {
991
+ const {
992
+ configArrayFactory,
993
+ defaultIgnores,
994
+ options: { cwd, ignore }
995
+ } = internalSlotsMap.get(this);
996
+ const absolutePath = path.resolve(cwd, filePath);
997
+
998
+ if (ignore) {
999
+ const config = configArrayFactory
1000
+ .getConfigArrayForFile(absolutePath)
1001
+ .extractConfig(absolutePath);
1002
+ const ignores = config.ignores || defaultIgnores;
1003
+
1004
+ return ignores(absolutePath);
1005
+ }
1006
+
1007
+ return defaultIgnores(absolutePath);
1008
+ }
1009
+
1010
+ /**
1011
+ * Returns the formatter representing the given format or null if the `format` is not a string.
1012
+ * @param {string} [format] The name of the format to load or the path to a
1013
+ * custom formatter.
1014
+ * @throws {any} As may be thrown by requiring of formatter
1015
+ * @returns {(FormatterFunction|null)} The formatter function or null if the `format` is not a string.
1016
+ */
1017
+ getFormatter(format) {
1018
+
1019
+ // default is stylish
1020
+ const resolvedFormatName = format || "stylish";
1021
+
1022
+ // only strings are valid formatters
1023
+ if (typeof resolvedFormatName === "string") {
1024
+
1025
+ // replace \ with / for Windows compatibility
1026
+ const normalizedFormatName = resolvedFormatName.replace(/\\/gu, "/");
1027
+
1028
+ const slots = internalSlotsMap.get(this);
1029
+ const cwd = slots ? slots.options.cwd : process.cwd();
1030
+ const namespace = naming.getNamespaceFromTerm(normalizedFormatName);
1031
+
1032
+ let formatterPath;
1033
+
1034
+ // if there's a slash, then it's a file (TODO: this check seems dubious for scoped npm packages)
1035
+ if (!namespace && normalizedFormatName.includes("/")) {
1036
+ formatterPath = path.resolve(cwd, normalizedFormatName);
1037
+ } else {
1038
+ try {
1039
+ const npmFormat = naming.normalizePackageName(normalizedFormatName, "eslint-formatter");
1040
+
1041
+ formatterPath = ModuleResolver.resolve(npmFormat, path.join(cwd, "__placeholder__.js"));
1042
+ } catch {
1043
+ formatterPath = path.resolve(__dirname, "formatters", normalizedFormatName);
1044
+ }
1045
+ }
1046
+
1047
+ try {
1048
+ return require(formatterPath);
1049
+ } catch (ex) {
1050
+ if (format === "table" || format === "codeframe") {
1051
+ ex.message = `The ${format} formatter is no longer part of core ESLint. Install it manually with \`npm install -D eslint-formatter-${format}\``;
1052
+ } else {
1053
+ ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`;
1054
+ }
1055
+ throw ex;
1056
+ }
1057
+
1058
+ } else {
1059
+ return null;
1060
+ }
1061
+ }
1062
+ }
1063
+
1064
+ CLIEngine.version = pkg.version;
1065
+ CLIEngine.getFormatter = CLIEngine.prototype.getFormatter;
1066
+
1067
+ module.exports = {
1068
+ CLIEngine,
1069
+
1070
+ /**
1071
+ * Get the internal slots of a given CLIEngine instance for tests.
1072
+ * @param {CLIEngine} instance The CLIEngine instance to get.
1073
+ * @returns {CLIEngineInternalSlots} The internal slots.
1074
+ */
1075
+ getCLIEngineInternalSlots(instance) {
1076
+ return internalSlotsMap.get(instance);
1077
+ }
1078
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/file-enumerator.js ADDED
@@ -0,0 +1,547 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview `FileEnumerator` class.
3
+ *
4
+ * `FileEnumerator` class has two responsibilities:
5
+ *
6
+ * 1. Find target files by processing glob patterns.
7
+ * 2. Tie each target file and appropriate configuration.
8
+ *
9
+ * It provides a method:
10
+ *
11
+ * - `iterateFiles(patterns)`
12
+ * Iterate files which are matched by given patterns together with the
13
+ * corresponded configuration. This is for `CLIEngine#executeOnFiles()`.
14
+ * While iterating files, it loads the configuration file of each directory
15
+ * before iterate files on the directory, so we can use the configuration
16
+ * files to determine target files.
17
+ *
18
+ * @example
19
+ * const enumerator = new FileEnumerator();
20
+ * const linter = new Linter();
21
+ *
22
+ * for (const { config, filePath } of enumerator.iterateFiles(["*.js"])) {
23
+ * const code = fs.readFileSync(filePath, "utf8");
24
+ * const messages = linter.verify(code, config, filePath);
25
+ *
26
+ * console.log(messages);
27
+ * }
28
+ *
29
+ * @author Toru Nagashima <https://github.com/mysticatea>
30
+ */
31
+ "use strict";
32
+
33
+ //------------------------------------------------------------------------------
34
+ // Requirements
35
+ //------------------------------------------------------------------------------
36
+
37
+ const fs = require("fs");
38
+ const path = require("path");
39
+ const getGlobParent = require("glob-parent");
40
+ const isGlob = require("is-glob");
41
+ const escapeRegExp = require("escape-string-regexp");
42
+ const { Minimatch } = require("minimatch");
43
+
44
+ const {
45
+ Legacy: {
46
+ IgnorePattern,
47
+ CascadingConfigArrayFactory
48
+ }
49
+ } = require("@eslint/eslintrc");
50
+ const debug = require("debug")("eslint:file-enumerator");
51
+
52
+ //------------------------------------------------------------------------------
53
+ // Helpers
54
+ //------------------------------------------------------------------------------
55
+
56
+ const minimatchOpts = { dot: true, matchBase: true };
57
+ const dotfilesPattern = /(?:(?:^\.)|(?:[/\\]\.))[^/\\.].*/u;
58
+ const NONE = 0;
59
+ const IGNORED_SILENTLY = 1;
60
+ const IGNORED = 2;
61
+
62
+ // For VSCode intellisense
63
+ /** @typedef {ReturnType<CascadingConfigArrayFactory.getConfigArrayForFile>} ConfigArray */
64
+
65
+ /**
66
+ * @typedef {Object} FileEnumeratorOptions
67
+ * @property {CascadingConfigArrayFactory} [configArrayFactory] The factory for config arrays.
68
+ * @property {string} [cwd] The base directory to start lookup.
69
+ * @property {string[]} [extensions] The extensions to match files for directory patterns.
70
+ * @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.
71
+ * @property {boolean} [ignore] The flag to check ignored files.
72
+ * @property {string[]} [rulePaths] The value of `--rulesdir` option.
73
+ */
74
+
75
+ /**
76
+ * @typedef {Object} FileAndConfig
77
+ * @property {string} filePath The path to a target file.
78
+ * @property {ConfigArray} config The config entries of that file.
79
+ * @property {boolean} ignored If `true` then this file should be ignored and warned because it was directly specified.
80
+ */
81
+
82
+ /**
83
+ * @typedef {Object} FileEntry
84
+ * @property {string} filePath The path to a target file.
85
+ * @property {ConfigArray} config The config entries of that file.
86
+ * @property {NONE|IGNORED_SILENTLY|IGNORED} flag The flag.
87
+ * - `NONE` means the file is a target file.
88
+ * - `IGNORED_SILENTLY` means the file should be ignored silently.
89
+ * - `IGNORED` means the file should be ignored and warned because it was directly specified.
90
+ */
91
+
92
+ /**
93
+ * @typedef {Object} FileEnumeratorInternalSlots
94
+ * @property {CascadingConfigArrayFactory} configArrayFactory The factory for config arrays.
95
+ * @property {string} cwd The base directory to start lookup.
96
+ * @property {RegExp|null} extensionRegExp The RegExp to test if a string ends with specific file extensions.
97
+ * @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.
98
+ * @property {boolean} ignoreFlag The flag to check ignored files.
99
+ * @property {(filePath:string, dot:boolean) => boolean} defaultIgnores The default predicate function to ignore files.
100
+ */
101
+
102
+ /** @type {WeakMap<FileEnumerator, FileEnumeratorInternalSlots>} */
103
+ const internalSlotsMap = new WeakMap();
104
+
105
+ /**
106
+ * Check if a string is a glob pattern or not.
107
+ * @param {string} pattern A glob pattern.
108
+ * @returns {boolean} `true` if the string is a glob pattern.
109
+ */
110
+ function isGlobPattern(pattern) {
111
+ return isGlob(path.sep === "\\" ? pattern.replace(/\\/gu, "/") : pattern);
112
+ }
113
+
114
+ /**
115
+ * Get stats of a given path.
116
+ * @param {string} filePath The path to target file.
117
+ * @throws {Error} As may be thrown by `fs.statSync`.
118
+ * @returns {fs.Stats|null} The stats.
119
+ * @private
120
+ */
121
+ function statSafeSync(filePath) {
122
+ try {
123
+ return fs.statSync(filePath);
124
+ } catch (error) {
125
+
126
+ /* c8 ignore next */
127
+ if (error.code !== "ENOENT") {
128
+ throw error;
129
+ }
130
+ return null;
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Get filenames in a given path to a directory.
136
+ * @param {string} directoryPath The path to target directory.
137
+ * @throws {Error} As may be thrown by `fs.readdirSync`.
138
+ * @returns {import("fs").Dirent[]} The filenames.
139
+ * @private
140
+ */
141
+ function readdirSafeSync(directoryPath) {
142
+ try {
143
+ return fs.readdirSync(directoryPath, { withFileTypes: true });
144
+ } catch (error) {
145
+
146
+ /* c8 ignore next */
147
+ if (error.code !== "ENOENT") {
148
+ throw error;
149
+ }
150
+ return [];
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Create a `RegExp` object to detect extensions.
156
+ * @param {string[] | null} extensions The extensions to create.
157
+ * @returns {RegExp | null} The created `RegExp` object or null.
158
+ */
159
+ function createExtensionRegExp(extensions) {
160
+ if (extensions) {
161
+ const normalizedExts = extensions.map(ext => escapeRegExp(
162
+ ext.startsWith(".")
163
+ ? ext.slice(1)
164
+ : ext
165
+ ));
166
+
167
+ return new RegExp(
168
+ `.\\.(?:${normalizedExts.join("|")})$`,
169
+ "u"
170
+ );
171
+ }
172
+ return null;
173
+ }
174
+
175
+ /**
176
+ * The error type when no files match a glob.
177
+ */
178
+ class NoFilesFoundError extends Error {
179
+
180
+ /**
181
+ * @param {string} pattern The glob pattern which was not found.
182
+ * @param {boolean} globDisabled If `true` then the pattern was a glob pattern, but glob was disabled.
183
+ */
184
+ constructor(pattern, globDisabled) {
185
+ super(`No files matching '${pattern}' were found${globDisabled ? " (glob was disabled)" : ""}.`);
186
+ this.messageTemplate = "file-not-found";
187
+ this.messageData = { pattern, globDisabled };
188
+ }
189
+ }
190
+
191
+ /**
192
+ * The error type when there are files matched by a glob, but all of them have been ignored.
193
+ */
194
+ class AllFilesIgnoredError extends Error {
195
+
196
+ /**
197
+ * @param {string} pattern The glob pattern which was not found.
198
+ */
199
+ constructor(pattern) {
200
+ super(`All files matched by '${pattern}' are ignored.`);
201
+ this.messageTemplate = "all-files-ignored";
202
+ this.messageData = { pattern };
203
+ }
204
+ }
205
+
206
+ /**
207
+ * This class provides the functionality that enumerates every file which is
208
+ * matched by given glob patterns and that configuration.
209
+ */
210
+ class FileEnumerator {
211
+
212
+ /**
213
+ * Initialize this enumerator.
214
+ * @param {FileEnumeratorOptions} options The options.
215
+ */
216
+ constructor({
217
+ cwd = process.cwd(),
218
+ configArrayFactory = new CascadingConfigArrayFactory({
219
+ cwd,
220
+ getEslintRecommendedConfig: () => require("@eslint/js").configs.recommended,
221
+ getEslintAllConfig: () => require("@eslint/js").configs.all
222
+ }),
223
+ extensions = null,
224
+ globInputPaths = true,
225
+ errorOnUnmatchedPattern = true,
226
+ ignore = true
227
+ } = {}) {
228
+ internalSlotsMap.set(this, {
229
+ configArrayFactory,
230
+ cwd,
231
+ defaultIgnores: IgnorePattern.createDefaultIgnore(cwd),
232
+ extensionRegExp: createExtensionRegExp(extensions),
233
+ globInputPaths,
234
+ errorOnUnmatchedPattern,
235
+ ignoreFlag: ignore
236
+ });
237
+ }
238
+
239
+ /**
240
+ * Check if a given file is target or not.
241
+ * @param {string} filePath The path to a candidate file.
242
+ * @param {ConfigArray} [providedConfig] Optional. The configuration for the file.
243
+ * @returns {boolean} `true` if the file is a target.
244
+ */
245
+ isTargetPath(filePath, providedConfig) {
246
+ const {
247
+ configArrayFactory,
248
+ extensionRegExp
249
+ } = internalSlotsMap.get(this);
250
+
251
+ // If `--ext` option is present, use it.
252
+ if (extensionRegExp) {
253
+ return extensionRegExp.test(filePath);
254
+ }
255
+
256
+ // `.js` file is target by default.
257
+ if (filePath.endsWith(".js")) {
258
+ return true;
259
+ }
260
+
261
+ // use `overrides[].files` to check additional targets.
262
+ const config =
263
+ providedConfig ||
264
+ configArrayFactory.getConfigArrayForFile(
265
+ filePath,
266
+ { ignoreNotFoundError: true }
267
+ );
268
+
269
+ return config.isAdditionalTargetPath(filePath);
270
+ }
271
+
272
+ /**
273
+ * Iterate files which are matched by given glob patterns.
274
+ * @param {string|string[]} patternOrPatterns The glob patterns to iterate files.
275
+ * @throws {NoFilesFoundError|AllFilesIgnoredError} On an unmatched pattern.
276
+ * @returns {IterableIterator<FileAndConfig>} The found files.
277
+ */
278
+ *iterateFiles(patternOrPatterns) {
279
+ const { globInputPaths, errorOnUnmatchedPattern } = internalSlotsMap.get(this);
280
+ const patterns = Array.isArray(patternOrPatterns)
281
+ ? patternOrPatterns
282
+ : [patternOrPatterns];
283
+
284
+ debug("Start to iterate files: %o", patterns);
285
+
286
+ // The set of paths to remove duplicate.
287
+ const set = new Set();
288
+
289
+ for (const pattern of patterns) {
290
+ let foundRegardlessOfIgnored = false;
291
+ let found = false;
292
+
293
+ // Skip empty string.
294
+ if (!pattern) {
295
+ continue;
296
+ }
297
+
298
+ // Iterate files of this pattern.
299
+ for (const { config, filePath, flag } of this._iterateFiles(pattern)) {
300
+ foundRegardlessOfIgnored = true;
301
+ if (flag === IGNORED_SILENTLY) {
302
+ continue;
303
+ }
304
+ found = true;
305
+
306
+ // Remove duplicate paths while yielding paths.
307
+ if (!set.has(filePath)) {
308
+ set.add(filePath);
309
+ yield {
310
+ config,
311
+ filePath,
312
+ ignored: flag === IGNORED
313
+ };
314
+ }
315
+ }
316
+
317
+ // Raise an error if any files were not found.
318
+ if (errorOnUnmatchedPattern) {
319
+ if (!foundRegardlessOfIgnored) {
320
+ throw new NoFilesFoundError(
321
+ pattern,
322
+ !globInputPaths && isGlob(pattern)
323
+ );
324
+ }
325
+ if (!found) {
326
+ throw new AllFilesIgnoredError(pattern);
327
+ }
328
+ }
329
+ }
330
+
331
+ debug(`Complete iterating files: ${JSON.stringify(patterns)}`);
332
+ }
333
+
334
+ /**
335
+ * Iterate files which are matched by a given glob pattern.
336
+ * @param {string} pattern The glob pattern to iterate files.
337
+ * @returns {IterableIterator<FileEntry>} The found files.
338
+ */
339
+ _iterateFiles(pattern) {
340
+ const { cwd, globInputPaths } = internalSlotsMap.get(this);
341
+ const absolutePath = path.resolve(cwd, pattern);
342
+ const isDot = dotfilesPattern.test(pattern);
343
+ const stat = statSafeSync(absolutePath);
344
+
345
+ if (stat && stat.isDirectory()) {
346
+ return this._iterateFilesWithDirectory(absolutePath, isDot);
347
+ }
348
+ if (stat && stat.isFile()) {
349
+ return this._iterateFilesWithFile(absolutePath);
350
+ }
351
+ if (globInputPaths && isGlobPattern(pattern)) {
352
+ return this._iterateFilesWithGlob(pattern, isDot);
353
+ }
354
+
355
+ return [];
356
+ }
357
+
358
+ /**
359
+ * Iterate a file which is matched by a given path.
360
+ * @param {string} filePath The path to the target file.
361
+ * @returns {IterableIterator<FileEntry>} The found files.
362
+ * @private
363
+ */
364
+ _iterateFilesWithFile(filePath) {
365
+ debug(`File: ${filePath}`);
366
+
367
+ const { configArrayFactory } = internalSlotsMap.get(this);
368
+ const config = configArrayFactory.getConfigArrayForFile(filePath);
369
+ const ignored = this._isIgnoredFile(filePath, { config, direct: true });
370
+ const flag = ignored ? IGNORED : NONE;
371
+
372
+ return [{ config, filePath, flag }];
373
+ }
374
+
375
+ /**
376
+ * Iterate files in a given path.
377
+ * @param {string} directoryPath The path to the target directory.
378
+ * @param {boolean} dotfiles If `true` then it doesn't skip dot files by default.
379
+ * @returns {IterableIterator<FileEntry>} The found files.
380
+ * @private
381
+ */
382
+ _iterateFilesWithDirectory(directoryPath, dotfiles) {
383
+ debug(`Directory: ${directoryPath}`);
384
+
385
+ return this._iterateFilesRecursive(
386
+ directoryPath,
387
+ { dotfiles, recursive: true, selector: null }
388
+ );
389
+ }
390
+
391
+ /**
392
+ * Iterate files which are matched by a given glob pattern.
393
+ * @param {string} pattern The glob pattern to iterate files.
394
+ * @param {boolean} dotfiles If `true` then it doesn't skip dot files by default.
395
+ * @returns {IterableIterator<FileEntry>} The found files.
396
+ * @private
397
+ */
398
+ _iterateFilesWithGlob(pattern, dotfiles) {
399
+ debug(`Glob: ${pattern}`);
400
+
401
+ const { cwd } = internalSlotsMap.get(this);
402
+ const directoryPath = path.resolve(cwd, getGlobParent(pattern));
403
+ const absolutePath = path.resolve(cwd, pattern);
404
+ const globPart = absolutePath.slice(directoryPath.length + 1);
405
+
406
+ /*
407
+ * recursive if there are `**` or path separators in the glob part.
408
+ * Otherwise, patterns such as `src/*.js`, it doesn't need recursive.
409
+ */
410
+ const recursive = /\*\*|\/|\\/u.test(globPart);
411
+ const selector = new Minimatch(absolutePath, minimatchOpts);
412
+
413
+ debug(`recursive? ${recursive}`);
414
+
415
+ return this._iterateFilesRecursive(
416
+ directoryPath,
417
+ { dotfiles, recursive, selector }
418
+ );
419
+ }
420
+
421
+ /**
422
+ * Iterate files in a given path.
423
+ * @param {string} directoryPath The path to the target directory.
424
+ * @param {Object} options The options to iterate files.
425
+ * @param {boolean} [options.dotfiles] If `true` then it doesn't skip dot files by default.
426
+ * @param {boolean} [options.recursive] If `true` then it dives into sub directories.
427
+ * @param {InstanceType<Minimatch>} [options.selector] The matcher to choose files.
428
+ * @returns {IterableIterator<FileEntry>} The found files.
429
+ * @private
430
+ */
431
+ *_iterateFilesRecursive(directoryPath, options) {
432
+ debug(`Enter the directory: ${directoryPath}`);
433
+ const { configArrayFactory } = internalSlotsMap.get(this);
434
+
435
+ /** @type {ConfigArray|null} */
436
+ let config = null;
437
+
438
+ // Enumerate the files of this directory.
439
+ for (const entry of readdirSafeSync(directoryPath)) {
440
+ const filePath = path.join(directoryPath, entry.name);
441
+ const fileInfo = entry.isSymbolicLink() ? statSafeSync(filePath) : entry;
442
+
443
+ if (!fileInfo) {
444
+ continue;
445
+ }
446
+
447
+ // Check if the file is matched.
448
+ if (fileInfo.isFile()) {
449
+ if (!config) {
450
+ config = configArrayFactory.getConfigArrayForFile(
451
+ filePath,
452
+
453
+ /*
454
+ * We must ignore `ConfigurationNotFoundError` at this
455
+ * point because we don't know if target files exist in
456
+ * this directory.
457
+ */
458
+ { ignoreNotFoundError: true }
459
+ );
460
+ }
461
+ const matched = options.selector
462
+
463
+ // Started with a glob pattern; choose by the pattern.
464
+ ? options.selector.match(filePath)
465
+
466
+ // Started with a directory path; choose by file extensions.
467
+ : this.isTargetPath(filePath, config);
468
+
469
+ if (matched) {
470
+ const ignored = this._isIgnoredFile(filePath, { ...options, config });
471
+ const flag = ignored ? IGNORED_SILENTLY : NONE;
472
+
473
+ debug(`Yield: ${entry.name}${ignored ? " but ignored" : ""}`);
474
+ yield {
475
+ config: configArrayFactory.getConfigArrayForFile(filePath),
476
+ filePath,
477
+ flag
478
+ };
479
+ } else {
480
+ debug(`Didn't match: ${entry.name}`);
481
+ }
482
+
483
+ // Dive into the sub directory.
484
+ } else if (options.recursive && fileInfo.isDirectory()) {
485
+ if (!config) {
486
+ config = configArrayFactory.getConfigArrayForFile(
487
+ filePath,
488
+ { ignoreNotFoundError: true }
489
+ );
490
+ }
491
+ const ignored = this._isIgnoredFile(
492
+ filePath + path.sep,
493
+ { ...options, config }
494
+ );
495
+
496
+ if (!ignored) {
497
+ yield* this._iterateFilesRecursive(filePath, options);
498
+ }
499
+ }
500
+ }
501
+
502
+ debug(`Leave the directory: ${directoryPath}`);
503
+ }
504
+
505
+ /**
506
+ * Check if a given file should be ignored.
507
+ * @param {string} filePath The path to a file to check.
508
+ * @param {Object} options Options
509
+ * @param {ConfigArray} [options.config] The config for this file.
510
+ * @param {boolean} [options.dotfiles] If `true` then this is not ignore dot files by default.
511
+ * @param {boolean} [options.direct] If `true` then this is a direct specified file.
512
+ * @returns {boolean} `true` if the file should be ignored.
513
+ * @private
514
+ */
515
+ _isIgnoredFile(filePath, {
516
+ config: providedConfig,
517
+ dotfiles = false,
518
+ direct = false
519
+ }) {
520
+ const {
521
+ configArrayFactory,
522
+ defaultIgnores,
523
+ ignoreFlag
524
+ } = internalSlotsMap.get(this);
525
+
526
+ if (ignoreFlag) {
527
+ const config =
528
+ providedConfig ||
529
+ configArrayFactory.getConfigArrayForFile(
530
+ filePath,
531
+ { ignoreNotFoundError: true }
532
+ );
533
+ const ignores =
534
+ config.extractConfig(filePath).ignores || defaultIgnores;
535
+
536
+ return ignores(filePath, dotfiles);
537
+ }
538
+
539
+ return !direct && defaultIgnores(filePath, dotfiles);
540
+ }
541
+ }
542
+
543
+ //------------------------------------------------------------------------------
544
+ // Public Interface
545
+ //------------------------------------------------------------------------------
546
+
547
+ module.exports = { FileEnumerator };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/checkstyle.js ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview CheckStyle XML reporter
3
+ * @author Ian Christian Myers
4
+ */
5
+ "use strict";
6
+
7
+ const xmlEscape = require("../xml-escape");
8
+
9
+ //------------------------------------------------------------------------------
10
+ // Helper Functions
11
+ //------------------------------------------------------------------------------
12
+
13
+ /**
14
+ * Returns the severity of warning or error
15
+ * @param {Object} message message object to examine
16
+ * @returns {string} severity level
17
+ * @private
18
+ */
19
+ function getMessageType(message) {
20
+ if (message.fatal || message.severity === 2) {
21
+ return "error";
22
+ }
23
+ return "warning";
24
+
25
+ }
26
+
27
+ //------------------------------------------------------------------------------
28
+ // Public Interface
29
+ //------------------------------------------------------------------------------
30
+
31
+ module.exports = function(results) {
32
+
33
+ let output = "";
34
+
35
+ output += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
36
+ output += "<checkstyle version=\"4.3\">";
37
+
38
+ results.forEach(result => {
39
+ const messages = result.messages;
40
+
41
+ output += `<file name="${xmlEscape(result.filePath)}">`;
42
+
43
+ messages.forEach(message => {
44
+ output += [
45
+ `<error line="${xmlEscape(message.line || 0)}"`,
46
+ `column="${xmlEscape(message.column || 0)}"`,
47
+ `severity="${xmlEscape(getMessageType(message))}"`,
48
+ `message="${xmlEscape(message.message)}${message.ruleId ? ` (${message.ruleId})` : ""}"`,
49
+ `source="${message.ruleId ? xmlEscape(`eslint.rules.${message.ruleId}`) : ""}" />`
50
+ ].join(" ");
51
+ });
52
+
53
+ output += "</file>";
54
+
55
+ });
56
+
57
+ output += "</checkstyle>";
58
+
59
+ return output;
60
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/compact.js ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Compact reporter
3
+ * @author Nicholas C. Zakas
4
+ */
5
+ "use strict";
6
+
7
+ //------------------------------------------------------------------------------
8
+ // Helper Functions
9
+ //------------------------------------------------------------------------------
10
+
11
+ /**
12
+ * Returns the severity of warning or error
13
+ * @param {Object} message message object to examine
14
+ * @returns {string} severity level
15
+ * @private
16
+ */
17
+ function getMessageType(message) {
18
+ if (message.fatal || message.severity === 2) {
19
+ return "Error";
20
+ }
21
+ return "Warning";
22
+
23
+ }
24
+
25
+
26
+ //------------------------------------------------------------------------------
27
+ // Public Interface
28
+ //------------------------------------------------------------------------------
29
+
30
+ module.exports = function(results) {
31
+
32
+ let output = "",
33
+ total = 0;
34
+
35
+ results.forEach(result => {
36
+
37
+ const messages = result.messages;
38
+
39
+ total += messages.length;
40
+
41
+ messages.forEach(message => {
42
+
43
+ output += `${result.filePath}: `;
44
+ output += `line ${message.line || 0}`;
45
+ output += `, col ${message.column || 0}`;
46
+ output += `, ${getMessageType(message)}`;
47
+ output += ` - ${message.message}`;
48
+ output += message.ruleId ? ` (${message.ruleId})` : "";
49
+ output += "\n";
50
+
51
+ });
52
+
53
+ });
54
+
55
+ if (total > 0) {
56
+ output += `\n${total} problem${total !== 1 ? "s" : ""}`;
57
+ }
58
+
59
+ return output;
60
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/formatters-meta.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "name": "checkstyle",
4
+ "description": "Outputs results to the [Checkstyle](https://checkstyle.sourceforge.io/) format."
5
+ },
6
+ {
7
+ "name": "compact",
8
+ "description": "Human-readable output format. Mimics the default output of JSHint."
9
+ },
10
+ {
11
+ "name": "html",
12
+ "description": "Outputs results to HTML. The `html` formatter is useful for visual presentation in the browser."
13
+ },
14
+ {
15
+ "name": "jslint-xml",
16
+ "description": "Outputs results to format compatible with the [JSLint Jenkins plugin](https://plugins.jenkins.io/jslint/)."
17
+ },
18
+ {
19
+ "name": "json-with-metadata",
20
+ "description": "Outputs JSON-serialized results. The `json-with-metadata` provides the same linting results as the [`json`](#json) formatter with additional metadata about the rules applied. The linting results are included in the `results` property and the rules metadata is included in the `metadata` property.\n\nAlternatively, you can use the [ESLint Node.js API](../../integrate/nodejs-api) to programmatically use ESLint."
21
+ },
22
+ {
23
+ "name": "json",
24
+ "description": "Outputs JSON-serialized results. The `json` formatter is useful when you want to programmatically work with the CLI's linting results.\n\nAlternatively, you can use the [ESLint Node.js API](../../integrate/nodejs-api) to programmatically use ESLint."
25
+ },
26
+ {
27
+ "name": "junit",
28
+ "description": "Outputs results to format compatible with the [JUnit Jenkins plugin](https://plugins.jenkins.io/junit/)."
29
+ },
30
+ {
31
+ "name": "stylish",
32
+ "description": "Human-readable output format. This is the default formatter."
33
+ },
34
+ {
35
+ "name": "tap",
36
+ "description": "Outputs results to the [Test Anything Protocol (TAP)](https://testanything.org/) specification format."
37
+ },
38
+ {
39
+ "name": "unix",
40
+ "description": "Outputs results to a format similar to many commands in UNIX-like systems. Parsable with tools such as [grep](https://www.gnu.org/software/grep/manual/grep.html), [sed](https://www.gnu.org/software/sed/manual/sed.html), and [awk](https://www.gnu.org/software/gawk/manual/gawk.html)."
41
+ },
42
+ {
43
+ "name": "visualstudio",
44
+ "description": "Outputs results to format compatible with the integrated terminal of the [Visual Studio](https://visualstudio.microsoft.com/) IDE. When using Visual Studio, you can click on the linting results in the integrated terminal to go to the issue in the source code."
45
+ }
46
+ ]
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/html.js ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview HTML reporter
3
+ * @author Julian Laval
4
+ */
5
+ "use strict";
6
+
7
+ //------------------------------------------------------------------------------
8
+ // Helpers
9
+ //------------------------------------------------------------------------------
10
+
11
+ const encodeHTML = (function() {
12
+ const encodeHTMLRules = {
13
+ "&": "&#38;",
14
+ "<": "&#60;",
15
+ ">": "&#62;",
16
+ '"': "&#34;",
17
+ "'": "&#39;"
18
+ };
19
+ const matchHTML = /[&<>"']/ug;
20
+
21
+ return function(code) {
22
+ return code
23
+ ? code.toString().replace(matchHTML, m => encodeHTMLRules[m] || m)
24
+ : "";
25
+ };
26
+ }());
27
+
28
+ /**
29
+ * Get the final HTML document.
30
+ * @param {Object} it data for the document.
31
+ * @returns {string} HTML document.
32
+ */
33
+ function pageTemplate(it) {
34
+ const { reportColor, reportSummary, date, results } = it;
35
+
36
+ return `
37
+ <!DOCTYPE html>
38
+ <html>
39
+ <head>
40
+ <meta charset="UTF-8">
41
+ <title>ESLint Report</title>
42
+ <link rel="icon" type="image/png" sizes="any" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAHaAAAB2gGFomX7AAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAABD1JREFUWMPFl11sk2UUx3/nbYtjxS1MF7MLMTECMgSTtSSyrQkLhAj7UBPnDSEGoxegGzMwojhXVpmTAA5iYpSoMQa8GBhFOrMFk03buei6yRAlcmOM0SEmU9d90b19jxcM1o5+sGnsc/e+z/l6ztf/HFFVMnns6QieeOCHBePGsHM+wrOtvLG2C4WRVDSSygNV7sCjlspxwDnPB44aols/DXk+mbMBmx/6OseITF1CuOtfevkPh2Uu+/jbdX8lujSScRlT5r7/QDlAfsRmfzmpnkQ/H3H13gf6bBrBn1uqK8WylgEnU8eZmk1repbfchJG1TyKyIKEwuBHFd3lD3naY3O1siiwXsVoBV2VgM1ht/QQUJk2ByqKghsQziYQ8ifKgexIXmuyzC4r67Y7R+xPAfuB/Nn3Cpva+0s7khpQVtZtd4bt51BWxtBYAiciprG7c7D4SixzU9PYalDL6110Ifb/w8W9eY7JqFeFHbO8fPGyLHwwFHJNJTSgwtVTB9oaw9BlQ+tO93vOxypoaQnfEYlI43SeCHDC4TDq9+51/h5fxr33q0ZfV9g04wat9Q943rjJgCp3952W2i8Bi6eDvdsfKj0cK/DYMRyXL4/sUJUmIHd2zYMezsvLaamp4WpcWN3BXSiHpuMwbGbZlnZ8tXY4rgosy+G7oRwQ0cAsd28YGgqfU5UjCZQDLALxDg+Hv/P5Rqvj4hwrS8izXzWb4spwc1GgENFnkpWRzxeuB+ssUHgLdb9UVdt8vpGdKQpze7n7y1U3DBChNRUuqOo9c+0+qpKKxyZqtAIYla7gY4JszAAQri93BSsMRZoyBcUC+w3Q3AyOA4sNhAOZ0q7Iq0b2vUNvK5zPgP+/H8+Zetdoa6uOikhdGurxebwvJY8Iz3V1rTMNAH+opEuQj5KTT/qA1yC+wyUjBm12OidaUtCcPNNX2h0Hx2JG69VulANZAJZJwfU7rzd/FHixuXniTdM0m4GtSQT7bTartqEh9yfImUEzkwKZmTwmo5a5JwkYBfcDL01/RkR5y8iWhtPBknB8ZxwtU9UjwOrrKCeizzc25nTGg1F/turEHoU9wMLpDvWKf8DTmNCAKnd/tqUTF4ElMXJ+A5rWDJS+41WsGWzALhJ+ErBWrLj9g+pqojHxlXJX8HGUg0BsR/x1yhxf3jm4cSzpQFLp6tmi6PEE7g1ZhtZ91ufpSZUAFa6gC+UoQslNaSmypT1U8mHKiUgEKS8KfgF4EpYunFI16tsHin+OG0LcgQK7yj7g6cSzpva2D3hKVNG0Y3mVO1BkqfSlmJrHBQ4uvM12gJHc6ETW8HZVfMRmXvyxxNC1Z/o839zyXlDuCr4nsC11J+MXueaVJWn6yPv+/pJtc9oLTNN4AeTvNGByd3rlhE2x9s5pLwDoHCy+grDzWmOZ95lUtLYj5Bma126Y8eX0/zj/ADxGyViSg4BXAAAAAElFTkSuQmCC">
43
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PScwIDAgMjk0LjgyNSAyNTguOTgyJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnPg0KPHBhdGggZmlsbD0nIzgwODBGMicgZD0nTTk3LjAyMSw5OS4wMTZsNDguNDMyLTI3Ljk2MmMxLjIxMi0wLjcsMi43MDYtMC43LDMuOTE4LDBsNDguNDMzLDI3Ljk2MiBjMS4yMTEsMC43LDEuOTU5LDEuOTkzLDEuOTU5LDMuMzkzdjU1LjkyNGMwLDEuMzk5LTAuNzQ4LDIuNjkzLTEuOTU5LDMuMzk0bC00OC40MzMsMjcuOTYyYy0xLjIxMiwwLjctMi43MDYsMC43LTMuOTE4LDAgbC00OC40MzItMjcuOTYyYy0xLjIxMi0wLjctMS45NTktMS45OTQtMS45NTktMy4zOTR2LTU1LjkyNEM5NS4wNjMsMTAxLjAwOSw5NS44MSw5OS43MTYsOTcuMDIxLDk5LjAxNicvPg0KPHBhdGggZmlsbD0nIzRCMzJDMycgZD0nTTI3My4zMzYsMTI0LjQ4OEwyMTUuNDY5LDIzLjgxNmMtMi4xMDItMy42NC01Ljk4NS02LjMyNS0xMC4xODgtNi4zMjVIODkuNTQ1IGMtNC4yMDQsMC04LjA4OCwyLjY4NS0xMC4xOSw2LjMyNWwtNTcuODY3LDEwMC40NWMtMi4xMDIsMy42NDEtMi4xMDIsOC4yMzYsMCwxMS44NzdsNTcuODY3LDk5Ljg0NyBjMi4xMDIsMy42NCw1Ljk4Niw1LjUwMSwxMC4xOSw1LjUwMWgxMTUuNzM1YzQuMjAzLDAsOC4wODctMS44MDUsMTAuMTg4LTUuNDQ2bDU3Ljg2Ny0xMDAuMDEgQzI3NS40MzksMTMyLjM5NiwyNzUuNDM5LDEyOC4xMjgsMjczLjMzNiwxMjQuNDg4IE0yMjUuNDE5LDE3Mi44OThjMCwxLjQ4LTAuODkxLDIuODQ5LTIuMTc0LDMuNTlsLTczLjcxLDQyLjUyNyBjLTEuMjgyLDAuNzQtMi44ODgsMC43NC00LjE3LDBsLTczLjc2Ny00Mi41MjdjLTEuMjgyLTAuNzQxLTIuMTc5LTIuMTA5LTIuMTc5LTMuNTlWODcuODQzYzAtMS40ODEsMC44ODQtMi44NDksMi4xNjctMy41OSBsNzMuNzA3LTQyLjUyN2MxLjI4Mi0wLjc0MSwyLjg4Ni0wLjc0MSw0LjE2OCwwbDczLjc3Miw0Mi41MjdjMS4yODMsMC43NDEsMi4xODYsMi4xMDksMi4xODYsMy41OVYxNzIuODk4eicvPg0KPC9zdmc+">
44
+ <style>
45
+ body {
46
+ font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
47
+ font-size: 16px;
48
+ font-weight: normal;
49
+ margin: 0;
50
+ padding: 0;
51
+ color: #333;
52
+ }
53
+
54
+ #overview {
55
+ padding: 20px 30px;
56
+ }
57
+
58
+ td,
59
+ th {
60
+ padding: 5px 10px;
61
+ }
62
+
63
+ h1 {
64
+ margin: 0;
65
+ }
66
+
67
+ table {
68
+ margin: 30px;
69
+ width: calc(100% - 60px);
70
+ max-width: 1000px;
71
+ border-radius: 5px;
72
+ border: 1px solid #ddd;
73
+ border-spacing: 0;
74
+ }
75
+
76
+ th {
77
+ font-weight: 400;
78
+ font-size: medium;
79
+ text-align: left;
80
+ cursor: pointer;
81
+ }
82
+
83
+ td.clr-1,
84
+ td.clr-2,
85
+ th span {
86
+ font-weight: 700;
87
+ }
88
+
89
+ th span {
90
+ float: right;
91
+ margin-left: 20px;
92
+ }
93
+
94
+ th span::after {
95
+ content: "";
96
+ clear: both;
97
+ display: block;
98
+ }
99
+
100
+ tr:last-child td {
101
+ border-bottom: none;
102
+ }
103
+
104
+ tr td:first-child,
105
+ tr td:last-child {
106
+ color: #9da0a4;
107
+ }
108
+
109
+ #overview.bg-0,
110
+ tr.bg-0 th {
111
+ color: #468847;
112
+ background: #dff0d8;
113
+ border-bottom: 1px solid #d6e9c6;
114
+ }
115
+
116
+ #overview.bg-1,
117
+ tr.bg-1 th {
118
+ color: #f0ad4e;
119
+ background: #fcf8e3;
120
+ border-bottom: 1px solid #fbeed5;
121
+ }
122
+
123
+ #overview.bg-2,
124
+ tr.bg-2 th {
125
+ color: #b94a48;
126
+ background: #f2dede;
127
+ border-bottom: 1px solid #eed3d7;
128
+ }
129
+
130
+ td {
131
+ border-bottom: 1px solid #ddd;
132
+ }
133
+
134
+ td.clr-1 {
135
+ color: #f0ad4e;
136
+ }
137
+
138
+ td.clr-2 {
139
+ color: #b94a48;
140
+ }
141
+
142
+ td a {
143
+ color: #3a33d1;
144
+ text-decoration: none;
145
+ }
146
+
147
+ td a:hover {
148
+ color: #272296;
149
+ text-decoration: underline;
150
+ }
151
+ </style>
152
+ </head>
153
+ <body>
154
+ <div id="overview" class="bg-${reportColor}">
155
+ <h1>ESLint Report</h1>
156
+ <div>
157
+ <span>${reportSummary}</span> - Generated on ${date}
158
+ </div>
159
+ </div>
160
+ <table>
161
+ <tbody>
162
+ ${results}
163
+ </tbody>
164
+ </table>
165
+ <script type="text/javascript">
166
+ var groups = document.querySelectorAll("tr[data-group]");
167
+ for (i = 0; i < groups.length; i++) {
168
+ groups[i].addEventListener("click", function() {
169
+ var inGroup = document.getElementsByClassName(this.getAttribute("data-group"));
170
+ this.innerHTML = (this.innerHTML.indexOf("+") > -1) ? this.innerHTML.replace("+", "-") : this.innerHTML.replace("-", "+");
171
+ for (var j = 0; j < inGroup.length; j++) {
172
+ inGroup[j].style.display = (inGroup[j].style.display !== "none") ? "none" : "table-row";
173
+ }
174
+ });
175
+ }
176
+ </script>
177
+ </body>
178
+ </html>
179
+ `.trimStart();
180
+ }
181
+
182
+ /**
183
+ * Given a word and a count, append an s if count is not one.
184
+ * @param {string} word A word in its singular form.
185
+ * @param {int} count A number controlling whether word should be pluralized.
186
+ * @returns {string} The original word with an s on the end if count is not one.
187
+ */
188
+ function pluralize(word, count) {
189
+ return (count === 1 ? word : `${word}s`);
190
+ }
191
+
192
+ /**
193
+ * Renders text along the template of x problems (x errors, x warnings)
194
+ * @param {string} totalErrors Total errors
195
+ * @param {string} totalWarnings Total warnings
196
+ * @returns {string} The formatted string, pluralized where necessary
197
+ */
198
+ function renderSummary(totalErrors, totalWarnings) {
199
+ const totalProblems = totalErrors + totalWarnings;
200
+ let renderedText = `${totalProblems} ${pluralize("problem", totalProblems)}`;
201
+
202
+ if (totalProblems !== 0) {
203
+ renderedText += ` (${totalErrors} ${pluralize("error", totalErrors)}, ${totalWarnings} ${pluralize("warning", totalWarnings)})`;
204
+ }
205
+ return renderedText;
206
+ }
207
+
208
+ /**
209
+ * Get the color based on whether there are errors/warnings...
210
+ * @param {string} totalErrors Total errors
211
+ * @param {string} totalWarnings Total warnings
212
+ * @returns {int} The color code (0 = green, 1 = yellow, 2 = red)
213
+ */
214
+ function renderColor(totalErrors, totalWarnings) {
215
+ if (totalErrors !== 0) {
216
+ return 2;
217
+ }
218
+ if (totalWarnings !== 0) {
219
+ return 1;
220
+ }
221
+ return 0;
222
+ }
223
+
224
+ /**
225
+ * Get HTML (table row) describing a single message.
226
+ * @param {Object} it data for the message.
227
+ * @returns {string} HTML (table row) describing the message.
228
+ */
229
+ function messageTemplate(it) {
230
+ const {
231
+ parentIndex,
232
+ lineNumber,
233
+ columnNumber,
234
+ severityNumber,
235
+ severityName,
236
+ message,
237
+ ruleUrl,
238
+ ruleId
239
+ } = it;
240
+
241
+ return `
242
+ <tr style="display: none;" class="f-${parentIndex}">
243
+ <td>${lineNumber}:${columnNumber}</td>
244
+ <td class="clr-${severityNumber}">${severityName}</td>
245
+ <td>${encodeHTML(message)}</td>
246
+ <td>
247
+ <a href="${ruleUrl ? ruleUrl : ""}" target="_blank" rel="noopener noreferrer">${ruleId ? ruleId : ""}</a>
248
+ </td>
249
+ </tr>
250
+ `.trimStart();
251
+ }
252
+
253
+ /**
254
+ * Get HTML (table rows) describing the messages.
255
+ * @param {Array} messages Messages.
256
+ * @param {int} parentIndex Index of the parent HTML row.
257
+ * @param {Object} rulesMeta Dictionary containing metadata for each rule executed by the analysis.
258
+ * @returns {string} HTML (table rows) describing the messages.
259
+ */
260
+ function renderMessages(messages, parentIndex, rulesMeta) {
261
+
262
+ /**
263
+ * Get HTML (table row) describing a message.
264
+ * @param {Object} message Message.
265
+ * @returns {string} HTML (table row) describing a message.
266
+ */
267
+ return messages.map(message => {
268
+ const lineNumber = message.line || 0;
269
+ const columnNumber = message.column || 0;
270
+ let ruleUrl;
271
+
272
+ if (rulesMeta) {
273
+ const meta = rulesMeta[message.ruleId];
274
+
275
+ if (meta && meta.docs && meta.docs.url) {
276
+ ruleUrl = meta.docs.url;
277
+ }
278
+ }
279
+
280
+ return messageTemplate({
281
+ parentIndex,
282
+ lineNumber,
283
+ columnNumber,
284
+ severityNumber: message.severity,
285
+ severityName: message.severity === 1 ? "Warning" : "Error",
286
+ message: message.message,
287
+ ruleId: message.ruleId,
288
+ ruleUrl
289
+ });
290
+ }).join("\n");
291
+ }
292
+
293
+ /**
294
+ * Get HTML (table row) describing the result for a single file.
295
+ * @param {Object} it data for the file.
296
+ * @returns {string} HTML (table row) describing the result for the file.
297
+ */
298
+ function resultTemplate(it) {
299
+ const { color, index, filePath, summary } = it;
300
+
301
+ return `
302
+ <tr class="bg-${color}" data-group="f-${index}">
303
+ <th colspan="4">
304
+ [+] ${encodeHTML(filePath)}
305
+ <span>${encodeHTML(summary)}</span>
306
+ </th>
307
+ </tr>
308
+ `.trimStart();
309
+ }
310
+
311
+ /**
312
+ * Render the results.
313
+ * @param {Array} results Test results.
314
+ * @param {Object} rulesMeta Dictionary containing metadata for each rule executed by the analysis.
315
+ * @returns {string} HTML string describing the results.
316
+ */
317
+ function renderResults(results, rulesMeta) {
318
+ return results.map((result, index) => resultTemplate({
319
+ index,
320
+ color: renderColor(result.errorCount, result.warningCount),
321
+ filePath: result.filePath,
322
+ summary: renderSummary(result.errorCount, result.warningCount)
323
+ }) + renderMessages(result.messages, index, rulesMeta)).join("\n");
324
+ }
325
+
326
+ //------------------------------------------------------------------------------
327
+ // Public Interface
328
+ //------------------------------------------------------------------------------
329
+
330
+ module.exports = function(results, data) {
331
+ let totalErrors,
332
+ totalWarnings;
333
+
334
+ const metaData = data ? data.rulesMeta : {};
335
+
336
+ totalErrors = 0;
337
+ totalWarnings = 0;
338
+
339
+ // Iterate over results to get totals
340
+ results.forEach(result => {
341
+ totalErrors += result.errorCount;
342
+ totalWarnings += result.warningCount;
343
+ });
344
+
345
+ return pageTemplate({
346
+ date: new Date(),
347
+ reportColor: renderColor(totalErrors, totalWarnings),
348
+ reportSummary: renderSummary(totalErrors, totalWarnings),
349
+ results: renderResults(results, metaData)
350
+ });
351
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/jslint-xml.js ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview JSLint XML reporter
3
+ * @author Ian Christian Myers
4
+ */
5
+ "use strict";
6
+
7
+ const xmlEscape = require("../xml-escape");
8
+
9
+ //------------------------------------------------------------------------------
10
+ // Public Interface
11
+ //------------------------------------------------------------------------------
12
+
13
+ module.exports = function(results) {
14
+
15
+ let output = "";
16
+
17
+ output += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
18
+ output += "<jslint>";
19
+
20
+ results.forEach(result => {
21
+ const messages = result.messages;
22
+
23
+ output += `<file name="${result.filePath}">`;
24
+
25
+ messages.forEach(message => {
26
+ output += [
27
+ `<issue line="${message.line}"`,
28
+ `char="${message.column}"`,
29
+ `evidence="${xmlEscape(message.source || "")}"`,
30
+ `reason="${xmlEscape(message.message || "")}${message.ruleId ? ` (${message.ruleId})` : ""}" />`
31
+ ].join(" ");
32
+ });
33
+
34
+ output += "</file>";
35
+
36
+ });
37
+
38
+ output += "</jslint>";
39
+
40
+ return output;
41
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/json-with-metadata.js ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview JSON reporter, including rules metadata
3
+ * @author Chris Meyer
4
+ */
5
+ "use strict";
6
+
7
+ //------------------------------------------------------------------------------
8
+ // Public Interface
9
+ //------------------------------------------------------------------------------
10
+
11
+ module.exports = function(results, data) {
12
+ return JSON.stringify({
13
+ results,
14
+ metadata: data
15
+ });
16
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/json.js ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview JSON reporter
3
+ * @author Burak Yigit Kaya aka BYK
4
+ */
5
+ "use strict";
6
+
7
+ //------------------------------------------------------------------------------
8
+ // Public Interface
9
+ //------------------------------------------------------------------------------
10
+
11
+ module.exports = function(results) {
12
+ return JSON.stringify(results);
13
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/junit.js ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview jUnit Reporter
3
+ * @author Jamund Ferguson
4
+ */
5
+ "use strict";
6
+
7
+ const xmlEscape = require("../xml-escape");
8
+ const path = require("path");
9
+
10
+ //------------------------------------------------------------------------------
11
+ // Helper Functions
12
+ //------------------------------------------------------------------------------
13
+
14
+ /**
15
+ * Returns the severity of warning or error
16
+ * @param {Object} message message object to examine
17
+ * @returns {string} severity level
18
+ * @private
19
+ */
20
+ function getMessageType(message) {
21
+ if (message.fatal || message.severity === 2) {
22
+ return "Error";
23
+ }
24
+ return "Warning";
25
+
26
+ }
27
+
28
+ /**
29
+ * Returns a full file path without extension
30
+ * @param {string} filePath input file path
31
+ * @returns {string} file path without extension
32
+ * @private
33
+ */
34
+ function pathWithoutExt(filePath) {
35
+ return path.join(path.dirname(filePath), path.basename(filePath, path.extname(filePath)));
36
+ }
37
+
38
+ //------------------------------------------------------------------------------
39
+ // Public Interface
40
+ //------------------------------------------------------------------------------
41
+
42
+ module.exports = function(results) {
43
+
44
+ let output = "";
45
+
46
+ output += "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
47
+ output += "<testsuites>\n";
48
+
49
+ results.forEach(result => {
50
+
51
+ const messages = result.messages;
52
+ const classname = pathWithoutExt(result.filePath);
53
+
54
+ if (messages.length > 0) {
55
+ output += `<testsuite package="org.eslint" time="0" tests="${messages.length}" errors="${messages.length}" name="${result.filePath}">\n`;
56
+ messages.forEach(message => {
57
+ const type = message.fatal ? "error" : "failure";
58
+
59
+ output += `<testcase time="0" name="org.eslint.${message.ruleId || "unknown"}" classname="${classname}">`;
60
+ output += `<${type} message="${xmlEscape(message.message || "")}">`;
61
+ output += "<![CDATA[";
62
+ output += `line ${message.line || 0}, col `;
63
+ output += `${message.column || 0}, ${getMessageType(message)}`;
64
+ output += ` - ${xmlEscape(message.message || "")}`;
65
+ output += (message.ruleId ? ` (${message.ruleId})` : "");
66
+ output += "]]>";
67
+ output += `</${type}>`;
68
+ output += "</testcase>\n";
69
+ });
70
+ output += "</testsuite>\n";
71
+ } else {
72
+ output += `<testsuite package="org.eslint" time="0" tests="1" errors="0" name="${result.filePath}">\n`;
73
+ output += `<testcase time="0" name="${result.filePath}" classname="${classname}" />\n`;
74
+ output += "</testsuite>\n";
75
+ }
76
+
77
+ });
78
+
79
+ output += "</testsuites>\n";
80
+
81
+ return output;
82
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/stylish.js ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Stylish reporter
3
+ * @author Sindre Sorhus
4
+ */
5
+ "use strict";
6
+
7
+ const chalk = require("chalk"),
8
+ stripAnsi = require("strip-ansi"),
9
+ table = require("text-table");
10
+
11
+ //------------------------------------------------------------------------------
12
+ // Helpers
13
+ //------------------------------------------------------------------------------
14
+
15
+ /**
16
+ * Given a word and a count, append an s if count is not one.
17
+ * @param {string} word A word in its singular form.
18
+ * @param {int} count A number controlling whether word should be pluralized.
19
+ * @returns {string} The original word with an s on the end if count is not one.
20
+ */
21
+ function pluralize(word, count) {
22
+ return (count === 1 ? word : `${word}s`);
23
+ }
24
+
25
+ //------------------------------------------------------------------------------
26
+ // Public Interface
27
+ //------------------------------------------------------------------------------
28
+
29
+ module.exports = function(results) {
30
+
31
+ let output = "\n",
32
+ errorCount = 0,
33
+ warningCount = 0,
34
+ fixableErrorCount = 0,
35
+ fixableWarningCount = 0,
36
+ summaryColor = "yellow";
37
+
38
+ results.forEach(result => {
39
+ const messages = result.messages;
40
+
41
+ if (messages.length === 0) {
42
+ return;
43
+ }
44
+
45
+ errorCount += result.errorCount;
46
+ warningCount += result.warningCount;
47
+ fixableErrorCount += result.fixableErrorCount;
48
+ fixableWarningCount += result.fixableWarningCount;
49
+
50
+ output += `${chalk.underline(result.filePath)}\n`;
51
+
52
+ output += `${table(
53
+ messages.map(message => {
54
+ let messageType;
55
+
56
+ if (message.fatal || message.severity === 2) {
57
+ messageType = chalk.red("error");
58
+ summaryColor = "red";
59
+ } else {
60
+ messageType = chalk.yellow("warning");
61
+ }
62
+
63
+ return [
64
+ "",
65
+ message.line || 0,
66
+ message.column || 0,
67
+ messageType,
68
+ message.message.replace(/([^ ])\.$/u, "$1"),
69
+ chalk.dim(message.ruleId || "")
70
+ ];
71
+ }),
72
+ {
73
+ align: ["", "r", "l"],
74
+ stringLength(str) {
75
+ return stripAnsi(str).length;
76
+ }
77
+ }
78
+ ).split("\n").map(el => el.replace(/(\d+)\s+(\d+)/u, (m, p1, p2) => chalk.dim(`${p1}:${p2}`))).join("\n")}\n\n`;
79
+ });
80
+
81
+ const total = errorCount + warningCount;
82
+
83
+ if (total > 0) {
84
+ output += chalk[summaryColor].bold([
85
+ "\u2716 ", total, pluralize(" problem", total),
86
+ " (", errorCount, pluralize(" error", errorCount), ", ",
87
+ warningCount, pluralize(" warning", warningCount), ")\n"
88
+ ].join(""));
89
+
90
+ if (fixableErrorCount > 0 || fixableWarningCount > 0) {
91
+ output += chalk[summaryColor].bold([
92
+ " ", fixableErrorCount, pluralize(" error", fixableErrorCount), " and ",
93
+ fixableWarningCount, pluralize(" warning", fixableWarningCount),
94
+ " potentially fixable with the `--fix` option.\n"
95
+ ].join(""));
96
+ }
97
+ }
98
+
99
+ // Resets output color, for prevent change on top level
100
+ return total > 0 ? chalk.reset(output) : "";
101
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/tap.js ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview TAP reporter
3
+ * @author Jonathan Kingston
4
+ */
5
+ "use strict";
6
+
7
+ const yaml = require("js-yaml");
8
+
9
+ //------------------------------------------------------------------------------
10
+ // Helper Functions
11
+ //------------------------------------------------------------------------------
12
+
13
+ /**
14
+ * Returns a canonical error level string based upon the error message passed in.
15
+ * @param {Object} message Individual error message provided by eslint
16
+ * @returns {string} Error level string
17
+ */
18
+ function getMessageType(message) {
19
+ if (message.fatal || message.severity === 2) {
20
+ return "error";
21
+ }
22
+ return "warning";
23
+ }
24
+
25
+ /**
26
+ * Takes in a JavaScript object and outputs a TAP diagnostics string
27
+ * @param {Object} diagnostic JavaScript object to be embedded as YAML into output.
28
+ * @returns {string} diagnostics string with YAML embedded - TAP version 13 compliant
29
+ */
30
+ function outputDiagnostics(diagnostic) {
31
+ const prefix = " ";
32
+ let output = `${prefix}---\n`;
33
+
34
+ output += prefix + yaml.dump(diagnostic).split("\n").join(`\n${prefix}`);
35
+ output += "...\n";
36
+ return output;
37
+ }
38
+
39
+ //------------------------------------------------------------------------------
40
+ // Public Interface
41
+ //------------------------------------------------------------------------------
42
+
43
+ module.exports = function(results) {
44
+ let output = `TAP version 13\n1..${results.length}\n`;
45
+
46
+ results.forEach((result, id) => {
47
+ const messages = result.messages;
48
+ let testResult = "ok";
49
+ let diagnostics = {};
50
+
51
+ if (messages.length > 0) {
52
+ messages.forEach(message => {
53
+ const severity = getMessageType(message);
54
+ const diagnostic = {
55
+ message: message.message,
56
+ severity,
57
+ data: {
58
+ line: message.line || 0,
59
+ column: message.column || 0,
60
+ ruleId: message.ruleId || ""
61
+ }
62
+ };
63
+
64
+ // This ensures a warning message is not flagged as error
65
+ if (severity === "error") {
66
+ testResult = "not ok";
67
+ }
68
+
69
+ /*
70
+ * If we have multiple messages place them under a messages key
71
+ * The first error will be logged as message key
72
+ * This is to adhere to TAP 13 loosely defined specification of having a message key
73
+ */
74
+ if ("message" in diagnostics) {
75
+ if (typeof diagnostics.messages === "undefined") {
76
+ diagnostics.messages = [];
77
+ }
78
+ diagnostics.messages.push(diagnostic);
79
+ } else {
80
+ diagnostics = diagnostic;
81
+ }
82
+ });
83
+ }
84
+
85
+ output += `${testResult} ${id + 1} - ${result.filePath}\n`;
86
+
87
+ // If we have an error include diagnostics
88
+ if (messages.length > 0) {
89
+ output += outputDiagnostics(diagnostics);
90
+ }
91
+
92
+ });
93
+
94
+ return output;
95
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/unix.js ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview unix-style formatter.
3
+ * @author oshi-shinobu
4
+ */
5
+ "use strict";
6
+
7
+ //------------------------------------------------------------------------------
8
+ // Helper Functions
9
+ //------------------------------------------------------------------------------
10
+
11
+ /**
12
+ * Returns a canonical error level string based upon the error message passed in.
13
+ * @param {Object} message Individual error message provided by eslint
14
+ * @returns {string} Error level string
15
+ */
16
+ function getMessageType(message) {
17
+ if (message.fatal || message.severity === 2) {
18
+ return "Error";
19
+ }
20
+ return "Warning";
21
+
22
+ }
23
+
24
+
25
+ //------------------------------------------------------------------------------
26
+ // Public Interface
27
+ //------------------------------------------------------------------------------
28
+
29
+ module.exports = function(results) {
30
+
31
+ let output = "",
32
+ total = 0;
33
+
34
+ results.forEach(result => {
35
+
36
+ const messages = result.messages;
37
+
38
+ total += messages.length;
39
+
40
+ messages.forEach(message => {
41
+
42
+ output += `${result.filePath}:`;
43
+ output += `${message.line || 0}:`;
44
+ output += `${message.column || 0}:`;
45
+ output += ` ${message.message} `;
46
+ output += `[${getMessageType(message)}${message.ruleId ? `/${message.ruleId}` : ""}]`;
47
+ output += "\n";
48
+
49
+ });
50
+
51
+ });
52
+
53
+ if (total > 0) {
54
+ output += `\n${total} problem${total !== 1 ? "s" : ""}`;
55
+ }
56
+
57
+ return output;
58
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/formatters/visualstudio.js ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Visual Studio compatible formatter
3
+ * @author Ronald Pijnacker
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //------------------------------------------------------------------------------
9
+ // Helper Functions
10
+ //------------------------------------------------------------------------------
11
+
12
+ /**
13
+ * Returns the severity of warning or error
14
+ * @param {Object} message message object to examine
15
+ * @returns {string} severity level
16
+ * @private
17
+ */
18
+ function getMessageType(message) {
19
+ if (message.fatal || message.severity === 2) {
20
+ return "error";
21
+ }
22
+ return "warning";
23
+
24
+ }
25
+
26
+
27
+ //------------------------------------------------------------------------------
28
+ // Public Interface
29
+ //------------------------------------------------------------------------------
30
+
31
+ module.exports = function(results) {
32
+
33
+ let output = "",
34
+ total = 0;
35
+
36
+ results.forEach(result => {
37
+
38
+ const messages = result.messages;
39
+
40
+ total += messages.length;
41
+
42
+ messages.forEach(message => {
43
+
44
+ output += result.filePath;
45
+ output += `(${message.line || 0}`;
46
+ output += message.column ? `,${message.column}` : "";
47
+ output += `): ${getMessageType(message)}`;
48
+ output += message.ruleId ? ` ${message.ruleId}` : "";
49
+ output += ` : ${message.message}`;
50
+ output += "\n";
51
+
52
+ });
53
+
54
+ });
55
+
56
+ if (total === 0) {
57
+ output += "no problems";
58
+ } else {
59
+ output += `\n${total} problem${total !== 1 ? "s" : ""}`;
60
+ }
61
+
62
+ return output;
63
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/hash.js ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Defining the hashing function in one place.
3
+ * @author Michael Ficarra
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //------------------------------------------------------------------------------
9
+ // Requirements
10
+ //------------------------------------------------------------------------------
11
+
12
+ const murmur = require("imurmurhash");
13
+
14
+ //------------------------------------------------------------------------------
15
+ // Helpers
16
+ //------------------------------------------------------------------------------
17
+
18
+ //------------------------------------------------------------------------------
19
+ // Private
20
+ //------------------------------------------------------------------------------
21
+
22
+ /**
23
+ * hash the given string
24
+ * @param {string} str the string to hash
25
+ * @returns {string} the hash
26
+ */
27
+ function hash(str) {
28
+ return murmur(str).result().toString(36);
29
+ }
30
+
31
+ //------------------------------------------------------------------------------
32
+ // Public Interface
33
+ //------------------------------------------------------------------------------
34
+
35
+ module.exports = hash;
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/index.js ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ "use strict";
2
+
3
+ const { CLIEngine } = require("./cli-engine");
4
+
5
+ module.exports = {
6
+ CLIEngine
7
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/lint-result-cache.js ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Utility for caching lint results.
3
+ * @author Kevin Partington
4
+ */
5
+ "use strict";
6
+
7
+ //-----------------------------------------------------------------------------
8
+ // Requirements
9
+ //-----------------------------------------------------------------------------
10
+
11
+ const assert = require("assert");
12
+ const fs = require("fs");
13
+ const fileEntryCache = require("file-entry-cache");
14
+ const stringify = require("json-stable-stringify-without-jsonify");
15
+ const pkg = require("../../package.json");
16
+ const hash = require("./hash");
17
+
18
+ const debug = require("debug")("eslint:lint-result-cache");
19
+
20
+ //-----------------------------------------------------------------------------
21
+ // Helpers
22
+ //-----------------------------------------------------------------------------
23
+
24
+ const configHashCache = new WeakMap();
25
+ const nodeVersion = process && process.version;
26
+
27
+ const validCacheStrategies = ["metadata", "content"];
28
+ const invalidCacheStrategyErrorMessage = `Cache strategy must be one of: ${validCacheStrategies
29
+ .map(strategy => `"${strategy}"`)
30
+ .join(", ")}`;
31
+
32
+ /**
33
+ * Tests whether a provided cacheStrategy is valid
34
+ * @param {string} cacheStrategy The cache strategy to use
35
+ * @returns {boolean} true if `cacheStrategy` is one of `validCacheStrategies`; false otherwise
36
+ */
37
+ function isValidCacheStrategy(cacheStrategy) {
38
+ return (
39
+ validCacheStrategies.includes(cacheStrategy)
40
+ );
41
+ }
42
+
43
+ /**
44
+ * Calculates the hash of the config
45
+ * @param {ConfigArray} config The config.
46
+ * @returns {string} The hash of the config
47
+ */
48
+ function hashOfConfigFor(config) {
49
+ if (!configHashCache.has(config)) {
50
+ configHashCache.set(config, hash(`${pkg.version}_${nodeVersion}_${stringify(config)}`));
51
+ }
52
+
53
+ return configHashCache.get(config);
54
+ }
55
+
56
+ //-----------------------------------------------------------------------------
57
+ // Public Interface
58
+ //-----------------------------------------------------------------------------
59
+
60
+ /**
61
+ * Lint result cache. This wraps around the file-entry-cache module,
62
+ * transparently removing properties that are difficult or expensive to
63
+ * serialize and adding them back in on retrieval.
64
+ */
65
+ class LintResultCache {
66
+
67
+ /**
68
+ * Creates a new LintResultCache instance.
69
+ * @param {string} cacheFileLocation The cache file location.
70
+ * @param {"metadata" | "content"} cacheStrategy The cache strategy to use.
71
+ */
72
+ constructor(cacheFileLocation, cacheStrategy) {
73
+ assert(cacheFileLocation, "Cache file location is required");
74
+ assert(cacheStrategy, "Cache strategy is required");
75
+ assert(
76
+ isValidCacheStrategy(cacheStrategy),
77
+ invalidCacheStrategyErrorMessage
78
+ );
79
+
80
+ debug(`Caching results to ${cacheFileLocation}`);
81
+
82
+ const useChecksum = cacheStrategy === "content";
83
+
84
+ debug(
85
+ `Using "${cacheStrategy}" strategy to detect changes`
86
+ );
87
+
88
+ this.fileEntryCache = fileEntryCache.create(
89
+ cacheFileLocation,
90
+ void 0,
91
+ useChecksum
92
+ );
93
+ this.cacheFileLocation = cacheFileLocation;
94
+ }
95
+
96
+ /**
97
+ * Retrieve cached lint results for a given file path, if present in the
98
+ * cache. If the file is present and has not been changed, rebuild any
99
+ * missing result information.
100
+ * @param {string} filePath The file for which to retrieve lint results.
101
+ * @param {ConfigArray} config The config of the file.
102
+ * @returns {Object|null} The rebuilt lint results, or null if the file is
103
+ * changed or not in the filesystem.
104
+ */
105
+ getCachedLintResults(filePath, config) {
106
+
107
+ /*
108
+ * Cached lint results are valid if and only if:
109
+ * 1. The file is present in the filesystem
110
+ * 2. The file has not changed since the time it was previously linted
111
+ * 3. The ESLint configuration has not changed since the time the file
112
+ * was previously linted
113
+ * If any of these are not true, we will not reuse the lint results.
114
+ */
115
+ const fileDescriptor = this.fileEntryCache.getFileDescriptor(filePath);
116
+ const hashOfConfig = hashOfConfigFor(config);
117
+ const changed =
118
+ fileDescriptor.changed ||
119
+ fileDescriptor.meta.hashOfConfig !== hashOfConfig;
120
+
121
+ if (fileDescriptor.notFound) {
122
+ debug(`File not found on the file system: ${filePath}`);
123
+ return null;
124
+ }
125
+
126
+ if (changed) {
127
+ debug(`Cache entry not found or no longer valid: ${filePath}`);
128
+ return null;
129
+ }
130
+
131
+ const cachedResults = fileDescriptor.meta.results;
132
+
133
+ // Just in case, not sure if this can ever happen.
134
+ if (!cachedResults) {
135
+ return cachedResults;
136
+ }
137
+
138
+ /*
139
+ * Shallow clone the object to ensure that any properties added or modified afterwards
140
+ * will not be accidentally stored in the cache file when `reconcile()` is called.
141
+ * https://github.com/eslint/eslint/issues/13507
142
+ * All intentional changes to the cache file must be done through `setCachedLintResults()`.
143
+ */
144
+ const results = { ...cachedResults };
145
+
146
+ // If source is present but null, need to reread the file from the filesystem.
147
+ if (results.source === null) {
148
+ debug(`Rereading cached result source from filesystem: ${filePath}`);
149
+ results.source = fs.readFileSync(filePath, "utf-8");
150
+ }
151
+
152
+ return results;
153
+ }
154
+
155
+ /**
156
+ * Set the cached lint results for a given file path, after removing any
157
+ * information that will be both unnecessary and difficult to serialize.
158
+ * Avoids caching results with an "output" property (meaning fixes were
159
+ * applied), to prevent potentially incorrect results if fixes are not
160
+ * written to disk.
161
+ * @param {string} filePath The file for which to set lint results.
162
+ * @param {ConfigArray} config The config of the file.
163
+ * @param {Object} result The lint result to be set for the file.
164
+ * @returns {void}
165
+ */
166
+ setCachedLintResults(filePath, config, result) {
167
+ if (result && Object.prototype.hasOwnProperty.call(result, "output")) {
168
+ return;
169
+ }
170
+
171
+ const fileDescriptor = this.fileEntryCache.getFileDescriptor(filePath);
172
+
173
+ if (fileDescriptor && !fileDescriptor.notFound) {
174
+ debug(`Updating cached result: ${filePath}`);
175
+
176
+ // Serialize the result, except that we want to remove the file source if present.
177
+ const resultToSerialize = Object.assign({}, result);
178
+
179
+ /*
180
+ * Set result.source to null.
181
+ * In `getCachedLintResults`, if source is explicitly null, we will
182
+ * read the file from the filesystem to set the value again.
183
+ */
184
+ if (Object.prototype.hasOwnProperty.call(resultToSerialize, "source")) {
185
+ resultToSerialize.source = null;
186
+ }
187
+
188
+ fileDescriptor.meta.results = resultToSerialize;
189
+ fileDescriptor.meta.hashOfConfig = hashOfConfigFor(config);
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Persists the in-memory cache to disk.
195
+ * @returns {void}
196
+ */
197
+ reconcile() {
198
+ debug(`Persisting cached results: ${this.cacheFileLocation}`);
199
+ this.fileEntryCache.reconcile();
200
+ }
201
+ }
202
+
203
+ module.exports = LintResultCache;
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/load-rules.js ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Module for loading rules from files and directories.
3
+ * @author Michael Ficarra
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //------------------------------------------------------------------------------
9
+ // Requirements
10
+ //------------------------------------------------------------------------------
11
+
12
+ const fs = require("fs"),
13
+ path = require("path");
14
+
15
+ const rulesDirCache = {};
16
+
17
+ //------------------------------------------------------------------------------
18
+ // Public Interface
19
+ //------------------------------------------------------------------------------
20
+
21
+ /**
22
+ * Load all rule modules from specified directory.
23
+ * @param {string} relativeRulesDir Path to rules directory, may be relative.
24
+ * @param {string} cwd Current working directory
25
+ * @returns {Object} Loaded rule modules.
26
+ */
27
+ module.exports = function(relativeRulesDir, cwd) {
28
+ const rulesDir = path.resolve(cwd, relativeRulesDir);
29
+
30
+ // cache will help performance as IO operation are expensive
31
+ if (rulesDirCache[rulesDir]) {
32
+ return rulesDirCache[rulesDir];
33
+ }
34
+
35
+ const rules = Object.create(null);
36
+
37
+ fs.readdirSync(rulesDir).forEach(file => {
38
+ if (path.extname(file) !== ".js") {
39
+ return;
40
+ }
41
+ rules[file.slice(0, -3)] = require(path.join(rulesDir, file));
42
+ });
43
+ rulesDirCache[rulesDir] = rules;
44
+
45
+ return rules;
46
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/cli-engine/xml-escape.js ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview XML character escaper
3
+ * @author George Chung
4
+ */
5
+ "use strict";
6
+
7
+ //------------------------------------------------------------------------------
8
+ // Public Interface
9
+ //------------------------------------------------------------------------------
10
+
11
+ /**
12
+ * Returns the escaped value for a character
13
+ * @param {string} s string to examine
14
+ * @returns {string} severity level
15
+ * @private
16
+ */
17
+ module.exports = function(s) {
18
+ return (`${s}`).replace(/[<>&"'\x00-\x1F\x7F\u0080-\uFFFF]/gu, c => { // eslint-disable-line no-control-regex -- Converting controls to entities
19
+ switch (c) {
20
+ case "<":
21
+ return "&lt;";
22
+ case ">":
23
+ return "&gt;";
24
+ case "&":
25
+ return "&amp;";
26
+ case "\"":
27
+ return "&quot;";
28
+ case "'":
29
+ return "&apos;";
30
+ default:
31
+ return `&#${c.charCodeAt(0)};`;
32
+ }
33
+ });
34
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/config/default-config.js ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Default configuration
3
+ * @author Nicholas C. Zakas
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //-----------------------------------------------------------------------------
9
+ // Requirements
10
+ //-----------------------------------------------------------------------------
11
+
12
+ const Rules = require("../rules");
13
+
14
+ //-----------------------------------------------------------------------------
15
+ // Helpers
16
+ //-----------------------------------------------------------------------------
17
+
18
+ exports.defaultConfig = [
19
+ {
20
+ plugins: {
21
+ "@": {
22
+
23
+ /*
24
+ * Because we try to delay loading rules until absolutely
25
+ * necessary, a proxy allows us to hook into the lazy-loading
26
+ * aspect of the rules map while still keeping all of the
27
+ * relevant configuration inside of the config array.
28
+ */
29
+ rules: new Proxy({}, {
30
+ get(target, property) {
31
+ return Rules.get(property);
32
+ },
33
+
34
+ has(target, property) {
35
+ return Rules.has(property);
36
+ }
37
+ })
38
+ }
39
+ },
40
+ languageOptions: {
41
+ sourceType: "module",
42
+ ecmaVersion: "latest",
43
+ parser: require("espree"),
44
+ parserOptions: {}
45
+ }
46
+ },
47
+
48
+ // default ignores are listed here
49
+ {
50
+ ignores: [
51
+ "**/node_modules/",
52
+ ".git/"
53
+ ]
54
+ },
55
+
56
+ // intentionally empty config to ensure these files are globbed by default
57
+ {
58
+ files: ["**/*.js", "**/*.mjs"]
59
+ },
60
+ {
61
+ files: ["**/*.cjs"],
62
+ languageOptions: {
63
+ sourceType: "commonjs",
64
+ ecmaVersion: "latest"
65
+ }
66
+ }
67
+ ];
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/config/flat-config-array.js ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Flat Config Array
3
+ * @author Nicholas C. Zakas
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //-----------------------------------------------------------------------------
9
+ // Requirements
10
+ //-----------------------------------------------------------------------------
11
+
12
+ const { ConfigArray, ConfigArraySymbol } = require("@humanwhocodes/config-array");
13
+ const { flatConfigSchema } = require("./flat-config-schema");
14
+ const { RuleValidator } = require("./rule-validator");
15
+ const { defaultConfig } = require("./default-config");
16
+ const jsPlugin = require("@eslint/js");
17
+
18
+ //-----------------------------------------------------------------------------
19
+ // Helpers
20
+ //-----------------------------------------------------------------------------
21
+
22
+ /**
23
+ * Fields that are considered metadata and not part of the config object.
24
+ */
25
+ const META_FIELDS = new Set(["name"]);
26
+
27
+ const ruleValidator = new RuleValidator();
28
+
29
+ /**
30
+ * Splits a plugin identifier in the form a/b/c into two parts: a/b and c.
31
+ * @param {string} identifier The identifier to parse.
32
+ * @returns {{objectName: string, pluginName: string}} The parts of the plugin
33
+ * name.
34
+ */
35
+ function splitPluginIdentifier(identifier) {
36
+ const parts = identifier.split("/");
37
+
38
+ return {
39
+ objectName: parts.pop(),
40
+ pluginName: parts.join("/")
41
+ };
42
+ }
43
+
44
+ /**
45
+ * Returns the name of an object in the config by reading its `meta` key.
46
+ * @param {Object} object The object to check.
47
+ * @returns {string?} The name of the object if found or `null` if there
48
+ * is no name.
49
+ */
50
+ function getObjectId(object) {
51
+
52
+ // first check old-style name
53
+ let name = object.name;
54
+
55
+ if (!name) {
56
+
57
+ if (!object.meta) {
58
+ return null;
59
+ }
60
+
61
+ name = object.meta.name;
62
+
63
+ if (!name) {
64
+ return null;
65
+ }
66
+ }
67
+
68
+ // now check for old-style version
69
+ let version = object.version;
70
+
71
+ if (!version) {
72
+ version = object.meta && object.meta.version;
73
+ }
74
+
75
+ // if there's a version then append that
76
+ if (version) {
77
+ return `${name}@${version}`;
78
+ }
79
+
80
+ return name;
81
+ }
82
+
83
+ /**
84
+ * Wraps a config error with details about where the error occurred.
85
+ * @param {Error} error The original error.
86
+ * @param {number} originalLength The original length of the config array.
87
+ * @param {number} baseLength The length of the base config.
88
+ * @returns {TypeError} The new error with details.
89
+ */
90
+ function wrapConfigErrorWithDetails(error, originalLength, baseLength) {
91
+
92
+ let location = "user-defined";
93
+ let configIndex = error.index;
94
+
95
+ /*
96
+ * A config array is set up in this order:
97
+ * 1. Base config
98
+ * 2. Original configs
99
+ * 3. User-defined configs
100
+ * 4. CLI-defined configs
101
+ *
102
+ * So we need to adjust the index to account for the base config.
103
+ *
104
+ * - If the index is less than the base length, it's in the base config
105
+ * (as specified by `baseConfig` argument to `FlatConfigArray` constructor).
106
+ * - If the index is greater than the base length but less than the original
107
+ * length + base length, it's in the original config. The original config
108
+ * is passed to the `FlatConfigArray` constructor as the first argument.
109
+ * - Otherwise, it's in the user-defined config, which is loaded from the
110
+ * config file and merged with any command-line options.
111
+ */
112
+ if (error.index < baseLength) {
113
+ location = "base";
114
+ } else if (error.index < originalLength + baseLength) {
115
+ location = "original";
116
+ configIndex = error.index - baseLength;
117
+ } else {
118
+ configIndex = error.index - originalLength - baseLength;
119
+ }
120
+
121
+ return new TypeError(
122
+ `${error.message.slice(0, -1)} at ${location} index ${configIndex}.`,
123
+ { cause: error }
124
+ );
125
+ }
126
+
127
+ const originalBaseConfig = Symbol("originalBaseConfig");
128
+ const originalLength = Symbol("originalLength");
129
+ const baseLength = Symbol("baseLength");
130
+
131
+ //-----------------------------------------------------------------------------
132
+ // Exports
133
+ //-----------------------------------------------------------------------------
134
+
135
+ /**
136
+ * Represents an array containing configuration information for ESLint.
137
+ */
138
+ class FlatConfigArray extends ConfigArray {
139
+
140
+ /**
141
+ * Creates a new instance.
142
+ * @param {*[]} configs An array of configuration information.
143
+ * @param {{basePath: string, shouldIgnore: boolean, baseConfig: FlatConfig}} options The options
144
+ * to use for the config array instance.
145
+ */
146
+ constructor(configs, {
147
+ basePath,
148
+ shouldIgnore = true,
149
+ baseConfig = defaultConfig
150
+ } = {}) {
151
+ super(configs, {
152
+ basePath,
153
+ schema: flatConfigSchema
154
+ });
155
+
156
+ /**
157
+ * The original length of the array before any modifications.
158
+ * @type {number}
159
+ */
160
+ this[originalLength] = this.length;
161
+
162
+ if (baseConfig[Symbol.iterator]) {
163
+ this.unshift(...baseConfig);
164
+ } else {
165
+ this.unshift(baseConfig);
166
+ }
167
+
168
+ /**
169
+ * The length of the array after applying the base config.
170
+ * @type {number}
171
+ */
172
+ this[baseLength] = this.length - this[originalLength];
173
+
174
+ /**
175
+ * The base config used to build the config array.
176
+ * @type {Array<FlatConfig>}
177
+ */
178
+ this[originalBaseConfig] = baseConfig;
179
+ Object.defineProperty(this, originalBaseConfig, { writable: false });
180
+
181
+ /**
182
+ * Determines if `ignores` fields should be honored.
183
+ * If true, then all `ignores` fields are honored.
184
+ * if false, then only `ignores` fields in the baseConfig are honored.
185
+ * @type {boolean}
186
+ */
187
+ this.shouldIgnore = shouldIgnore;
188
+ Object.defineProperty(this, "shouldIgnore", { writable: false });
189
+ }
190
+
191
+ /**
192
+ * Normalizes the array by calling the superclass method and catching/rethrowing
193
+ * any ConfigError exceptions with additional details.
194
+ * @param {any} [context] The context to use to normalize the array.
195
+ * @returns {Promise<FlatConfigArray>} A promise that resolves when the array is normalized.
196
+ */
197
+ normalize(context) {
198
+ return super.normalize(context)
199
+ .catch(error => {
200
+ if (error.name === "ConfigError") {
201
+ throw wrapConfigErrorWithDetails(error, this[originalLength], this[baseLength]);
202
+ }
203
+
204
+ throw error;
205
+
206
+ });
207
+ }
208
+
209
+ /**
210
+ * Normalizes the array by calling the superclass method and catching/rethrowing
211
+ * any ConfigError exceptions with additional details.
212
+ * @param {any} [context] The context to use to normalize the array.
213
+ * @returns {FlatConfigArray} The current instance.
214
+ * @throws {TypeError} If the config is invalid.
215
+ */
216
+ normalizeSync(context) {
217
+
218
+ try {
219
+
220
+ return super.normalizeSync(context);
221
+
222
+ } catch (error) {
223
+
224
+ if (error.name === "ConfigError") {
225
+ throw wrapConfigErrorWithDetails(error, this[originalLength], this[baseLength]);
226
+ }
227
+
228
+ throw error;
229
+
230
+ }
231
+
232
+ }
233
+
234
+ /* eslint-disable class-methods-use-this -- Desired as instance method */
235
+ /**
236
+ * Replaces a config with another config to allow us to put strings
237
+ * in the config array that will be replaced by objects before
238
+ * normalization.
239
+ * @param {Object} config The config to preprocess.
240
+ * @returns {Object} The preprocessed config.
241
+ */
242
+ [ConfigArraySymbol.preprocessConfig](config) {
243
+ if (config === "eslint:recommended") {
244
+
245
+ // if we are in a Node.js environment warn the user
246
+ if (typeof process !== "undefined" && process.emitWarning) {
247
+ process.emitWarning("The 'eslint:recommended' string configuration is deprecated and will be replaced by the @eslint/js package's 'recommended' config.");
248
+ }
249
+
250
+ return jsPlugin.configs.recommended;
251
+ }
252
+
253
+ if (config === "eslint:all") {
254
+
255
+ // if we are in a Node.js environment warn the user
256
+ if (typeof process !== "undefined" && process.emitWarning) {
257
+ process.emitWarning("The 'eslint:all' string configuration is deprecated and will be replaced by the @eslint/js package's 'all' config.");
258
+ }
259
+
260
+ return jsPlugin.configs.all;
261
+ }
262
+
263
+ /*
264
+ * If a config object has `ignores` and no other non-meta fields, then it's an object
265
+ * for global ignores. If `shouldIgnore` is false, that object shouldn't apply,
266
+ * so we'll remove its `ignores`.
267
+ */
268
+ if (
269
+ !this.shouldIgnore &&
270
+ !this[originalBaseConfig].includes(config) &&
271
+ config.ignores &&
272
+ Object.keys(config).filter(key => !META_FIELDS.has(key)).length === 1
273
+ ) {
274
+ /* eslint-disable-next-line no-unused-vars -- need to strip off other keys */
275
+ const { ignores, ...otherKeys } = config;
276
+
277
+ return otherKeys;
278
+ }
279
+
280
+ return config;
281
+ }
282
+
283
+ /**
284
+ * Finalizes the config by replacing plugin references with their objects
285
+ * and validating rule option schemas.
286
+ * @param {Object} config The config to finalize.
287
+ * @returns {Object} The finalized config.
288
+ * @throws {TypeError} If the config is invalid.
289
+ */
290
+ [ConfigArraySymbol.finalizeConfig](config) {
291
+
292
+ const { plugins, languageOptions, processor } = config;
293
+ let parserName, processorName;
294
+ let invalidParser = false,
295
+ invalidProcessor = false;
296
+
297
+ // Check parser value
298
+ if (languageOptions && languageOptions.parser) {
299
+ const { parser } = languageOptions;
300
+
301
+ if (typeof parser === "object") {
302
+ parserName = getObjectId(parser);
303
+
304
+ if (!parserName) {
305
+ invalidParser = true;
306
+ }
307
+
308
+ } else {
309
+ invalidParser = true;
310
+ }
311
+ }
312
+
313
+ // Check processor value
314
+ if (processor) {
315
+ if (typeof processor === "string") {
316
+ const { pluginName, objectName: localProcessorName } = splitPluginIdentifier(processor);
317
+
318
+ processorName = processor;
319
+
320
+ if (!plugins || !plugins[pluginName] || !plugins[pluginName].processors || !plugins[pluginName].processors[localProcessorName]) {
321
+ throw new TypeError(`Key "processor": Could not find "${localProcessorName}" in plugin "${pluginName}".`);
322
+ }
323
+
324
+ config.processor = plugins[pluginName].processors[localProcessorName];
325
+ } else if (typeof processor === "object") {
326
+ processorName = getObjectId(processor);
327
+
328
+ if (!processorName) {
329
+ invalidProcessor = true;
330
+ }
331
+
332
+ } else {
333
+ invalidProcessor = true;
334
+ }
335
+ }
336
+
337
+ ruleValidator.validate(config);
338
+
339
+ // apply special logic for serialization into JSON
340
+ /* eslint-disable object-shorthand -- shorthand would change "this" value */
341
+ Object.defineProperty(config, "toJSON", {
342
+ value: function() {
343
+
344
+ if (invalidParser) {
345
+ throw new Error("Could not serialize parser object (missing 'meta' object).");
346
+ }
347
+
348
+ if (invalidProcessor) {
349
+ throw new Error("Could not serialize processor object (missing 'meta' object).");
350
+ }
351
+
352
+ return {
353
+ ...this,
354
+ plugins: Object.entries(plugins).map(([namespace, plugin]) => {
355
+
356
+ const pluginId = getObjectId(plugin);
357
+
358
+ if (!pluginId) {
359
+ return namespace;
360
+ }
361
+
362
+ return `${namespace}:${pluginId}`;
363
+ }),
364
+ languageOptions: {
365
+ ...languageOptions,
366
+ parser: parserName
367
+ },
368
+ processor: processorName
369
+ };
370
+ }
371
+ });
372
+ /* eslint-enable object-shorthand -- ok to enable now */
373
+
374
+ return config;
375
+ }
376
+ /* eslint-enable class-methods-use-this -- Desired as instance method */
377
+
378
+ }
379
+
380
+ exports.FlatConfigArray = FlatConfigArray;
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/config/flat-config-helpers.js ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Shared functions to work with configs.
3
+ * @author Nicholas C. Zakas
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //-----------------------------------------------------------------------------
9
+ // Functions
10
+ //-----------------------------------------------------------------------------
11
+
12
+ /**
13
+ * Parses a ruleId into its plugin and rule parts.
14
+ * @param {string} ruleId The rule ID to parse.
15
+ * @returns {{pluginName:string,ruleName:string}} The plugin and rule
16
+ * parts of the ruleId;
17
+ */
18
+ function parseRuleId(ruleId) {
19
+ let pluginName, ruleName;
20
+
21
+ // distinguish between core rules and plugin rules
22
+ if (ruleId.includes("/")) {
23
+
24
+ // mimic scoped npm packages
25
+ if (ruleId.startsWith("@")) {
26
+ pluginName = ruleId.slice(0, ruleId.lastIndexOf("/"));
27
+ } else {
28
+ pluginName = ruleId.slice(0, ruleId.indexOf("/"));
29
+ }
30
+
31
+ ruleName = ruleId.slice(pluginName.length + 1);
32
+ } else {
33
+ pluginName = "@";
34
+ ruleName = ruleId;
35
+ }
36
+
37
+ return {
38
+ pluginName,
39
+ ruleName
40
+ };
41
+ }
42
+
43
+ /**
44
+ * Retrieves a rule instance from a given config based on the ruleId.
45
+ * @param {string} ruleId The rule ID to look for.
46
+ * @param {FlatConfig} config The config to search.
47
+ * @returns {import("../shared/types").Rule|undefined} The rule if found
48
+ * or undefined if not.
49
+ */
50
+ function getRuleFromConfig(ruleId, config) {
51
+
52
+ const { pluginName, ruleName } = parseRuleId(ruleId);
53
+
54
+ const plugin = config.plugins && config.plugins[pluginName];
55
+ let rule = plugin && plugin.rules && plugin.rules[ruleName];
56
+
57
+
58
+ // normalize function rules into objects
59
+ if (rule && typeof rule === "function") {
60
+ rule = {
61
+ create: rule
62
+ };
63
+ }
64
+
65
+ return rule;
66
+ }
67
+
68
+ /**
69
+ * Gets a complete options schema for a rule.
70
+ * @param {{create: Function, schema: (Array|null)}} rule A new-style rule object
71
+ * @returns {Object} JSON Schema for the rule's options.
72
+ */
73
+ function getRuleOptionsSchema(rule) {
74
+
75
+ if (!rule) {
76
+ return null;
77
+ }
78
+
79
+ const schema = rule.schema || rule.meta && rule.meta.schema;
80
+
81
+ if (Array.isArray(schema)) {
82
+ if (schema.length) {
83
+ return {
84
+ type: "array",
85
+ items: schema,
86
+ minItems: 0,
87
+ maxItems: schema.length
88
+ };
89
+ }
90
+ return {
91
+ type: "array",
92
+ minItems: 0,
93
+ maxItems: 0
94
+ };
95
+
96
+ }
97
+
98
+ // Given a full schema, leave it alone
99
+ return schema || null;
100
+ }
101
+
102
+
103
+ //-----------------------------------------------------------------------------
104
+ // Exports
105
+ //-----------------------------------------------------------------------------
106
+
107
+ module.exports = {
108
+ parseRuleId,
109
+ getRuleFromConfig,
110
+ getRuleOptionsSchema
111
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/config/flat-config-schema.js ADDED
@@ -0,0 +1,598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Flat config schema
3
+ * @author Nicholas C. Zakas
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //-----------------------------------------------------------------------------
9
+ // Requirements
10
+ //-----------------------------------------------------------------------------
11
+
12
+ /*
13
+ * Note: This can be removed in ESLint v9 because structuredClone is available globally
14
+ * starting in Node.js v17.
15
+ */
16
+ const structuredClone = require("@ungap/structured-clone").default;
17
+ const { normalizeSeverityToNumber } = require("../shared/severity");
18
+
19
+ //-----------------------------------------------------------------------------
20
+ // Type Definitions
21
+ //-----------------------------------------------------------------------------
22
+
23
+ /**
24
+ * @typedef ObjectPropertySchema
25
+ * @property {Function|string} merge The function or name of the function to call
26
+ * to merge multiple objects with this property.
27
+ * @property {Function|string} validate The function or name of the function to call
28
+ * to validate the value of this property.
29
+ */
30
+
31
+ //-----------------------------------------------------------------------------
32
+ // Helpers
33
+ //-----------------------------------------------------------------------------
34
+
35
+ const ruleSeverities = new Map([
36
+ [0, 0], ["off", 0],
37
+ [1, 1], ["warn", 1],
38
+ [2, 2], ["error", 2]
39
+ ]);
40
+
41
+ const globalVariablesValues = new Set([
42
+ true, "true", "writable", "writeable",
43
+ false, "false", "readonly", "readable", null,
44
+ "off"
45
+ ]);
46
+
47
+ /**
48
+ * Check if a value is a non-null object.
49
+ * @param {any} value The value to check.
50
+ * @returns {boolean} `true` if the value is a non-null object.
51
+ */
52
+ function isNonNullObject(value) {
53
+ return typeof value === "object" && value !== null;
54
+ }
55
+
56
+ /**
57
+ * Check if a value is a non-null non-array object.
58
+ * @param {any} value The value to check.
59
+ * @returns {boolean} `true` if the value is a non-null non-array object.
60
+ */
61
+ function isNonArrayObject(value) {
62
+ return isNonNullObject(value) && !Array.isArray(value);
63
+ }
64
+
65
+ /**
66
+ * Check if a value is undefined.
67
+ * @param {any} value The value to check.
68
+ * @returns {boolean} `true` if the value is undefined.
69
+ */
70
+ function isUndefined(value) {
71
+ return typeof value === "undefined";
72
+ }
73
+
74
+ /**
75
+ * Deeply merges two non-array objects.
76
+ * @param {Object} first The base object.
77
+ * @param {Object} second The overrides object.
78
+ * @param {Map<string, Map<string, Object>>} [mergeMap] Maps the combination of first and second arguments to a merged result.
79
+ * @returns {Object} An object with properties from both first and second.
80
+ */
81
+ function deepMerge(first, second, mergeMap = new Map()) {
82
+
83
+ let secondMergeMap = mergeMap.get(first);
84
+
85
+ if (secondMergeMap) {
86
+ const result = secondMergeMap.get(second);
87
+
88
+ if (result) {
89
+
90
+ // If this combination of first and second arguments has been already visited, return the previously created result.
91
+ return result;
92
+ }
93
+ } else {
94
+ secondMergeMap = new Map();
95
+ mergeMap.set(first, secondMergeMap);
96
+ }
97
+
98
+ /*
99
+ * First create a result object where properties from the second object
100
+ * overwrite properties from the first. This sets up a baseline to use
101
+ * later rather than needing to inspect and change every property
102
+ * individually.
103
+ */
104
+ const result = {
105
+ ...first,
106
+ ...second
107
+ };
108
+
109
+ delete result.__proto__; // eslint-disable-line no-proto -- don't merge own property "__proto__"
110
+
111
+ // Store the pending result for this combination of first and second arguments.
112
+ secondMergeMap.set(second, result);
113
+
114
+ for (const key of Object.keys(second)) {
115
+
116
+ // avoid hairy edge case
117
+ if (key === "__proto__" || !Object.prototype.propertyIsEnumerable.call(first, key)) {
118
+ continue;
119
+ }
120
+
121
+ const firstValue = first[key];
122
+ const secondValue = second[key];
123
+
124
+ if (isNonArrayObject(firstValue) && isNonArrayObject(secondValue)) {
125
+ result[key] = deepMerge(firstValue, secondValue, mergeMap);
126
+ } else if (isUndefined(secondValue)) {
127
+ result[key] = firstValue;
128
+ }
129
+ }
130
+
131
+ return result;
132
+
133
+ }
134
+
135
+ /**
136
+ * Normalizes the rule options config for a given rule by ensuring that
137
+ * it is an array and that the first item is 0, 1, or 2.
138
+ * @param {Array|string|number} ruleOptions The rule options config.
139
+ * @returns {Array} An array of rule options.
140
+ */
141
+ function normalizeRuleOptions(ruleOptions) {
142
+
143
+ const finalOptions = Array.isArray(ruleOptions)
144
+ ? ruleOptions.slice(0)
145
+ : [ruleOptions];
146
+
147
+ finalOptions[0] = ruleSeverities.get(finalOptions[0]);
148
+ return structuredClone(finalOptions);
149
+ }
150
+
151
+ //-----------------------------------------------------------------------------
152
+ // Assertions
153
+ //-----------------------------------------------------------------------------
154
+
155
+ /**
156
+ * The error type when a rule's options are configured with an invalid type.
157
+ */
158
+ class InvalidRuleOptionsError extends Error {
159
+
160
+ /**
161
+ * @param {string} ruleId Rule name being configured.
162
+ * @param {any} value The invalid value.
163
+ */
164
+ constructor(ruleId, value) {
165
+ super(`Key "${ruleId}": Expected severity of "off", 0, "warn", 1, "error", or 2.`);
166
+ this.messageTemplate = "invalid-rule-options";
167
+ this.messageData = { ruleId, value };
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Validates that a value is a valid rule options entry.
173
+ * @param {string} ruleId Rule name being configured.
174
+ * @param {any} value The value to check.
175
+ * @returns {void}
176
+ * @throws {InvalidRuleOptionsError} If the value isn't a valid rule options.
177
+ */
178
+ function assertIsRuleOptions(ruleId, value) {
179
+ if (typeof value !== "string" && typeof value !== "number" && !Array.isArray(value)) {
180
+ throw new InvalidRuleOptionsError(ruleId, value);
181
+ }
182
+ }
183
+
184
+ /**
185
+ * The error type when a rule's severity is invalid.
186
+ */
187
+ class InvalidRuleSeverityError extends Error {
188
+
189
+ /**
190
+ * @param {string} ruleId Rule name being configured.
191
+ * @param {any} value The invalid value.
192
+ */
193
+ constructor(ruleId, value) {
194
+ super(`Key "${ruleId}": Expected severity of "off", 0, "warn", 1, "error", or 2.`);
195
+ this.messageTemplate = "invalid-rule-severity";
196
+ this.messageData = { ruleId, value };
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Validates that a value is valid rule severity.
202
+ * @param {string} ruleId Rule name being configured.
203
+ * @param {any} value The value to check.
204
+ * @returns {void}
205
+ * @throws {InvalidRuleSeverityError} If the value isn't a valid rule severity.
206
+ */
207
+ function assertIsRuleSeverity(ruleId, value) {
208
+ const severity = ruleSeverities.get(value);
209
+
210
+ if (typeof severity === "undefined") {
211
+ throw new InvalidRuleSeverityError(ruleId, value);
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Validates that a given string is the form pluginName/objectName.
217
+ * @param {string} value The string to check.
218
+ * @returns {void}
219
+ * @throws {TypeError} If the string isn't in the correct format.
220
+ */
221
+ function assertIsPluginMemberName(value) {
222
+ if (!/[@a-z0-9-_$]+(?:\/(?:[a-z0-9-_$]+))+$/iu.test(value)) {
223
+ throw new TypeError(`Expected string in the form "pluginName/objectName" but found "${value}".`);
224
+ }
225
+ }
226
+
227
+ /**
228
+ * Validates that a value is an object.
229
+ * @param {any} value The value to check.
230
+ * @returns {void}
231
+ * @throws {TypeError} If the value isn't an object.
232
+ */
233
+ function assertIsObject(value) {
234
+ if (!isNonNullObject(value)) {
235
+ throw new TypeError("Expected an object.");
236
+ }
237
+ }
238
+
239
+ /**
240
+ * The error type when there's an eslintrc-style options in a flat config.
241
+ */
242
+ class IncompatibleKeyError extends Error {
243
+
244
+ /**
245
+ * @param {string} key The invalid key.
246
+ */
247
+ constructor(key) {
248
+ super("This appears to be in eslintrc format rather than flat config format.");
249
+ this.messageTemplate = "eslintrc-incompat";
250
+ this.messageData = { key };
251
+ }
252
+ }
253
+
254
+ /**
255
+ * The error type when there's an eslintrc-style plugins array found.
256
+ */
257
+ class IncompatiblePluginsError extends Error {
258
+
259
+ /**
260
+ * Creates a new instance.
261
+ * @param {Array<string>} plugins The plugins array.
262
+ */
263
+ constructor(plugins) {
264
+ super("This appears to be in eslintrc format (array of strings) rather than flat config format (object).");
265
+ this.messageTemplate = "eslintrc-plugins";
266
+ this.messageData = { plugins };
267
+ }
268
+ }
269
+
270
+
271
+ //-----------------------------------------------------------------------------
272
+ // Low-Level Schemas
273
+ //-----------------------------------------------------------------------------
274
+
275
+ /** @type {ObjectPropertySchema} */
276
+ const booleanSchema = {
277
+ merge: "replace",
278
+ validate: "boolean"
279
+ };
280
+
281
+ const ALLOWED_SEVERITIES = new Set(["error", "warn", "off", 2, 1, 0]);
282
+
283
+ /** @type {ObjectPropertySchema} */
284
+ const disableDirectiveSeveritySchema = {
285
+ merge(first, second) {
286
+ const value = second === void 0 ? first : second;
287
+
288
+ if (typeof value === "boolean") {
289
+ return value ? "warn" : "off";
290
+ }
291
+
292
+ return normalizeSeverityToNumber(value);
293
+ },
294
+ validate(value) {
295
+ if (!(ALLOWED_SEVERITIES.has(value) || typeof value === "boolean")) {
296
+ throw new TypeError("Expected one of: \"error\", \"warn\", \"off\", 0, 1, 2, or a boolean.");
297
+ }
298
+ }
299
+ };
300
+
301
+ /** @type {ObjectPropertySchema} */
302
+ const deepObjectAssignSchema = {
303
+ merge(first = {}, second = {}) {
304
+ return deepMerge(first, second);
305
+ },
306
+ validate: "object"
307
+ };
308
+
309
+ //-----------------------------------------------------------------------------
310
+ // High-Level Schemas
311
+ //-----------------------------------------------------------------------------
312
+
313
+ /** @type {ObjectPropertySchema} */
314
+ const globalsSchema = {
315
+ merge: "assign",
316
+ validate(value) {
317
+
318
+ assertIsObject(value);
319
+
320
+ for (const key of Object.keys(value)) {
321
+
322
+ // avoid hairy edge case
323
+ if (key === "__proto__") {
324
+ continue;
325
+ }
326
+
327
+ if (key !== key.trim()) {
328
+ throw new TypeError(`Global "${key}" has leading or trailing whitespace.`);
329
+ }
330
+
331
+ if (!globalVariablesValues.has(value[key])) {
332
+ throw new TypeError(`Key "${key}": Expected "readonly", "writable", or "off".`);
333
+ }
334
+ }
335
+ }
336
+ };
337
+
338
+ /** @type {ObjectPropertySchema} */
339
+ const parserSchema = {
340
+ merge: "replace",
341
+ validate(value) {
342
+
343
+ if (!value || typeof value !== "object" ||
344
+ (typeof value.parse !== "function" && typeof value.parseForESLint !== "function")
345
+ ) {
346
+ throw new TypeError("Expected object with parse() or parseForESLint() method.");
347
+ }
348
+
349
+ }
350
+ };
351
+
352
+ /** @type {ObjectPropertySchema} */
353
+ const pluginsSchema = {
354
+ merge(first = {}, second = {}) {
355
+ const keys = new Set([...Object.keys(first), ...Object.keys(second)]);
356
+ const result = {};
357
+
358
+ // manually validate that plugins are not redefined
359
+ for (const key of keys) {
360
+
361
+ // avoid hairy edge case
362
+ if (key === "__proto__") {
363
+ continue;
364
+ }
365
+
366
+ if (key in first && key in second && first[key] !== second[key]) {
367
+ throw new TypeError(`Cannot redefine plugin "${key}".`);
368
+ }
369
+
370
+ result[key] = second[key] || first[key];
371
+ }
372
+
373
+ return result;
374
+ },
375
+ validate(value) {
376
+
377
+ // first check the value to be sure it's an object
378
+ if (value === null || typeof value !== "object") {
379
+ throw new TypeError("Expected an object.");
380
+ }
381
+
382
+ // make sure it's not an array, which would mean eslintrc-style is used
383
+ if (Array.isArray(value)) {
384
+ throw new IncompatiblePluginsError(value);
385
+ }
386
+
387
+ // second check the keys to make sure they are objects
388
+ for (const key of Object.keys(value)) {
389
+
390
+ // avoid hairy edge case
391
+ if (key === "__proto__") {
392
+ continue;
393
+ }
394
+
395
+ if (value[key] === null || typeof value[key] !== "object") {
396
+ throw new TypeError(`Key "${key}": Expected an object.`);
397
+ }
398
+ }
399
+ }
400
+ };
401
+
402
+ /** @type {ObjectPropertySchema} */
403
+ const processorSchema = {
404
+ merge: "replace",
405
+ validate(value) {
406
+ if (typeof value === "string") {
407
+ assertIsPluginMemberName(value);
408
+ } else if (value && typeof value === "object") {
409
+ if (typeof value.preprocess !== "function" || typeof value.postprocess !== "function") {
410
+ throw new TypeError("Object must have a preprocess() and a postprocess() method.");
411
+ }
412
+ } else {
413
+ throw new TypeError("Expected an object or a string.");
414
+ }
415
+ }
416
+ };
417
+
418
+ /** @type {ObjectPropertySchema} */
419
+ const rulesSchema = {
420
+ merge(first = {}, second = {}) {
421
+
422
+ const result = {
423
+ ...first,
424
+ ...second
425
+ };
426
+
427
+
428
+ for (const ruleId of Object.keys(result)) {
429
+
430
+ try {
431
+
432
+ // avoid hairy edge case
433
+ if (ruleId === "__proto__") {
434
+
435
+ /* eslint-disable-next-line no-proto -- Though deprecated, may still be present */
436
+ delete result.__proto__;
437
+ continue;
438
+ }
439
+
440
+ result[ruleId] = normalizeRuleOptions(result[ruleId]);
441
+
442
+ /*
443
+ * If either rule config is missing, then the correct
444
+ * config is already present and we just need to normalize
445
+ * the severity.
446
+ */
447
+ if (!(ruleId in first) || !(ruleId in second)) {
448
+ continue;
449
+ }
450
+
451
+ const firstRuleOptions = normalizeRuleOptions(first[ruleId]);
452
+ const secondRuleOptions = normalizeRuleOptions(second[ruleId]);
453
+
454
+ /*
455
+ * If the second rule config only has a severity (length of 1),
456
+ * then use that severity and keep the rest of the options from
457
+ * the first rule config.
458
+ */
459
+ if (secondRuleOptions.length === 1) {
460
+ result[ruleId] = [secondRuleOptions[0], ...firstRuleOptions.slice(1)];
461
+ continue;
462
+ }
463
+
464
+ /*
465
+ * In any other situation, then the second rule config takes
466
+ * precedence. That means the value at `result[ruleId]` is
467
+ * already correct and no further work is necessary.
468
+ */
469
+ } catch (ex) {
470
+ throw new Error(`Key "${ruleId}": ${ex.message}`, { cause: ex });
471
+ }
472
+
473
+ }
474
+
475
+ return result;
476
+
477
+
478
+ },
479
+
480
+ validate(value) {
481
+ assertIsObject(value);
482
+
483
+ /*
484
+ * We are not checking the rule schema here because there is no
485
+ * guarantee that the rule definition is present at this point. Instead
486
+ * we wait and check the rule schema during the finalization step
487
+ * of calculating a config.
488
+ */
489
+ for (const ruleId of Object.keys(value)) {
490
+
491
+ // avoid hairy edge case
492
+ if (ruleId === "__proto__") {
493
+ continue;
494
+ }
495
+
496
+ const ruleOptions = value[ruleId];
497
+
498
+ assertIsRuleOptions(ruleId, ruleOptions);
499
+
500
+ if (Array.isArray(ruleOptions)) {
501
+ assertIsRuleSeverity(ruleId, ruleOptions[0]);
502
+ } else {
503
+ assertIsRuleSeverity(ruleId, ruleOptions);
504
+ }
505
+ }
506
+ }
507
+ };
508
+
509
+ /** @type {ObjectPropertySchema} */
510
+ const ecmaVersionSchema = {
511
+ merge: "replace",
512
+ validate(value) {
513
+ if (typeof value === "number" || value === "latest") {
514
+ return;
515
+ }
516
+
517
+ throw new TypeError("Expected a number or \"latest\".");
518
+ }
519
+ };
520
+
521
+ /** @type {ObjectPropertySchema} */
522
+ const sourceTypeSchema = {
523
+ merge: "replace",
524
+ validate(value) {
525
+ if (typeof value !== "string" || !/^(?:script|module|commonjs)$/u.test(value)) {
526
+ throw new TypeError("Expected \"script\", \"module\", or \"commonjs\".");
527
+ }
528
+ }
529
+ };
530
+
531
+ /**
532
+ * Creates a schema that always throws an error. Useful for warning
533
+ * about eslintrc-style keys.
534
+ * @param {string} key The eslintrc key to create a schema for.
535
+ * @returns {ObjectPropertySchema} The schema.
536
+ */
537
+ function createEslintrcErrorSchema(key) {
538
+ return {
539
+ merge: "replace",
540
+ validate() {
541
+ throw new IncompatibleKeyError(key);
542
+ }
543
+ };
544
+ }
545
+
546
+ const eslintrcKeys = [
547
+ "env",
548
+ "extends",
549
+ "globals",
550
+ "ignorePatterns",
551
+ "noInlineConfig",
552
+ "overrides",
553
+ "parser",
554
+ "parserOptions",
555
+ "reportUnusedDisableDirectives",
556
+ "root"
557
+ ];
558
+
559
+ //-----------------------------------------------------------------------------
560
+ // Full schema
561
+ //-----------------------------------------------------------------------------
562
+
563
+ const flatConfigSchema = {
564
+
565
+ // eslintrc-style keys that should always error
566
+ ...Object.fromEntries(eslintrcKeys.map(key => [key, createEslintrcErrorSchema(key)])),
567
+
568
+ // flat config keys
569
+ settings: deepObjectAssignSchema,
570
+ linterOptions: {
571
+ schema: {
572
+ noInlineConfig: booleanSchema,
573
+ reportUnusedDisableDirectives: disableDirectiveSeveritySchema
574
+ }
575
+ },
576
+ languageOptions: {
577
+ schema: {
578
+ ecmaVersion: ecmaVersionSchema,
579
+ sourceType: sourceTypeSchema,
580
+ globals: globalsSchema,
581
+ parser: parserSchema,
582
+ parserOptions: deepObjectAssignSchema
583
+ }
584
+ },
585
+ processor: processorSchema,
586
+ plugins: pluginsSchema,
587
+ rules: rulesSchema
588
+ };
589
+
590
+ //-----------------------------------------------------------------------------
591
+ // Exports
592
+ //-----------------------------------------------------------------------------
593
+
594
+ module.exports = {
595
+ flatConfigSchema,
596
+ assertIsRuleSeverity,
597
+ assertIsRuleOptions
598
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/config/rule-validator.js ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Rule Validator
3
+ * @author Nicholas C. Zakas
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //-----------------------------------------------------------------------------
9
+ // Requirements
10
+ //-----------------------------------------------------------------------------
11
+
12
+ const ajvImport = require("../shared/ajv");
13
+ const ajv = ajvImport();
14
+ const {
15
+ parseRuleId,
16
+ getRuleFromConfig,
17
+ getRuleOptionsSchema
18
+ } = require("./flat-config-helpers");
19
+ const ruleReplacements = require("../../conf/replacements.json");
20
+
21
+ //-----------------------------------------------------------------------------
22
+ // Helpers
23
+ //-----------------------------------------------------------------------------
24
+
25
+ /**
26
+ * Throws a helpful error when a rule cannot be found.
27
+ * @param {Object} ruleId The rule identifier.
28
+ * @param {string} ruleId.pluginName The ID of the rule to find.
29
+ * @param {string} ruleId.ruleName The ID of the rule to find.
30
+ * @param {Object} config The config to search in.
31
+ * @throws {TypeError} For missing plugin or rule.
32
+ * @returns {void}
33
+ */
34
+ function throwRuleNotFoundError({ pluginName, ruleName }, config) {
35
+
36
+ const ruleId = pluginName === "@" ? ruleName : `${pluginName}/${ruleName}`;
37
+
38
+ const errorMessageHeader = `Key "rules": Key "${ruleId}"`;
39
+ let errorMessage = `${errorMessageHeader}: Could not find plugin "${pluginName}".`;
40
+
41
+ // if the plugin exists then we need to check if the rule exists
42
+ if (config.plugins && config.plugins[pluginName]) {
43
+ const replacementRuleName = ruleReplacements.rules[ruleName];
44
+
45
+ if (pluginName === "@" && replacementRuleName) {
46
+
47
+ errorMessage = `${errorMessageHeader}: Rule "${ruleName}" was removed and replaced by "${replacementRuleName}".`;
48
+
49
+ } else {
50
+
51
+ errorMessage = `${errorMessageHeader}: Could not find "${ruleName}" in plugin "${pluginName}".`;
52
+
53
+ // otherwise, let's see if we can find the rule name elsewhere
54
+ for (const [otherPluginName, otherPlugin] of Object.entries(config.plugins)) {
55
+ if (otherPlugin.rules && otherPlugin.rules[ruleName]) {
56
+ errorMessage += ` Did you mean "${otherPluginName}/${ruleName}"?`;
57
+ break;
58
+ }
59
+ }
60
+
61
+ }
62
+
63
+ // falls through to throw error
64
+ }
65
+
66
+ throw new TypeError(errorMessage);
67
+ }
68
+
69
+ //-----------------------------------------------------------------------------
70
+ // Exports
71
+ //-----------------------------------------------------------------------------
72
+
73
+ /**
74
+ * Implements validation functionality for the rules portion of a config.
75
+ */
76
+ class RuleValidator {
77
+
78
+ /**
79
+ * Creates a new instance.
80
+ */
81
+ constructor() {
82
+
83
+ /**
84
+ * A collection of compiled validators for rules that have already
85
+ * been validated.
86
+ * @type {WeakMap}
87
+ */
88
+ this.validators = new WeakMap();
89
+ }
90
+
91
+ /**
92
+ * Validates all of the rule configurations in a config against each
93
+ * rule's schema.
94
+ * @param {Object} config The full config to validate. This object must
95
+ * contain both the rules section and the plugins section.
96
+ * @returns {void}
97
+ * @throws {Error} If a rule's configuration does not match its schema.
98
+ */
99
+ validate(config) {
100
+
101
+ if (!config.rules) {
102
+ return;
103
+ }
104
+
105
+ for (const [ruleId, ruleOptions] of Object.entries(config.rules)) {
106
+
107
+ // check for edge case
108
+ if (ruleId === "__proto__") {
109
+ continue;
110
+ }
111
+
112
+ /*
113
+ * If a rule is disabled, we don't do any validation. This allows
114
+ * users to safely set any value to 0 or "off" without worrying
115
+ * that it will cause a validation error.
116
+ *
117
+ * Note: ruleOptions is always an array at this point because
118
+ * this validation occurs after FlatConfigArray has merged and
119
+ * normalized values.
120
+ */
121
+ if (ruleOptions[0] === 0) {
122
+ continue;
123
+ }
124
+
125
+ const rule = getRuleFromConfig(ruleId, config);
126
+
127
+ if (!rule) {
128
+ throwRuleNotFoundError(parseRuleId(ruleId), config);
129
+ }
130
+
131
+ // Precompile and cache validator the first time
132
+ if (!this.validators.has(rule)) {
133
+ const schema = getRuleOptionsSchema(rule);
134
+
135
+ if (schema) {
136
+ this.validators.set(rule, ajv.compile(schema));
137
+ }
138
+ }
139
+
140
+ const validateRule = this.validators.get(rule);
141
+
142
+ if (validateRule) {
143
+
144
+ validateRule(ruleOptions.slice(1));
145
+
146
+ if (validateRule.errors) {
147
+ throw new Error(`Key "rules": Key "${ruleId}": ${
148
+ validateRule.errors.map(
149
+ error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`
150
+ ).join("")
151
+ }`);
152
+ }
153
+ }
154
+ }
155
+ }
156
+ }
157
+
158
+ exports.RuleValidator = RuleValidator;
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/eslint/eslint-helpers.js ADDED
@@ -0,0 +1,932 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Helper functions for ESLint class
3
+ * @author Nicholas C. Zakas
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //-----------------------------------------------------------------------------
9
+ // Requirements
10
+ //-----------------------------------------------------------------------------
11
+
12
+ const path = require("path");
13
+ const fs = require("fs");
14
+ const fsp = fs.promises;
15
+ const isGlob = require("is-glob");
16
+ const hash = require("../cli-engine/hash");
17
+ const minimatch = require("minimatch");
18
+ const fswalk = require("@nodelib/fs.walk");
19
+ const globParent = require("glob-parent");
20
+ const isPathInside = require("is-path-inside");
21
+
22
+ //-----------------------------------------------------------------------------
23
+ // Fixup references
24
+ //-----------------------------------------------------------------------------
25
+
26
+ const Minimatch = minimatch.Minimatch;
27
+ const MINIMATCH_OPTIONS = { dot: true };
28
+
29
+ //-----------------------------------------------------------------------------
30
+ // Types
31
+ //-----------------------------------------------------------------------------
32
+
33
+ /**
34
+ * @typedef {Object} GlobSearch
35
+ * @property {Array<string>} patterns The normalized patterns to use for a search.
36
+ * @property {Array<string>} rawPatterns The patterns as entered by the user
37
+ * before doing any normalization.
38
+ */
39
+
40
+ //-----------------------------------------------------------------------------
41
+ // Errors
42
+ //-----------------------------------------------------------------------------
43
+
44
+ /**
45
+ * The error type when no files match a glob.
46
+ */
47
+ class NoFilesFoundError extends Error {
48
+
49
+ /**
50
+ * @param {string} pattern The glob pattern which was not found.
51
+ * @param {boolean} globEnabled If `false` then the pattern was a glob pattern, but glob was disabled.
52
+ */
53
+ constructor(pattern, globEnabled) {
54
+ super(`No files matching '${pattern}' were found${!globEnabled ? " (glob was disabled)" : ""}.`);
55
+ this.messageTemplate = "file-not-found";
56
+ this.messageData = { pattern, globDisabled: !globEnabled };
57
+ }
58
+ }
59
+
60
+ /**
61
+ * The error type when a search fails to match multiple patterns.
62
+ */
63
+ class UnmatchedSearchPatternsError extends Error {
64
+
65
+ /**
66
+ * @param {Object} options The options for the error.
67
+ * @param {string} options.basePath The directory that was searched.
68
+ * @param {Array<string>} options.unmatchedPatterns The glob patterns
69
+ * which were not found.
70
+ * @param {Array<string>} options.patterns The glob patterns that were
71
+ * searched.
72
+ * @param {Array<string>} options.rawPatterns The raw glob patterns that
73
+ * were searched.
74
+ */
75
+ constructor({ basePath, unmatchedPatterns, patterns, rawPatterns }) {
76
+ super(`No files matching '${rawPatterns}' in '${basePath}' were found.`);
77
+ this.basePath = basePath;
78
+ this.unmatchedPatterns = unmatchedPatterns;
79
+ this.patterns = patterns;
80
+ this.rawPatterns = rawPatterns;
81
+ }
82
+ }
83
+
84
+ /**
85
+ * The error type when there are files matched by a glob, but all of them have been ignored.
86
+ */
87
+ class AllFilesIgnoredError extends Error {
88
+
89
+ /**
90
+ * @param {string} pattern The glob pattern which was not found.
91
+ */
92
+ constructor(pattern) {
93
+ super(`All files matched by '${pattern}' are ignored.`);
94
+ this.messageTemplate = "all-files-ignored";
95
+ this.messageData = { pattern };
96
+ }
97
+ }
98
+
99
+
100
+ //-----------------------------------------------------------------------------
101
+ // General Helpers
102
+ //-----------------------------------------------------------------------------
103
+
104
+ /**
105
+ * Check if a given value is a non-empty string or not.
106
+ * @param {any} x The value to check.
107
+ * @returns {boolean} `true` if `x` is a non-empty string.
108
+ */
109
+ function isNonEmptyString(x) {
110
+ return typeof x === "string" && x.trim() !== "";
111
+ }
112
+
113
+ /**
114
+ * Check if a given value is an array of non-empty strings or not.
115
+ * @param {any} x The value to check.
116
+ * @returns {boolean} `true` if `x` is an array of non-empty strings.
117
+ */
118
+ function isArrayOfNonEmptyString(x) {
119
+ return Array.isArray(x) && x.every(isNonEmptyString);
120
+ }
121
+
122
+ //-----------------------------------------------------------------------------
123
+ // File-related Helpers
124
+ //-----------------------------------------------------------------------------
125
+
126
+ /**
127
+ * Normalizes slashes in a file pattern to posix-style.
128
+ * @param {string} pattern The pattern to replace slashes in.
129
+ * @returns {string} The pattern with slashes normalized.
130
+ */
131
+ function normalizeToPosix(pattern) {
132
+ return pattern.replace(/\\/gu, "/");
133
+ }
134
+
135
+ /**
136
+ * Check if a string is a glob pattern or not.
137
+ * @param {string} pattern A glob pattern.
138
+ * @returns {boolean} `true` if the string is a glob pattern.
139
+ */
140
+ function isGlobPattern(pattern) {
141
+ return isGlob(path.sep === "\\" ? normalizeToPosix(pattern) : pattern);
142
+ }
143
+
144
+
145
+ /**
146
+ * Determines if a given glob pattern will return any results.
147
+ * Used primarily to help with useful error messages.
148
+ * @param {Object} options The options for the function.
149
+ * @param {string} options.basePath The directory to search.
150
+ * @param {string} options.pattern A glob pattern to match.
151
+ * @returns {Promise<boolean>} True if there is a glob match, false if not.
152
+ */
153
+ function globMatch({ basePath, pattern }) {
154
+
155
+ let found = false;
156
+ const patternToUse = path.isAbsolute(pattern)
157
+ ? normalizeToPosix(path.relative(basePath, pattern))
158
+ : pattern;
159
+
160
+ const matcher = new Minimatch(patternToUse, MINIMATCH_OPTIONS);
161
+
162
+ const fsWalkSettings = {
163
+
164
+ deepFilter(entry) {
165
+ const relativePath = normalizeToPosix(path.relative(basePath, entry.path));
166
+
167
+ return !found && matcher.match(relativePath, true);
168
+ },
169
+
170
+ entryFilter(entry) {
171
+ if (found || entry.dirent.isDirectory()) {
172
+ return false;
173
+ }
174
+
175
+ const relativePath = normalizeToPosix(path.relative(basePath, entry.path));
176
+
177
+ if (matcher.match(relativePath)) {
178
+ found = true;
179
+ return true;
180
+ }
181
+
182
+ return false;
183
+ }
184
+ };
185
+
186
+ return new Promise(resolve => {
187
+
188
+ // using a stream so we can exit early because we just need one match
189
+ const globStream = fswalk.walkStream(basePath, fsWalkSettings);
190
+
191
+ globStream.on("data", () => {
192
+ globStream.destroy();
193
+ resolve(true);
194
+ });
195
+
196
+ // swallow errors as they're not important here
197
+ globStream.on("error", () => { });
198
+
199
+ globStream.on("end", () => {
200
+ resolve(false);
201
+ });
202
+ globStream.read();
203
+ });
204
+
205
+ }
206
+
207
+ /**
208
+ * Searches a directory looking for matching glob patterns. This uses
209
+ * the config array's logic to determine if a directory or file should
210
+ * be ignored, so it is consistent with how ignoring works throughout
211
+ * ESLint.
212
+ * @param {Object} options The options for this function.
213
+ * @param {string} options.basePath The directory to search.
214
+ * @param {Array<string>} options.patterns An array of glob patterns
215
+ * to match.
216
+ * @param {Array<string>} options.rawPatterns An array of glob patterns
217
+ * as the user inputted them. Used for errors.
218
+ * @param {FlatConfigArray} options.configs The config array to use for
219
+ * determining what to ignore.
220
+ * @param {boolean} options.errorOnUnmatchedPattern Determines if an error
221
+ * should be thrown when a pattern is unmatched.
222
+ * @returns {Promise<Array<string>>} An array of matching file paths
223
+ * or an empty array if there are no matches.
224
+ * @throws {UnmatchedSearchPatternsError} If there is a pattern that doesn't
225
+ * match any files.
226
+ */
227
+ async function globSearch({
228
+ basePath,
229
+ patterns,
230
+ rawPatterns,
231
+ configs,
232
+ errorOnUnmatchedPattern
233
+ }) {
234
+
235
+ if (patterns.length === 0) {
236
+ return [];
237
+ }
238
+
239
+ /*
240
+ * In this section we are converting the patterns into Minimatch
241
+ * instances for performance reasons. Because we are doing the same
242
+ * matches repeatedly, it's best to compile those patterns once and
243
+ * reuse them multiple times.
244
+ *
245
+ * To do that, we convert any patterns with an absolute path into a
246
+ * relative path and normalize it to Posix-style slashes. We also keep
247
+ * track of the relative patterns to map them back to the original
248
+ * patterns, which we need in order to throw an error if there are any
249
+ * unmatched patterns.
250
+ */
251
+ const relativeToPatterns = new Map();
252
+ const matchers = patterns.map((pattern, i) => {
253
+ const patternToUse = path.isAbsolute(pattern)
254
+ ? normalizeToPosix(path.relative(basePath, pattern))
255
+ : pattern;
256
+
257
+ relativeToPatterns.set(patternToUse, patterns[i]);
258
+
259
+ return new Minimatch(patternToUse, MINIMATCH_OPTIONS);
260
+ });
261
+
262
+ /*
263
+ * We track unmatched patterns because we may want to throw an error when
264
+ * they occur. To start, this set is initialized with all of the patterns.
265
+ * Every time a match occurs, the pattern is removed from the set, making
266
+ * it easy to tell if we have any unmatched patterns left at the end of
267
+ * search.
268
+ */
269
+ const unmatchedPatterns = new Set([...relativeToPatterns.keys()]);
270
+
271
+ const filePaths = (await new Promise((resolve, reject) => {
272
+
273
+ let promiseRejected = false;
274
+
275
+ /**
276
+ * Wraps a boolean-returning filter function. The wrapped function will reject the promise if an error occurs.
277
+ * @param {Function} filter A filter function to wrap.
278
+ * @returns {Function} A function similar to the wrapped filter that rejects the promise if an error occurs.
279
+ */
280
+ function wrapFilter(filter) {
281
+ return (...args) => {
282
+
283
+ // No need to run the filter if an error has been thrown.
284
+ if (!promiseRejected) {
285
+ try {
286
+ return filter(...args);
287
+ } catch (error) {
288
+ promiseRejected = true;
289
+ reject(error);
290
+ }
291
+ }
292
+ return false;
293
+ };
294
+ }
295
+
296
+ fswalk.walk(
297
+ basePath,
298
+ {
299
+ deepFilter: wrapFilter(entry => {
300
+ const relativePath = normalizeToPosix(path.relative(basePath, entry.path));
301
+ const matchesPattern = matchers.some(matcher => matcher.match(relativePath, true));
302
+
303
+ return matchesPattern && !configs.isDirectoryIgnored(entry.path);
304
+ }),
305
+ entryFilter: wrapFilter(entry => {
306
+ const relativePath = normalizeToPosix(path.relative(basePath, entry.path));
307
+
308
+ // entries may be directories or files so filter out directories
309
+ if (entry.dirent.isDirectory()) {
310
+ return false;
311
+ }
312
+
313
+ /*
314
+ * Optimization: We need to track when patterns are left unmatched
315
+ * and so we use `unmatchedPatterns` to do that. There is a bit of
316
+ * complexity here because the same file can be matched by more than
317
+ * one pattern. So, when we start, we actually need to test every
318
+ * pattern against every file. Once we know there are no remaining
319
+ * unmatched patterns, then we can switch to just looking for the
320
+ * first matching pattern for improved speed.
321
+ */
322
+ const matchesPattern = unmatchedPatterns.size > 0
323
+ ? matchers.reduce((previousValue, matcher) => {
324
+ const pathMatches = matcher.match(relativePath);
325
+
326
+ /*
327
+ * We updated the unmatched patterns set only if the path
328
+ * matches and the file isn't ignored. If the file is
329
+ * ignored, that means there wasn't a match for the
330
+ * pattern so it should not be removed.
331
+ *
332
+ * Performance note: isFileIgnored() aggressively caches
333
+ * results so there is no performance penalty for calling
334
+ * it twice with the same argument.
335
+ */
336
+ if (pathMatches && !configs.isFileIgnored(entry.path)) {
337
+ unmatchedPatterns.delete(matcher.pattern);
338
+ }
339
+
340
+ return pathMatches || previousValue;
341
+ }, false)
342
+ : matchers.some(matcher => matcher.match(relativePath));
343
+
344
+ return matchesPattern && !configs.isFileIgnored(entry.path);
345
+ })
346
+ },
347
+ (error, entries) => {
348
+
349
+ // If the promise is already rejected, calling `resolve` or `reject` will do nothing.
350
+ if (error) {
351
+ reject(error);
352
+ } else {
353
+ resolve(entries);
354
+ }
355
+ }
356
+ );
357
+ })).map(entry => entry.path);
358
+
359
+ // now check to see if we have any unmatched patterns
360
+ if (errorOnUnmatchedPattern && unmatchedPatterns.size > 0) {
361
+ throw new UnmatchedSearchPatternsError({
362
+ basePath,
363
+ unmatchedPatterns: [...unmatchedPatterns].map(
364
+ pattern => relativeToPatterns.get(pattern)
365
+ ),
366
+ patterns,
367
+ rawPatterns
368
+ });
369
+ }
370
+
371
+ return filePaths;
372
+ }
373
+
374
+ /**
375
+ * Throws an error for unmatched patterns. The error will only contain information about the first one.
376
+ * Checks to see if there are any ignored results for a given search.
377
+ * @param {Object} options The options for this function.
378
+ * @param {string} options.basePath The directory to search.
379
+ * @param {Array<string>} options.patterns An array of glob patterns
380
+ * that were used in the original search.
381
+ * @param {Array<string>} options.rawPatterns An array of glob patterns
382
+ * as the user inputted them. Used for errors.
383
+ * @param {Array<string>} options.unmatchedPatterns A non-empty array of glob patterns
384
+ * that were unmatched in the original search.
385
+ * @returns {void} Always throws an error.
386
+ * @throws {NoFilesFoundError} If the first unmatched pattern
387
+ * doesn't match any files even when there are no ignores.
388
+ * @throws {AllFilesIgnoredError} If the first unmatched pattern
389
+ * matches some files when there are no ignores.
390
+ */
391
+ async function throwErrorForUnmatchedPatterns({
392
+ basePath,
393
+ patterns,
394
+ rawPatterns,
395
+ unmatchedPatterns
396
+ }) {
397
+
398
+ const pattern = unmatchedPatterns[0];
399
+ const rawPattern = rawPatterns[patterns.indexOf(pattern)];
400
+
401
+ const patternHasMatch = await globMatch({
402
+ basePath,
403
+ pattern
404
+ });
405
+
406
+ if (patternHasMatch) {
407
+ throw new AllFilesIgnoredError(rawPattern);
408
+ }
409
+
410
+ // if we get here there are truly no matches
411
+ throw new NoFilesFoundError(rawPattern, true);
412
+ }
413
+
414
+ /**
415
+ * Performs multiple glob searches in parallel.
416
+ * @param {Object} options The options for this function.
417
+ * @param {Map<string,GlobSearch>} options.searches
418
+ * An array of glob patterns to match.
419
+ * @param {FlatConfigArray} options.configs The config array to use for
420
+ * determining what to ignore.
421
+ * @param {boolean} options.errorOnUnmatchedPattern Determines if an
422
+ * unmatched glob pattern should throw an error.
423
+ * @returns {Promise<Array<string>>} An array of matching file paths
424
+ * or an empty array if there are no matches.
425
+ */
426
+ async function globMultiSearch({ searches, configs, errorOnUnmatchedPattern }) {
427
+
428
+ /*
429
+ * For convenience, we normalized the search map into an array of objects.
430
+ * Next, we filter out all searches that have no patterns. This happens
431
+ * primarily for the cwd, which is prepopulated in the searches map as an
432
+ * optimization. However, if it has no patterns, it means all patterns
433
+ * occur outside of the cwd and we can safely filter out that search.
434
+ */
435
+ const normalizedSearches = [...searches].map(
436
+ ([basePath, { patterns, rawPatterns }]) => ({ basePath, patterns, rawPatterns })
437
+ ).filter(({ patterns }) => patterns.length > 0);
438
+
439
+ const results = await Promise.allSettled(
440
+ normalizedSearches.map(
441
+ ({ basePath, patterns, rawPatterns }) => globSearch({
442
+ basePath,
443
+ patterns,
444
+ rawPatterns,
445
+ configs,
446
+ errorOnUnmatchedPattern
447
+ })
448
+ )
449
+ );
450
+
451
+ const filePaths = [];
452
+
453
+ for (let i = 0; i < results.length; i++) {
454
+
455
+ const result = results[i];
456
+ const currentSearch = normalizedSearches[i];
457
+
458
+ if (result.status === "fulfilled") {
459
+
460
+ // if the search was successful just add the results
461
+ if (result.value.length > 0) {
462
+ filePaths.push(...result.value);
463
+ }
464
+
465
+ continue;
466
+ }
467
+
468
+ // if we make it here then there was an error
469
+ const error = result.reason;
470
+
471
+ // unexpected errors should be re-thrown
472
+ if (!error.basePath) {
473
+ throw error;
474
+ }
475
+
476
+ if (errorOnUnmatchedPattern) {
477
+
478
+ await throwErrorForUnmatchedPatterns({
479
+ ...currentSearch,
480
+ unmatchedPatterns: error.unmatchedPatterns
481
+ });
482
+
483
+ }
484
+
485
+ }
486
+
487
+ return filePaths;
488
+
489
+ }
490
+
491
+ /**
492
+ * Finds all files matching the options specified.
493
+ * @param {Object} args The arguments objects.
494
+ * @param {Array<string>} args.patterns An array of glob patterns.
495
+ * @param {boolean} args.globInputPaths true to interpret glob patterns,
496
+ * false to not interpret glob patterns.
497
+ * @param {string} args.cwd The current working directory to find from.
498
+ * @param {FlatConfigArray} args.configs The configs for the current run.
499
+ * @param {boolean} args.errorOnUnmatchedPattern Determines if an unmatched pattern
500
+ * should throw an error.
501
+ * @returns {Promise<Array<string>>} The fully resolved file paths.
502
+ * @throws {AllFilesIgnoredError} If there are no results due to an ignore pattern.
503
+ * @throws {NoFilesFoundError} If no files matched the given patterns.
504
+ */
505
+ async function findFiles({
506
+ patterns,
507
+ globInputPaths,
508
+ cwd,
509
+ configs,
510
+ errorOnUnmatchedPattern
511
+ }) {
512
+
513
+ const results = [];
514
+ const missingPatterns = [];
515
+ let globbyPatterns = [];
516
+ let rawPatterns = [];
517
+ const searches = new Map([[cwd, { patterns: globbyPatterns, rawPatterns: [] }]]);
518
+
519
+ // check to see if we have explicit files and directories
520
+ const filePaths = patterns.map(filePath => path.resolve(cwd, filePath));
521
+ const stats = await Promise.all(
522
+ filePaths.map(
523
+ filePath => fsp.stat(filePath).catch(() => { })
524
+ )
525
+ );
526
+
527
+ stats.forEach((stat, index) => {
528
+
529
+ const filePath = filePaths[index];
530
+ const pattern = normalizeToPosix(patterns[index]);
531
+
532
+ if (stat) {
533
+
534
+ // files are added directly to the list
535
+ if (stat.isFile()) {
536
+ results.push(filePath);
537
+ }
538
+
539
+ // directories need extensions attached
540
+ if (stat.isDirectory()) {
541
+
542
+ // group everything in cwd together and split out others
543
+ if (isPathInside(filePath, cwd)) {
544
+ ({ patterns: globbyPatterns, rawPatterns } = searches.get(cwd));
545
+ } else {
546
+ if (!searches.has(filePath)) {
547
+ searches.set(filePath, { patterns: [], rawPatterns: [] });
548
+ }
549
+ ({ patterns: globbyPatterns, rawPatterns } = searches.get(filePath));
550
+ }
551
+
552
+ globbyPatterns.push(`${normalizeToPosix(filePath)}/**`);
553
+ rawPatterns.push(pattern);
554
+ }
555
+
556
+ return;
557
+ }
558
+
559
+ // save patterns for later use based on whether globs are enabled
560
+ if (globInputPaths && isGlobPattern(pattern)) {
561
+
562
+ const basePath = path.resolve(cwd, globParent(pattern));
563
+
564
+ // group in cwd if possible and split out others
565
+ if (isPathInside(basePath, cwd)) {
566
+ ({ patterns: globbyPatterns, rawPatterns } = searches.get(cwd));
567
+ } else {
568
+ if (!searches.has(basePath)) {
569
+ searches.set(basePath, { patterns: [], rawPatterns: [] });
570
+ }
571
+ ({ patterns: globbyPatterns, rawPatterns } = searches.get(basePath));
572
+ }
573
+
574
+ globbyPatterns.push(filePath);
575
+ rawPatterns.push(pattern);
576
+ } else {
577
+ missingPatterns.push(pattern);
578
+ }
579
+ });
580
+
581
+ // there were patterns that didn't match anything, tell the user
582
+ if (errorOnUnmatchedPattern && missingPatterns.length) {
583
+ throw new NoFilesFoundError(missingPatterns[0], globInputPaths);
584
+ }
585
+
586
+ // now we are safe to do the search
587
+ const globbyResults = await globMultiSearch({
588
+ searches,
589
+ configs,
590
+ errorOnUnmatchedPattern
591
+ });
592
+
593
+ return [
594
+ ...new Set([
595
+ ...results,
596
+ ...globbyResults.map(filePath => path.resolve(filePath))
597
+ ])
598
+ ];
599
+ }
600
+
601
+ //-----------------------------------------------------------------------------
602
+ // Results-related Helpers
603
+ //-----------------------------------------------------------------------------
604
+
605
+ /**
606
+ * Checks if the given message is an error message.
607
+ * @param {LintMessage} message The message to check.
608
+ * @returns {boolean} Whether or not the message is an error message.
609
+ * @private
610
+ */
611
+ function isErrorMessage(message) {
612
+ return message.severity === 2;
613
+ }
614
+
615
+ /**
616
+ * Returns result with warning by ignore settings
617
+ * @param {string} filePath File path of checked code
618
+ * @param {string} baseDir Absolute path of base directory
619
+ * @returns {LintResult} Result with single warning
620
+ * @private
621
+ */
622
+ function createIgnoreResult(filePath, baseDir) {
623
+ let message;
624
+ const isInNodeModules = baseDir && path.dirname(path.relative(baseDir, filePath)).split(path.sep).includes("node_modules");
625
+
626
+ if (isInNodeModules) {
627
+ message = "File ignored by default because it is located under the node_modules directory. Use ignore pattern \"!**/node_modules/\" to disable file ignore settings or use \"--no-warn-ignored\" to suppress this warning.";
628
+ } else {
629
+ message = "File ignored because of a matching ignore pattern. Use \"--no-ignore\" to disable file ignore settings or use \"--no-warn-ignored\" to suppress this warning.";
630
+ }
631
+
632
+ return {
633
+ filePath: path.resolve(filePath),
634
+ messages: [
635
+ {
636
+ ruleId: null,
637
+ fatal: false,
638
+ severity: 1,
639
+ message,
640
+ nodeType: null
641
+ }
642
+ ],
643
+ suppressedMessages: [],
644
+ errorCount: 0,
645
+ warningCount: 1,
646
+ fatalErrorCount: 0,
647
+ fixableErrorCount: 0,
648
+ fixableWarningCount: 0
649
+ };
650
+ }
651
+
652
+ //-----------------------------------------------------------------------------
653
+ // Options-related Helpers
654
+ //-----------------------------------------------------------------------------
655
+
656
+
657
+ /**
658
+ * Check if a given value is a valid fix type or not.
659
+ * @param {any} x The value to check.
660
+ * @returns {boolean} `true` if `x` is valid fix type.
661
+ */
662
+ function isFixType(x) {
663
+ return x === "directive" || x === "problem" || x === "suggestion" || x === "layout";
664
+ }
665
+
666
+ /**
667
+ * Check if a given value is an array of fix types or not.
668
+ * @param {any} x The value to check.
669
+ * @returns {boolean} `true` if `x` is an array of fix types.
670
+ */
671
+ function isFixTypeArray(x) {
672
+ return Array.isArray(x) && x.every(isFixType);
673
+ }
674
+
675
+ /**
676
+ * The error for invalid options.
677
+ */
678
+ class ESLintInvalidOptionsError extends Error {
679
+ constructor(messages) {
680
+ super(`Invalid Options:\n- ${messages.join("\n- ")}`);
681
+ this.code = "ESLINT_INVALID_OPTIONS";
682
+ Error.captureStackTrace(this, ESLintInvalidOptionsError);
683
+ }
684
+ }
685
+
686
+ /**
687
+ * Validates and normalizes options for the wrapped CLIEngine instance.
688
+ * @param {FlatESLintOptions} options The options to process.
689
+ * @throws {ESLintInvalidOptionsError} If of any of a variety of type errors.
690
+ * @returns {FlatESLintOptions} The normalized options.
691
+ */
692
+ function processOptions({
693
+ allowInlineConfig = true, // ← we cannot use `overrideConfig.noInlineConfig` instead because `allowInlineConfig` has side-effect that suppress warnings that show inline configs are ignored.
694
+ baseConfig = null,
695
+ cache = false,
696
+ cacheLocation = ".eslintcache",
697
+ cacheStrategy = "metadata",
698
+ cwd = process.cwd(),
699
+ errorOnUnmatchedPattern = true,
700
+ fix = false,
701
+ 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.
702
+ globInputPaths = true,
703
+ ignore = true,
704
+ ignorePatterns = null,
705
+ overrideConfig = null,
706
+ overrideConfigFile = null,
707
+ plugins = {},
708
+ warnIgnored = true,
709
+ ...unknownOptions
710
+ }) {
711
+ const errors = [];
712
+ const unknownOptionKeys = Object.keys(unknownOptions);
713
+
714
+ if (unknownOptionKeys.length >= 1) {
715
+ errors.push(`Unknown options: ${unknownOptionKeys.join(", ")}`);
716
+ if (unknownOptionKeys.includes("cacheFile")) {
717
+ errors.push("'cacheFile' has been removed. Please use the 'cacheLocation' option instead.");
718
+ }
719
+ if (unknownOptionKeys.includes("configFile")) {
720
+ errors.push("'configFile' has been removed. Please use the 'overrideConfigFile' option instead.");
721
+ }
722
+ if (unknownOptionKeys.includes("envs")) {
723
+ errors.push("'envs' has been removed.");
724
+ }
725
+ if (unknownOptionKeys.includes("extensions")) {
726
+ errors.push("'extensions' has been removed.");
727
+ }
728
+ if (unknownOptionKeys.includes("resolvePluginsRelativeTo")) {
729
+ errors.push("'resolvePluginsRelativeTo' has been removed.");
730
+ }
731
+ if (unknownOptionKeys.includes("globals")) {
732
+ errors.push("'globals' has been removed. Please use the 'overrideConfig.languageOptions.globals' option instead.");
733
+ }
734
+ if (unknownOptionKeys.includes("ignorePath")) {
735
+ errors.push("'ignorePath' has been removed.");
736
+ }
737
+ if (unknownOptionKeys.includes("ignorePattern")) {
738
+ errors.push("'ignorePattern' has been removed. Please use the 'overrideConfig.ignorePatterns' option instead.");
739
+ }
740
+ if (unknownOptionKeys.includes("parser")) {
741
+ errors.push("'parser' has been removed. Please use the 'overrideConfig.languageOptions.parser' option instead.");
742
+ }
743
+ if (unknownOptionKeys.includes("parserOptions")) {
744
+ errors.push("'parserOptions' has been removed. Please use the 'overrideConfig.languageOptions.parserOptions' option instead.");
745
+ }
746
+ if (unknownOptionKeys.includes("rules")) {
747
+ errors.push("'rules' has been removed. Please use the 'overrideConfig.rules' option instead.");
748
+ }
749
+ if (unknownOptionKeys.includes("rulePaths")) {
750
+ errors.push("'rulePaths' has been removed. Please define your rules using plugins.");
751
+ }
752
+ if (unknownOptionKeys.includes("reportUnusedDisableDirectives")) {
753
+ errors.push("'reportUnusedDisableDirectives' has been removed. Please use the 'overrideConfig.linterOptions.reportUnusedDisableDirectives' option instead.");
754
+ }
755
+ }
756
+ if (typeof allowInlineConfig !== "boolean") {
757
+ errors.push("'allowInlineConfig' must be a boolean.");
758
+ }
759
+ if (typeof baseConfig !== "object") {
760
+ errors.push("'baseConfig' must be an object or null.");
761
+ }
762
+ if (typeof cache !== "boolean") {
763
+ errors.push("'cache' must be a boolean.");
764
+ }
765
+ if (!isNonEmptyString(cacheLocation)) {
766
+ errors.push("'cacheLocation' must be a non-empty string.");
767
+ }
768
+ if (
769
+ cacheStrategy !== "metadata" &&
770
+ cacheStrategy !== "content"
771
+ ) {
772
+ errors.push("'cacheStrategy' must be any of \"metadata\", \"content\".");
773
+ }
774
+ if (!isNonEmptyString(cwd) || !path.isAbsolute(cwd)) {
775
+ errors.push("'cwd' must be an absolute path.");
776
+ }
777
+ if (typeof errorOnUnmatchedPattern !== "boolean") {
778
+ errors.push("'errorOnUnmatchedPattern' must be a boolean.");
779
+ }
780
+ if (typeof fix !== "boolean" && typeof fix !== "function") {
781
+ errors.push("'fix' must be a boolean or a function.");
782
+ }
783
+ if (fixTypes !== null && !isFixTypeArray(fixTypes)) {
784
+ errors.push("'fixTypes' must be an array of any of \"directive\", \"problem\", \"suggestion\", and \"layout\".");
785
+ }
786
+ if (typeof globInputPaths !== "boolean") {
787
+ errors.push("'globInputPaths' must be a boolean.");
788
+ }
789
+ if (typeof ignore !== "boolean") {
790
+ errors.push("'ignore' must be a boolean.");
791
+ }
792
+ if (!isArrayOfNonEmptyString(ignorePatterns) && ignorePatterns !== null) {
793
+ errors.push("'ignorePatterns' must be an array of non-empty strings or null.");
794
+ }
795
+ if (typeof overrideConfig !== "object") {
796
+ errors.push("'overrideConfig' must be an object or null.");
797
+ }
798
+ if (!isNonEmptyString(overrideConfigFile) && overrideConfigFile !== null && overrideConfigFile !== true) {
799
+ errors.push("'overrideConfigFile' must be a non-empty string, null, or true.");
800
+ }
801
+ if (typeof plugins !== "object") {
802
+ errors.push("'plugins' must be an object or null.");
803
+ } else if (plugins !== null && Object.keys(plugins).includes("")) {
804
+ errors.push("'plugins' must not include an empty string.");
805
+ }
806
+ if (Array.isArray(plugins)) {
807
+ errors.push("'plugins' doesn't add plugins to configuration to load. Please use the 'overrideConfig.plugins' option instead.");
808
+ }
809
+ if (typeof warnIgnored !== "boolean") {
810
+ errors.push("'warnIgnored' must be a boolean.");
811
+ }
812
+ if (errors.length > 0) {
813
+ throw new ESLintInvalidOptionsError(errors);
814
+ }
815
+
816
+ return {
817
+ allowInlineConfig,
818
+ baseConfig,
819
+ cache,
820
+ cacheLocation,
821
+ cacheStrategy,
822
+
823
+ // when overrideConfigFile is true that means don't do config file lookup
824
+ configFile: overrideConfigFile === true ? false : overrideConfigFile,
825
+ overrideConfig,
826
+ cwd: path.normalize(cwd),
827
+ errorOnUnmatchedPattern,
828
+ fix,
829
+ fixTypes,
830
+ globInputPaths,
831
+ ignore,
832
+ ignorePatterns,
833
+ warnIgnored
834
+ };
835
+ }
836
+
837
+
838
+ //-----------------------------------------------------------------------------
839
+ // Cache-related helpers
840
+ //-----------------------------------------------------------------------------
841
+
842
+ /**
843
+ * return the cacheFile to be used by eslint, based on whether the provided parameter is
844
+ * a directory or looks like a directory (ends in `path.sep`), in which case the file
845
+ * name will be the `cacheFile/.cache_hashOfCWD`
846
+ *
847
+ * if cacheFile points to a file or looks like a file then in will just use that file
848
+ * @param {string} cacheFile The name of file to be used to store the cache
849
+ * @param {string} cwd Current working directory
850
+ * @returns {string} the resolved path to the cache file
851
+ */
852
+ function getCacheFile(cacheFile, cwd) {
853
+
854
+ /*
855
+ * make sure the path separators are normalized for the environment/os
856
+ * keeping the trailing path separator if present
857
+ */
858
+ const normalizedCacheFile = path.normalize(cacheFile);
859
+
860
+ const resolvedCacheFile = path.resolve(cwd, normalizedCacheFile);
861
+ const looksLikeADirectory = normalizedCacheFile.slice(-1) === path.sep;
862
+
863
+ /**
864
+ * return the name for the cache file in case the provided parameter is a directory
865
+ * @returns {string} the resolved path to the cacheFile
866
+ */
867
+ function getCacheFileForDirectory() {
868
+ return path.join(resolvedCacheFile, `.cache_${hash(cwd)}`);
869
+ }
870
+
871
+ let fileStats;
872
+
873
+ try {
874
+ fileStats = fs.lstatSync(resolvedCacheFile);
875
+ } catch {
876
+ fileStats = null;
877
+ }
878
+
879
+
880
+ /*
881
+ * in case the file exists we need to verify if the provided path
882
+ * is a directory or a file. If it is a directory we want to create a file
883
+ * inside that directory
884
+ */
885
+ if (fileStats) {
886
+
887
+ /*
888
+ * is a directory or is a file, but the original file the user provided
889
+ * looks like a directory but `path.resolve` removed the `last path.sep`
890
+ * so we need to still treat this like a directory
891
+ */
892
+ if (fileStats.isDirectory() || looksLikeADirectory) {
893
+ return getCacheFileForDirectory();
894
+ }
895
+
896
+ // is file so just use that file
897
+ return resolvedCacheFile;
898
+ }
899
+
900
+ /*
901
+ * here we known the file or directory doesn't exist,
902
+ * so we will try to infer if its a directory if it looks like a directory
903
+ * for the current operating system.
904
+ */
905
+
906
+ // if the last character passed is a path separator we assume is a directory
907
+ if (looksLikeADirectory) {
908
+ return getCacheFileForDirectory();
909
+ }
910
+
911
+ return resolvedCacheFile;
912
+ }
913
+
914
+
915
+ //-----------------------------------------------------------------------------
916
+ // Exports
917
+ //-----------------------------------------------------------------------------
918
+
919
+ module.exports = {
920
+ isGlobPattern,
921
+ findFiles,
922
+
923
+ isNonEmptyString,
924
+ isArrayOfNonEmptyString,
925
+
926
+ createIgnoreResult,
927
+ isErrorMessage,
928
+
929
+ processOptions,
930
+
931
+ getCacheFile
932
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/eslint/eslint.js ADDED
@@ -0,0 +1,707 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Main API Class
3
+ * @author Kai Cataldo
4
+ * @author Toru Nagashima
5
+ */
6
+
7
+ "use strict";
8
+
9
+ //------------------------------------------------------------------------------
10
+ // Requirements
11
+ //------------------------------------------------------------------------------
12
+
13
+ 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");
18
+ const {
19
+ Legacy: {
20
+ ConfigOps: {
21
+ getRuleSeverity
22
+ }
23
+ }
24
+ } = require("@eslint/eslintrc");
25
+ const { version } = require("../../package.json");
26
+
27
+ //------------------------------------------------------------------------------
28
+ // Typedefs
29
+ //------------------------------------------------------------------------------
30
+
31
+ /** @typedef {import("../cli-engine/cli-engine").LintReport} CLIEngineLintReport */
32
+ /** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */
33
+ /** @typedef {import("../shared/types").ConfigData} ConfigData */
34
+ /** @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
+ /** @typedef {import("../shared/types").LintResult} LintResult */
39
+ /** @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
+ */
46
+
47
+ /**
48
+ * The options with which to configure the ESLint instance.
49
+ * @typedef {Object} ESLintOptions
50
+ * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments.
51
+ * @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this instance
52
+ * @property {boolean} [cache] Enable result caching.
53
+ * @property {string} [cacheLocation] The cache file to use instead of .eslintcache.
54
+ * @property {"metadata" | "content"} [cacheStrategy] The strategy used to detect changed files.
55
+ * @property {string} [cwd] The value to use for the current working directory.
56
+ * @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
+ * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean.
59
+ * @property {string[]} [fixTypes] Array of rule types to apply fixes for.
60
+ * @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.
63
+ * @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
+ */
85
+
86
+ //------------------------------------------------------------------------------
87
+ // Helpers
88
+ //------------------------------------------------------------------------------
89
+
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
+ }
144
+
145
+ /**
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.
150
+ */
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
304
+ };
305
+ }
306
+
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;
317
+ }
318
+ }
319
+ }
320
+ return false;
321
+ }
322
+
323
+ /**
324
+ * Create rulesMeta object.
325
+ * @param {Map<string,Rule>} rules a map of rules from which to generate the object.
326
+ * @returns {Object} metadata for all enabled rules.
327
+ */
328
+ function createRulesMeta(rules) {
329
+ return Array.from(rules).reduce((retVal, [id, rule]) => {
330
+ retVal[id] = rule.meta;
331
+ return retVal;
332
+ }, {});
333
+ }
334
+
335
+ /** @type {WeakMap<ExtractedConfig, DeprecatedRuleInfo[]>} */
336
+ const usedDeprecatedRulesCache = new WeakMap();
337
+
338
+ /**
339
+ * Create used deprecated rule list.
340
+ * @param {CLIEngine} cliEngine The CLIEngine instance.
341
+ * @param {string} maybeFilePath The absolute path to a lint target file or `"<text>"`.
342
+ * @returns {DeprecatedRuleInfo[]} The used deprecated rule list.
343
+ */
344
+ function getOrFindUsedDeprecatedRules(cliEngine, maybeFilePath) {
345
+ const {
346
+ configArrayFactory,
347
+ options: { cwd }
348
+ } = getCLIEngineInternalSlots(cliEngine);
349
+ const filePath = path.isAbsolute(maybeFilePath)
350
+ ? maybeFilePath
351
+ : path.join(cwd, "__placeholder__.js");
352
+ const configArray = configArrayFactory.getConfigArrayForFile(filePath);
353
+ const config = configArray.extractConfig(filePath);
354
+
355
+ // Most files use the same config, so cache it.
356
+ if (!usedDeprecatedRulesCache.has(config)) {
357
+ const pluginRules = configArray.pluginRules;
358
+ const retv = [];
359
+
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 || [] });
369
+ }
370
+ }
371
+
372
+ usedDeprecatedRulesCache.set(config, Object.freeze(retv));
373
+ }
374
+
375
+ return usedDeprecatedRulesCache.get(config);
376
+ }
377
+
378
+ /**
379
+ * Processes the linting results generated by a CLIEngine linting report to
380
+ * match the ESLint class's API.
381
+ * @param {CLIEngine} cliEngine The CLIEngine instance.
382
+ * @param {CLIEngineLintReport} report The CLIEngine linting report to process.
383
+ * @returns {LintResult[]} The processed linting results.
384
+ */
385
+ function processCLIEngineLintReport(cliEngine, { results }) {
386
+ const descriptor = {
387
+ configurable: true,
388
+ enumerable: true,
389
+ get() {
390
+ return getOrFindUsedDeprecatedRules(cliEngine, this.filePath);
391
+ }
392
+ };
393
+
394
+ for (const result of results) {
395
+ Object.defineProperty(result, "usedDeprecatedRules", descriptor);
396
+ }
397
+
398
+ return results;
399
+ }
400
+
401
+ /**
402
+ * An Array.prototype.sort() compatible compare function to order results by their file path.
403
+ * @param {LintResult} a The first lint result.
404
+ * @param {LintResult} b The second lint result.
405
+ * @returns {number} An integer representing the order in which the two results should occur.
406
+ */
407
+ function compareResultsByFilePath(a, b) {
408
+ if (a.filePath < b.filePath) {
409
+ return -1;
410
+ }
411
+
412
+ if (a.filePath > b.filePath) {
413
+ return 1;
414
+ }
415
+
416
+ return 0;
417
+ }
418
+
419
+ /**
420
+ * Main API.
421
+ */
422
+ class ESLint {
423
+
424
+ /**
425
+ * Creates a new instance of the main ESLint API.
426
+ * @param {ESLintOptions} options The options for this instance.
427
+ */
428
+ constructor(options = {}) {
429
+ 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;
436
+
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.
441
+ */
442
+ if (hasDefinedProperty(options.overrideConfig)) {
443
+ configArrayFactory.setOverrideConfig(options.overrideConfig);
444
+ updated = true;
445
+ }
446
+
447
+ // Update caches.
448
+ if (updated) {
449
+ configArrayFactory.clearCache();
450
+ lastConfigArrays[0] = configArrayFactory.getConfigArrayForFile();
451
+ }
452
+
453
+ // Initialize private properties.
454
+ privateMembersMap.set(this, {
455
+ cliEngine,
456
+ options: processedOptions
457
+ });
458
+ }
459
+
460
+ /**
461
+ * The version text.
462
+ * @type {string}
463
+ */
464
+ static get version() {
465
+ return version;
466
+ }
467
+
468
+ /**
469
+ * Outputs fixes from the given results to files.
470
+ * @param {LintResult[]} results The lint results.
471
+ * @returns {Promise<void>} Returns a promise that is used to track side effects.
472
+ */
473
+ static async outputFixes(results) {
474
+ if (!Array.isArray(results)) {
475
+ throw new Error("'results' must be an array");
476
+ }
477
+
478
+ await Promise.all(
479
+ results
480
+ .filter(result => {
481
+ if (typeof result !== "object" || result === null) {
482
+ throw new Error("'results' must include only objects");
483
+ }
484
+ return (
485
+ typeof result.output === "string" &&
486
+ path.isAbsolute(result.filePath)
487
+ );
488
+ })
489
+ .map(r => writeFile(r.filePath, r.output))
490
+ );
491
+ }
492
+
493
+ /**
494
+ * Returns results that only contains errors.
495
+ * @param {LintResult[]} results The results to filter.
496
+ * @returns {LintResult[]} The filtered results.
497
+ */
498
+ static getErrorResults(results) {
499
+ return CLIEngine.getErrorResults(results);
500
+ }
501
+
502
+ /**
503
+ * Returns meta objects for each rule represented in the lint results.
504
+ * @param {LintResult[]} results The results to fetch rules meta for.
505
+ * @returns {Object} A mapping of ruleIds to rule meta objects.
506
+ */
507
+ getRulesMetaForResults(results) {
508
+
509
+ const resultRuleIds = new Set();
510
+
511
+ // first gather all ruleIds from all results
512
+
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
+ }
520
+ }
521
+
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();
527
+
528
+ for (const [ruleId, rule] of rules) {
529
+ if (resultRuleIds.has(ruleId)) {
530
+ resultRules.set(ruleId, rule);
531
+ }
532
+ }
533
+
534
+ return createRulesMeta(resultRules);
535
+
536
+ }
537
+
538
+ /**
539
+ * Executes the current configuration on an array of file and directory names.
540
+ * @param {string[]} patterns An array of file and directory names.
541
+ * @returns {Promise<LintResult[]>} The results of linting the file patterns given.
542
+ */
543
+ 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");
546
+ }
547
+ const { cliEngine } = privateMembersMap.get(this);
548
+
549
+ return processCLIEngineLintReport(
550
+ cliEngine,
551
+ cliEngine.executeOnFiles(patterns)
552
+ );
553
+ }
554
+
555
+ /**
556
+ * Executes the current configuration on text.
557
+ * @param {string} code A string of JavaScript code to lint.
558
+ * @param {Object} [options] The options.
559
+ * @param {string} [options.filePath] The path to the file of the source code.
560
+ * @param {boolean} [options.warnIgnored] When set to true, warn if given filePath is an ignored path.
561
+ * @returns {Promise<LintResult[]>} The results of linting the string of code given.
562
+ */
563
+ async lintText(code, options = {}) {
564
+ if (typeof code !== "string") {
565
+ throw new Error("'code' must be a string");
566
+ }
567
+ if (typeof options !== "object") {
568
+ throw new Error("'options' must be an object, null, or undefined");
569
+ }
570
+ const {
571
+ filePath,
572
+ warnIgnored = false,
573
+ ...unknownOptions
574
+ } = options || {};
575
+
576
+ const unknownOptionKeys = Object.keys(unknownOptions);
577
+
578
+ if (unknownOptionKeys.length > 0) {
579
+ throw new Error(`'options' must not include the unknown option(s): ${unknownOptionKeys.join(", ")}`);
580
+ }
581
+
582
+ if (filePath !== void 0 && !isNonEmptyString(filePath)) {
583
+ throw new Error("'options.filePath' must be a non-empty string or undefined");
584
+ }
585
+ if (typeof warnIgnored !== "boolean") {
586
+ throw new Error("'options.warnIgnored' must be a boolean or undefined");
587
+ }
588
+
589
+ const { cliEngine } = privateMembersMap.get(this);
590
+
591
+ return processCLIEngineLintReport(
592
+ cliEngine,
593
+ cliEngine.executeOnText(code, filePath, warnIgnored)
594
+ );
595
+ }
596
+
597
+ /**
598
+ * Returns the formatter representing the given formatter name.
599
+ * @param {string} [name] The name of the formatter to load.
600
+ * The following values are allowed:
601
+ * - `undefined` ... Load `stylish` builtin formatter.
602
+ * - A builtin formatter name ... Load the builtin formatter.
603
+ * - A third-party formatter name:
604
+ * - `foo` → `eslint-formatter-foo`
605
+ * - `@foo` → `@foo/eslint-formatter`
606
+ * - `@foo/bar` → `@foo/eslint-formatter-bar`
607
+ * - A file path ... Load the file.
608
+ * @returns {Promise<LoadedFormatter>} A promise resolving to the formatter object.
609
+ * This promise will be rejected if the given formatter was not found or not
610
+ * a function.
611
+ */
612
+ async loadFormatter(name = "stylish") {
613
+ if (typeof name !== "string") {
614
+ throw new Error("'name' must be a string");
615
+ }
616
+
617
+ const { cliEngine, options } = privateMembersMap.get(this);
618
+ const formatter = cliEngine.getFormatter(name);
619
+
620
+ if (typeof formatter !== "function") {
621
+ throw new Error(`Formatter must be a function, but got a ${typeof formatter}.`);
622
+ }
623
+
624
+ return {
625
+
626
+ /**
627
+ * The main formatter method.
628
+ * @param {LintResult[]} results The lint results to format.
629
+ * @param {ResultsMeta} resultsMeta Warning count and max threshold.
630
+ * @returns {string | Promise<string>} The formatted lint results.
631
+ */
632
+ format(results, resultsMeta) {
633
+ let rulesMeta = null;
634
+
635
+ results.sort(compareResultsByFilePath);
636
+
637
+ return formatter(results, {
638
+ ...resultsMeta,
639
+ get cwd() {
640
+ return options.cwd;
641
+ },
642
+ get rulesMeta() {
643
+ if (!rulesMeta) {
644
+ rulesMeta = createRulesMeta(cliEngine.getRules());
645
+ }
646
+
647
+ return rulesMeta;
648
+ }
649
+ });
650
+ }
651
+ };
652
+ }
653
+
654
+ /**
655
+ * Returns a configuration object for the given file based on the CLI options.
656
+ * This is the same logic used by the ESLint CLI executable to determine
657
+ * configuration for each file it processes.
658
+ * @param {string} filePath The path of the file to retrieve a config object for.
659
+ * @returns {Promise<ConfigData>} A configuration object for the file.
660
+ */
661
+ async calculateConfigForFile(filePath) {
662
+ if (!isNonEmptyString(filePath)) {
663
+ throw new Error("'filePath' must be a non-empty string");
664
+ }
665
+ const { cliEngine } = privateMembersMap.get(this);
666
+
667
+ return cliEngine.getConfigForFile(filePath);
668
+ }
669
+
670
+ /**
671
+ * Checks if a given path is ignored by ESLint.
672
+ * @param {string} filePath The path of the file to check.
673
+ * @returns {Promise<boolean>} Whether or not the given path is ignored.
674
+ */
675
+ 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);
680
+
681
+ return cliEngine.isPathIgnored(filePath);
682
+ }
683
+ }
684
+
685
+ /**
686
+ * The type of configuration used by this class.
687
+ * @type {string}
688
+ * @static
689
+ */
690
+ ESLint.configType = "eslintrc";
691
+
692
+ //------------------------------------------------------------------------------
693
+ // Public Interface
694
+ //------------------------------------------------------------------------------
695
+
696
+ module.exports = {
697
+ 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
+ }
707
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/eslint/flat-eslint.js ADDED
@@ -0,0 +1,1159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { existsSync } = require("fs");
15
+ const path = require("path");
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");
20
+ const {
21
+ Legacy: {
22
+ ConfigOps: {
23
+ getRuleSeverity
24
+ },
25
+ ModuleResolver,
26
+ naming
27
+ }
28
+ } = require("@eslint/eslintrc");
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
+
46
+ /*
47
+ * This is necessary to allow overwriting writeFile for testing purposes.
48
+ * We can just use fs/promises once we drop Node.js 12 support.
49
+ */
50
+
51
+ //------------------------------------------------------------------------------
52
+ // Typedefs
53
+ //------------------------------------------------------------------------------
54
+
55
+ // For VSCode IntelliSense
56
+ /** @typedef {import("../shared/types").ConfigData} ConfigData */
57
+ /** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */
58
+ /** @typedef {import("../shared/types").LintMessage} LintMessage */
59
+ /** @typedef {import("../shared/types").LintResult} LintResult */
60
+ /** @typedef {import("../shared/types").ParserOptions} ParserOptions */
61
+ /** @typedef {import("../shared/types").Plugin} Plugin */
62
+ /** @typedef {import("../shared/types").ResultsMeta} ResultsMeta */
63
+ /** @typedef {import("../shared/types").RuleConf} RuleConf */
64
+ /** @typedef {import("../shared/types").Rule} Rule */
65
+ /** @typedef {ReturnType<ConfigArray.extractConfig>} ExtractedConfig */
66
+
67
+ /**
68
+ * The options with which to configure the ESLint instance.
69
+ * @typedef {Object} FlatESLintOptions
70
+ * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments.
71
+ * @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this instance
72
+ * @property {boolean} [cache] Enable result caching.
73
+ * @property {string} [cacheLocation] The cache file to use instead of .eslintcache.
74
+ * @property {"metadata" | "content"} [cacheStrategy] The strategy used to detect changed files.
75
+ * @property {string} [cwd] The value to use for the current working directory.
76
+ * @property {boolean} [errorOnUnmatchedPattern] If `false` then `ESLint#lintFiles()` doesn't throw even if no target files found. Defaults to `true`.
77
+ * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean.
78
+ * @property {string[]} [fixTypes] Array of rule types to apply fixes for.
79
+ * @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.
80
+ * @property {boolean} [ignore] False disables all ignore patterns except for the default ones.
81
+ * @property {string[]} [ignorePatterns] Ignore file patterns to use in addition to config ignores. These patterns are relative to `cwd`.
82
+ * @property {ConfigData} [overrideConfig] Override config object, overrides all configs used with this instance
83
+ * @property {boolean|string} [overrideConfigFile] Searches for default config file when falsy;
84
+ * doesn't do any config file lookup when `true`; considered to be a config filename
85
+ * when a string.
86
+ * @property {Record<string,Plugin>} [plugins] An array of plugin implementations.
87
+ * @property {boolean} warnIgnored Show warnings when the file list includes ignored files
88
+ */
89
+
90
+ //------------------------------------------------------------------------------
91
+ // Helpers
92
+ //------------------------------------------------------------------------------
93
+
94
+ const FLAT_CONFIG_FILENAMES = [
95
+ "eslint.config.js",
96
+ "eslint.config.mjs",
97
+ "eslint.config.cjs"
98
+ ];
99
+ const debug = require("debug")("eslint:flat-eslint");
100
+ const removedFormatters = new Set(["table", "codeframe"]);
101
+ const privateMembers = new WeakMap();
102
+ const importedConfigFileModificationTime = new Map();
103
+
104
+ /**
105
+ * It will calculate the error and warning count for collection of messages per file
106
+ * @param {LintMessage[]} messages Collection of messages
107
+ * @returns {Object} Contains the stats
108
+ * @private
109
+ */
110
+ function calculateStatsPerFile(messages) {
111
+ const stat = {
112
+ errorCount: 0,
113
+ fatalErrorCount: 0,
114
+ warningCount: 0,
115
+ fixableErrorCount: 0,
116
+ fixableWarningCount: 0
117
+ };
118
+
119
+ for (let i = 0; i < messages.length; i++) {
120
+ const message = messages[i];
121
+
122
+ if (message.fatal || message.severity === 2) {
123
+ stat.errorCount++;
124
+ if (message.fatal) {
125
+ stat.fatalErrorCount++;
126
+ }
127
+ if (message.fix) {
128
+ stat.fixableErrorCount++;
129
+ }
130
+ } else {
131
+ stat.warningCount++;
132
+ if (message.fix) {
133
+ stat.fixableWarningCount++;
134
+ }
135
+ }
136
+ }
137
+ return stat;
138
+ }
139
+
140
+ /**
141
+ * Create rulesMeta object.
142
+ * @param {Map<string,Rule>} rules a map of rules from which to generate the object.
143
+ * @returns {Object} metadata for all enabled rules.
144
+ */
145
+ function createRulesMeta(rules) {
146
+ return Array.from(rules).reduce((retVal, [id, rule]) => {
147
+ retVal[id] = rule.meta;
148
+ return retVal;
149
+ }, {});
150
+ }
151
+
152
+ /**
153
+ * Return the absolute path of a file named `"__placeholder__.js"` in a given directory.
154
+ * This is used as a replacement for a missing file path.
155
+ * @param {string} cwd An absolute directory path.
156
+ * @returns {string} The absolute path of a file named `"__placeholder__.js"` in the given directory.
157
+ */
158
+ function getPlaceholderPath(cwd) {
159
+ return path.join(cwd, "__placeholder__.js");
160
+ }
161
+
162
+ /** @type {WeakMap<ExtractedConfig, DeprecatedRuleInfo[]>} */
163
+ const usedDeprecatedRulesCache = new WeakMap();
164
+
165
+ /**
166
+ * Create used deprecated rule list.
167
+ * @param {CLIEngine} eslint The CLIEngine instance.
168
+ * @param {string} maybeFilePath The absolute path to a lint target file or `"<text>"`.
169
+ * @returns {DeprecatedRuleInfo[]} The used deprecated rule list.
170
+ */
171
+ function getOrFindUsedDeprecatedRules(eslint, maybeFilePath) {
172
+ const {
173
+ configs,
174
+ options: { cwd }
175
+ } = privateMembers.get(eslint);
176
+ const filePath = path.isAbsolute(maybeFilePath)
177
+ ? maybeFilePath
178
+ : getPlaceholderPath(cwd);
179
+ const config = configs.getConfig(filePath);
180
+
181
+ // Most files use the same config, so cache it.
182
+ if (config && !usedDeprecatedRulesCache.has(config)) {
183
+ const retv = [];
184
+
185
+ if (config.rules) {
186
+ for (const [ruleId, ruleConf] of Object.entries(config.rules)) {
187
+ if (getRuleSeverity(ruleConf) === 0) {
188
+ continue;
189
+ }
190
+ const rule = getRuleFromConfig(ruleId, config);
191
+ const meta = rule && rule.meta;
192
+
193
+ if (meta && meta.deprecated) {
194
+ retv.push({ ruleId, replacedBy: meta.replacedBy || [] });
195
+ }
196
+ }
197
+ }
198
+
199
+
200
+ usedDeprecatedRulesCache.set(config, Object.freeze(retv));
201
+ }
202
+
203
+ return config ? usedDeprecatedRulesCache.get(config) : Object.freeze([]);
204
+ }
205
+
206
+ /**
207
+ * Processes the linting results generated by a CLIEngine linting report to
208
+ * match the ESLint class's API.
209
+ * @param {CLIEngine} eslint The CLIEngine instance.
210
+ * @param {CLIEngineLintReport} report The CLIEngine linting report to process.
211
+ * @returns {LintResult[]} The processed linting results.
212
+ */
213
+ function processLintReport(eslint, { results }) {
214
+ const descriptor = {
215
+ configurable: true,
216
+ enumerable: true,
217
+ get() {
218
+ return getOrFindUsedDeprecatedRules(eslint, this.filePath);
219
+ }
220
+ };
221
+
222
+ for (const result of results) {
223
+ Object.defineProperty(result, "usedDeprecatedRules", descriptor);
224
+ }
225
+
226
+ return results;
227
+ }
228
+
229
+ /**
230
+ * An Array.prototype.sort() compatible compare function to order results by their file path.
231
+ * @param {LintResult} a The first lint result.
232
+ * @param {LintResult} b The second lint result.
233
+ * @returns {number} An integer representing the order in which the two results should occur.
234
+ */
235
+ function compareResultsByFilePath(a, b) {
236
+ if (a.filePath < b.filePath) {
237
+ return -1;
238
+ }
239
+
240
+ if (a.filePath > b.filePath) {
241
+ return 1;
242
+ }
243
+
244
+ return 0;
245
+ }
246
+
247
+ /**
248
+ * Searches from the current working directory up until finding the
249
+ * given flat config filename.
250
+ * @param {string} cwd The current working directory to search from.
251
+ * @returns {Promise<string|undefined>} The filename if found or `undefined` if not.
252
+ */
253
+ function findFlatConfigFile(cwd) {
254
+ return findUp(
255
+ FLAT_CONFIG_FILENAMES,
256
+ { cwd }
257
+ );
258
+ }
259
+
260
+ /**
261
+ * Load the config array from the given filename.
262
+ * @param {string} filePath The filename to load from.
263
+ * @returns {Promise<any>} The config loaded from the config file.
264
+ */
265
+ async function loadFlatConfigFile(filePath) {
266
+ debug(`Loading config from ${filePath}`);
267
+
268
+ const fileURL = pathToFileURL(filePath);
269
+
270
+ debug(`Config file URL is ${fileURL}`);
271
+
272
+ const mtime = (await fs.stat(filePath)).mtime.getTime();
273
+
274
+ /*
275
+ * Append a query with the config file's modification time (`mtime`) in order
276
+ * to import the current version of the config file. Without the query, `import()` would
277
+ * cache the config file module by the pathname only, and then always return
278
+ * the same version (the one that was actual when the module was imported for the first time).
279
+ *
280
+ * This ensures that the config file module is loaded and executed again
281
+ * if it has been changed since the last time it was imported.
282
+ * If it hasn't been changed, `import()` will just return the cached version.
283
+ *
284
+ * Note that we should not overuse queries (e.g., by appending the current time
285
+ * to always reload the config file module) as that could cause memory leaks
286
+ * because entries are never removed from the import cache.
287
+ */
288
+ fileURL.searchParams.append("mtime", mtime);
289
+
290
+ /*
291
+ * With queries, we can bypass the import cache. However, when import-ing a CJS module,
292
+ * Node.js uses the require infrastructure under the hood. That includes the require cache,
293
+ * which caches the config file module by its file path (queries have no effect).
294
+ * Therefore, we also need to clear the require cache before importing the config file module.
295
+ * In order to get the same behavior with ESM and CJS config files, in particular - to reload
296
+ * the config file only if it has been changed, we track file modification times and clear
297
+ * the require cache only if the file has been changed.
298
+ */
299
+ if (importedConfigFileModificationTime.get(filePath) !== mtime) {
300
+ delete require.cache[filePath];
301
+ }
302
+
303
+ const config = (await import(fileURL)).default;
304
+
305
+ importedConfigFileModificationTime.set(filePath, mtime);
306
+
307
+ return config;
308
+ }
309
+
310
+ /**
311
+ * Determines which config file to use. This is determined by seeing if an
312
+ * override config file was passed, and if so, using it; otherwise, as long
313
+ * as override config file is not explicitly set to `false`, it will search
314
+ * upwards from the cwd for a file named `eslint.config.js`.
315
+ * @param {import("./eslint").ESLintOptions} options The ESLint instance options.
316
+ * @returns {{configFilePath:string|undefined,basePath:string,error:Error|null}} Location information for
317
+ * the config file.
318
+ */
319
+ async function locateConfigFileToUse({ configFile, cwd }) {
320
+
321
+ // determine where to load config file from
322
+ let configFilePath;
323
+ let basePath = cwd;
324
+ let error = null;
325
+
326
+ if (typeof configFile === "string") {
327
+ debug(`Override config file path is ${configFile}`);
328
+ configFilePath = path.resolve(cwd, configFile);
329
+ } else if (configFile !== false) {
330
+ debug("Searching for eslint.config.js");
331
+ configFilePath = await findFlatConfigFile(cwd);
332
+
333
+ if (configFilePath) {
334
+ basePath = path.resolve(path.dirname(configFilePath));
335
+ } else {
336
+ error = new Error("Could not find config file.");
337
+ }
338
+
339
+ }
340
+
341
+ return {
342
+ configFilePath,
343
+ basePath,
344
+ error
345
+ };
346
+
347
+ }
348
+
349
+ /**
350
+ * Calculates the config array for this run based on inputs.
351
+ * @param {FlatESLint} eslint The instance to create the config array for.
352
+ * @param {import("./eslint").ESLintOptions} options The ESLint instance options.
353
+ * @returns {FlatConfigArray} The config array for `eslint``.
354
+ */
355
+ async function calculateConfigArray(eslint, {
356
+ cwd,
357
+ baseConfig,
358
+ overrideConfig,
359
+ configFile,
360
+ ignore: shouldIgnore,
361
+ ignorePatterns
362
+ }) {
363
+
364
+ // check for cached instance
365
+ const slots = privateMembers.get(eslint);
366
+
367
+ if (slots.configs) {
368
+ return slots.configs;
369
+ }
370
+
371
+ const { configFilePath, basePath, error } = await locateConfigFileToUse({ configFile, cwd });
372
+
373
+ // config file is required to calculate config
374
+ if (error) {
375
+ throw error;
376
+ }
377
+
378
+ const configs = new FlatConfigArray(baseConfig || [], { basePath, shouldIgnore });
379
+
380
+ // load config file
381
+ if (configFilePath) {
382
+ const fileConfig = await loadFlatConfigFile(configFilePath);
383
+
384
+ if (Array.isArray(fileConfig)) {
385
+ configs.push(...fileConfig);
386
+ } else {
387
+ configs.push(fileConfig);
388
+ }
389
+ }
390
+
391
+ // add in any configured defaults
392
+ configs.push(...slots.defaultConfigs);
393
+
394
+ // append command line ignore patterns
395
+ if (ignorePatterns && ignorePatterns.length > 0) {
396
+
397
+ let relativeIgnorePatterns;
398
+
399
+ /*
400
+ * If the config file basePath is different than the cwd, then
401
+ * the ignore patterns won't work correctly. Here, we adjust the
402
+ * ignore pattern to include the correct relative path. Patterns
403
+ * passed as `ignorePatterns` are relative to the cwd, whereas
404
+ * the config file basePath can be an ancestor of the cwd.
405
+ */
406
+ if (basePath === cwd) {
407
+ relativeIgnorePatterns = ignorePatterns;
408
+ } else {
409
+
410
+ const relativeIgnorePath = path.relative(basePath, cwd);
411
+
412
+ relativeIgnorePatterns = ignorePatterns.map(pattern => {
413
+ const negated = pattern.startsWith("!");
414
+ const basePattern = negated ? pattern.slice(1) : pattern;
415
+
416
+ return (negated ? "!" : "") +
417
+ path.posix.join(relativeIgnorePath, basePattern);
418
+ });
419
+ }
420
+
421
+ /*
422
+ * Ignore patterns are added to the end of the config array
423
+ * so they can override default ignores.
424
+ */
425
+ configs.push({
426
+ ignores: relativeIgnorePatterns
427
+ });
428
+ }
429
+
430
+ if (overrideConfig) {
431
+ if (Array.isArray(overrideConfig)) {
432
+ configs.push(...overrideConfig);
433
+ } else {
434
+ configs.push(overrideConfig);
435
+ }
436
+ }
437
+
438
+ await configs.normalize();
439
+
440
+ // cache the config array for this instance
441
+ slots.configs = configs;
442
+
443
+ return configs;
444
+ }
445
+
446
+ /**
447
+ * Processes an source code using ESLint.
448
+ * @param {Object} config The config object.
449
+ * @param {string} config.text The source code to verify.
450
+ * @param {string} config.cwd The path to the current working directory.
451
+ * @param {string|undefined} config.filePath The path to the file of `text`. If this is undefined, it uses `<text>`.
452
+ * @param {FlatConfigArray} config.configs The config.
453
+ * @param {boolean} config.fix If `true` then it does fix.
454
+ * @param {boolean} config.allowInlineConfig If `true` then it uses directive comments.
455
+ * @param {Linter} config.linter The linter instance to verify.
456
+ * @returns {LintResult} The result of linting.
457
+ * @private
458
+ */
459
+ function verifyText({
460
+ text,
461
+ cwd,
462
+ filePath: providedFilePath,
463
+ configs,
464
+ fix,
465
+ allowInlineConfig,
466
+ linter
467
+ }) {
468
+ const filePath = providedFilePath || "<text>";
469
+
470
+ debug(`Lint ${filePath}`);
471
+
472
+ /*
473
+ * Verify.
474
+ * `config.extractConfig(filePath)` requires an absolute path, but `linter`
475
+ * doesn't know CWD, so it gives `linter` an absolute path always.
476
+ */
477
+ const filePathToVerify = filePath === "<text>" ? getPlaceholderPath(cwd) : filePath;
478
+ const { fixed, messages, output } = linter.verifyAndFix(
479
+ text,
480
+ configs,
481
+ {
482
+ allowInlineConfig,
483
+ filename: filePathToVerify,
484
+ fix,
485
+
486
+ /**
487
+ * Check if the linter should adopt a given code block or not.
488
+ * @param {string} blockFilename The virtual filename of a code block.
489
+ * @returns {boolean} `true` if the linter should adopt the code block.
490
+ */
491
+ filterCodeBlock(blockFilename) {
492
+ return configs.getConfig(blockFilename) !== void 0;
493
+ }
494
+ }
495
+ );
496
+
497
+ // Tweak and return.
498
+ const result = {
499
+ filePath: filePath === "<text>" ? filePath : path.resolve(filePath),
500
+ messages,
501
+ suppressedMessages: linter.getSuppressedMessages(),
502
+ ...calculateStatsPerFile(messages)
503
+ };
504
+
505
+ if (fixed) {
506
+ result.output = output;
507
+ }
508
+
509
+ if (
510
+ result.errorCount + result.warningCount > 0 &&
511
+ typeof result.output === "undefined"
512
+ ) {
513
+ result.source = text;
514
+ }
515
+
516
+ return result;
517
+ }
518
+
519
+ /**
520
+ * Checks whether a message's rule type should be fixed.
521
+ * @param {LintMessage} message The message to check.
522
+ * @param {FlatConfig} config The config for the file that generated the message.
523
+ * @param {string[]} fixTypes An array of fix types to check.
524
+ * @returns {boolean} Whether the message should be fixed.
525
+ */
526
+ function shouldMessageBeFixed(message, config, fixTypes) {
527
+ if (!message.ruleId) {
528
+ return fixTypes.has("directive");
529
+ }
530
+
531
+ const rule = message.ruleId && getRuleFromConfig(message.ruleId, config);
532
+
533
+ return Boolean(rule && rule.meta && fixTypes.has(rule.meta.type));
534
+ }
535
+
536
+ /**
537
+ * Creates an error to be thrown when an array of results passed to `getRulesMetaForResults` was not created by the current engine.
538
+ * @returns {TypeError} An error object.
539
+ */
540
+ function createExtraneousResultsError() {
541
+ return new TypeError("Results object was not created from this ESLint instance.");
542
+ }
543
+
544
+ /**
545
+ * Creates a fixer function based on the provided fix, fixTypesSet, and config.
546
+ * @param {Function|boolean} fix The original fix option.
547
+ * @param {Set<string>} fixTypesSet A set of fix types to filter messages for fixing.
548
+ * @param {FlatConfig} config The config for the file that generated the message.
549
+ * @returns {Function|boolean} The fixer function or the original fix value.
550
+ */
551
+ function getFixerForFixTypes(fix, fixTypesSet, config) {
552
+ if (!fix || !fixTypesSet) {
553
+ return fix;
554
+ }
555
+
556
+ const originalFix = (typeof fix === "function") ? fix : () => true;
557
+
558
+ return message => shouldMessageBeFixed(message, config, fixTypesSet) && originalFix(message);
559
+ }
560
+
561
+ //-----------------------------------------------------------------------------
562
+ // Main API
563
+ //-----------------------------------------------------------------------------
564
+
565
+ /**
566
+ * Primary Node.js API for ESLint.
567
+ */
568
+ class FlatESLint {
569
+
570
+ /**
571
+ * Creates a new instance of the main ESLint API.
572
+ * @param {FlatESLintOptions} options The options for this instance.
573
+ */
574
+ constructor(options = {}) {
575
+
576
+ const defaultConfigs = [];
577
+ const processedOptions = processOptions(options);
578
+ const linter = new Linter({
579
+ cwd: processedOptions.cwd,
580
+ configType: "flat"
581
+ });
582
+
583
+ const cacheFilePath = getCacheFile(
584
+ processedOptions.cacheLocation,
585
+ processedOptions.cwd
586
+ );
587
+
588
+ const lintResultCache = processedOptions.cache
589
+ ? new LintResultCache(cacheFilePath, processedOptions.cacheStrategy)
590
+ : null;
591
+
592
+ privateMembers.set(this, {
593
+ options: processedOptions,
594
+ linter,
595
+ cacheFilePath,
596
+ lintResultCache,
597
+ defaultConfigs,
598
+ configs: null
599
+ });
600
+
601
+ /**
602
+ * If additional plugins are passed in, add that to the default
603
+ * configs for this instance.
604
+ */
605
+ if (options.plugins) {
606
+
607
+ const plugins = {};
608
+
609
+ for (const [pluginName, plugin] of Object.entries(options.plugins)) {
610
+ plugins[naming.getShorthandName(pluginName, "eslint-plugin")] = plugin;
611
+ }
612
+
613
+ defaultConfigs.push({
614
+ plugins
615
+ });
616
+ }
617
+
618
+ }
619
+
620
+ /**
621
+ * The version text.
622
+ * @type {string}
623
+ */
624
+ static get version() {
625
+ return version;
626
+ }
627
+
628
+ /**
629
+ * Outputs fixes from the given results to files.
630
+ * @param {LintResult[]} results The lint results.
631
+ * @returns {Promise<void>} Returns a promise that is used to track side effects.
632
+ */
633
+ static async outputFixes(results) {
634
+ if (!Array.isArray(results)) {
635
+ throw new Error("'results' must be an array");
636
+ }
637
+
638
+ await Promise.all(
639
+ results
640
+ .filter(result => {
641
+ if (typeof result !== "object" || result === null) {
642
+ throw new Error("'results' must include only objects");
643
+ }
644
+ return (
645
+ typeof result.output === "string" &&
646
+ path.isAbsolute(result.filePath)
647
+ );
648
+ })
649
+ .map(r => fs.writeFile(r.filePath, r.output))
650
+ );
651
+ }
652
+
653
+ /**
654
+ * Returns results that only contains errors.
655
+ * @param {LintResult[]} results The results to filter.
656
+ * @returns {LintResult[]} The filtered results.
657
+ */
658
+ static getErrorResults(results) {
659
+ const filtered = [];
660
+
661
+ results.forEach(result => {
662
+ const filteredMessages = result.messages.filter(isErrorMessage);
663
+ const filteredSuppressedMessages = result.suppressedMessages.filter(isErrorMessage);
664
+
665
+ if (filteredMessages.length > 0) {
666
+ filtered.push({
667
+ ...result,
668
+ messages: filteredMessages,
669
+ suppressedMessages: filteredSuppressedMessages,
670
+ errorCount: filteredMessages.length,
671
+ warningCount: 0,
672
+ fixableErrorCount: result.fixableErrorCount,
673
+ fixableWarningCount: 0
674
+ });
675
+ }
676
+ });
677
+
678
+ return filtered;
679
+ }
680
+
681
+ /**
682
+ * Returns meta objects for each rule represented in the lint results.
683
+ * @param {LintResult[]} results The results to fetch rules meta for.
684
+ * @returns {Object} A mapping of ruleIds to rule meta objects.
685
+ * @throws {TypeError} When the results object wasn't created from this ESLint instance.
686
+ * @throws {TypeError} When a plugin or rule is missing.
687
+ */
688
+ getRulesMetaForResults(results) {
689
+
690
+ // short-circuit simple case
691
+ if (results.length === 0) {
692
+ return {};
693
+ }
694
+
695
+ const resultRules = new Map();
696
+ const {
697
+ configs,
698
+ options: { cwd }
699
+ } = privateMembers.get(this);
700
+
701
+ /*
702
+ * We can only accurately return rules meta information for linting results if the
703
+ * results were created by this instance. Otherwise, the necessary rules data is
704
+ * not available. So if the config array doesn't already exist, just throw an error
705
+ * to let the user know we can't do anything here.
706
+ */
707
+ if (!configs) {
708
+ throw createExtraneousResultsError();
709
+ }
710
+
711
+ for (const result of results) {
712
+
713
+ /*
714
+ * Normalize filename for <text>.
715
+ */
716
+ const filePath = result.filePath === "<text>"
717
+ ? getPlaceholderPath(cwd) : result.filePath;
718
+ const allMessages = result.messages.concat(result.suppressedMessages);
719
+
720
+ for (const { ruleId } of allMessages) {
721
+ if (!ruleId) {
722
+ continue;
723
+ }
724
+
725
+ /*
726
+ * All of the plugin and rule information is contained within the
727
+ * calculated config for the given file.
728
+ */
729
+ const config = configs.getConfig(filePath);
730
+
731
+ if (!config) {
732
+ throw createExtraneousResultsError();
733
+ }
734
+ const rule = getRuleFromConfig(ruleId, config);
735
+
736
+ // ignore unknown rules
737
+ if (rule) {
738
+ resultRules.set(ruleId, rule);
739
+ }
740
+ }
741
+ }
742
+
743
+ return createRulesMeta(resultRules);
744
+ }
745
+
746
+ /**
747
+ * Executes the current configuration on an array of file and directory names.
748
+ * @param {string|string[]} patterns An array of file and directory names.
749
+ * @returns {Promise<LintResult[]>} The results of linting the file patterns given.
750
+ */
751
+ async lintFiles(patterns) {
752
+ if (!isNonEmptyString(patterns) && !isArrayOfNonEmptyString(patterns)) {
753
+ throw new Error("'patterns' must be a non-empty string or an array of non-empty strings");
754
+ }
755
+
756
+ const {
757
+ cacheFilePath,
758
+ lintResultCache,
759
+ linter,
760
+ options: eslintOptions
761
+ } = privateMembers.get(this);
762
+ const configs = await calculateConfigArray(this, eslintOptions);
763
+ const {
764
+ allowInlineConfig,
765
+ cache,
766
+ cwd,
767
+ fix,
768
+ fixTypes,
769
+ globInputPaths,
770
+ errorOnUnmatchedPattern,
771
+ warnIgnored
772
+ } = eslintOptions;
773
+ const startTime = Date.now();
774
+ const fixTypesSet = fixTypes ? new Set(fixTypes) : null;
775
+
776
+ // Delete cache file; should this be done here?
777
+ if (!cache && cacheFilePath) {
778
+ debug(`Deleting cache file at ${cacheFilePath}`);
779
+
780
+ try {
781
+ await fs.unlink(cacheFilePath);
782
+ } catch (error) {
783
+ const errorCode = error && error.code;
784
+
785
+ // Ignore errors when no such file exists or file system is read only (and cache file does not exist)
786
+ if (errorCode !== "ENOENT" && !(errorCode === "EROFS" && !existsSync(cacheFilePath))) {
787
+ throw error;
788
+ }
789
+ }
790
+ }
791
+
792
+ const filePaths = await findFiles({
793
+ patterns: typeof patterns === "string" ? [patterns] : patterns,
794
+ cwd,
795
+ globInputPaths,
796
+ configs,
797
+ errorOnUnmatchedPattern
798
+ });
799
+
800
+ debug(`${filePaths.length} files found in: ${Date.now() - startTime}ms`);
801
+
802
+ /*
803
+ * Because we need to process multiple files, including reading from disk,
804
+ * it is most efficient to start by reading each file via promises so that
805
+ * they can be done in parallel. Then, we can lint the returned text. This
806
+ * ensures we are waiting the minimum amount of time in between lints.
807
+ */
808
+ const results = await Promise.all(
809
+
810
+ filePaths.map(filePath => {
811
+
812
+ const config = configs.getConfig(filePath);
813
+
814
+ /*
815
+ * If a filename was entered that cannot be matched
816
+ * to a config, then notify the user.
817
+ */
818
+ if (!config) {
819
+ if (warnIgnored) {
820
+ return createIgnoreResult(filePath, cwd);
821
+ }
822
+
823
+ return void 0;
824
+ }
825
+
826
+ // Skip if there is cached result.
827
+ if (lintResultCache) {
828
+ const cachedResult =
829
+ lintResultCache.getCachedLintResults(filePath, config);
830
+
831
+ if (cachedResult) {
832
+ const hadMessages =
833
+ cachedResult.messages &&
834
+ cachedResult.messages.length > 0;
835
+
836
+ if (hadMessages && fix) {
837
+ debug(`Reprocessing cached file to allow autofix: ${filePath}`);
838
+ } else {
839
+ debug(`Skipping file since it hasn't changed: ${filePath}`);
840
+ return cachedResult;
841
+ }
842
+ }
843
+ }
844
+
845
+
846
+ // set up fixer for fixTypes if necessary
847
+ const fixer = getFixerForFixTypes(fix, fixTypesSet, config);
848
+
849
+ return fs.readFile(filePath, "utf8")
850
+ .then(text => {
851
+
852
+ // do the linting
853
+ const result = verifyText({
854
+ text,
855
+ filePath,
856
+ configs,
857
+ cwd,
858
+ fix: fixer,
859
+ allowInlineConfig,
860
+ linter
861
+ });
862
+
863
+ /*
864
+ * Store the lint result in the LintResultCache.
865
+ * NOTE: The LintResultCache will remove the file source and any
866
+ * other properties that are difficult to serialize, and will
867
+ * hydrate those properties back in on future lint runs.
868
+ */
869
+ if (lintResultCache) {
870
+ lintResultCache.setCachedLintResults(filePath, config, result);
871
+ }
872
+
873
+ return result;
874
+ });
875
+
876
+ })
877
+ );
878
+
879
+ // Persist the cache to disk.
880
+ if (lintResultCache) {
881
+ lintResultCache.reconcile();
882
+ }
883
+
884
+ const finalResults = results.filter(result => !!result);
885
+
886
+ return processLintReport(this, {
887
+ results: finalResults
888
+ });
889
+ }
890
+
891
+ /**
892
+ * Executes the current configuration on text.
893
+ * @param {string} code A string of JavaScript code to lint.
894
+ * @param {Object} [options] The options.
895
+ * @param {string} [options.filePath] The path to the file of the source code.
896
+ * @param {boolean} [options.warnIgnored] When set to true, warn if given filePath is an ignored path.
897
+ * @returns {Promise<LintResult[]>} The results of linting the string of code given.
898
+ */
899
+ async lintText(code, options = {}) {
900
+
901
+ // Parameter validation
902
+
903
+ if (typeof code !== "string") {
904
+ throw new Error("'code' must be a string");
905
+ }
906
+
907
+ if (typeof options !== "object") {
908
+ throw new Error("'options' must be an object, null, or undefined");
909
+ }
910
+
911
+ // Options validation
912
+
913
+ const {
914
+ filePath,
915
+ warnIgnored,
916
+ ...unknownOptions
917
+ } = options || {};
918
+
919
+ const unknownOptionKeys = Object.keys(unknownOptions);
920
+
921
+ if (unknownOptionKeys.length > 0) {
922
+ throw new Error(`'options' must not include the unknown option(s): ${unknownOptionKeys.join(", ")}`);
923
+ }
924
+
925
+ if (filePath !== void 0 && !isNonEmptyString(filePath)) {
926
+ throw new Error("'options.filePath' must be a non-empty string or undefined");
927
+ }
928
+
929
+ if (typeof warnIgnored !== "boolean" && typeof warnIgnored !== "undefined") {
930
+ throw new Error("'options.warnIgnored' must be a boolean or undefined");
931
+ }
932
+
933
+ // Now we can get down to linting
934
+
935
+ const {
936
+ linter,
937
+ options: eslintOptions
938
+ } = privateMembers.get(this);
939
+ const configs = await calculateConfigArray(this, eslintOptions);
940
+ const {
941
+ allowInlineConfig,
942
+ cwd,
943
+ fix,
944
+ fixTypes,
945
+ warnIgnored: constructorWarnIgnored
946
+ } = eslintOptions;
947
+ const results = [];
948
+ const startTime = Date.now();
949
+ const fixTypesSet = fixTypes ? new Set(fixTypes) : null;
950
+ const resolvedFilename = path.resolve(cwd, filePath || "__placeholder__.js");
951
+ const config = configs.getConfig(resolvedFilename);
952
+
953
+ const fixer = getFixerForFixTypes(fix, fixTypesSet, config);
954
+
955
+ // Clear the last used config arrays.
956
+ if (resolvedFilename && await this.isPathIgnored(resolvedFilename)) {
957
+ const shouldWarnIgnored = typeof warnIgnored === "boolean" ? warnIgnored : constructorWarnIgnored;
958
+
959
+ if (shouldWarnIgnored) {
960
+ results.push(createIgnoreResult(resolvedFilename, cwd));
961
+ }
962
+ } else {
963
+
964
+ // Do lint.
965
+ results.push(verifyText({
966
+ text: code,
967
+ filePath: resolvedFilename.endsWith("__placeholder__.js") ? "<text>" : resolvedFilename,
968
+ configs,
969
+ cwd,
970
+ fix: fixer,
971
+ allowInlineConfig,
972
+ linter
973
+ }));
974
+ }
975
+
976
+ debug(`Linting complete in: ${Date.now() - startTime}ms`);
977
+
978
+ return processLintReport(this, {
979
+ results
980
+ });
981
+
982
+ }
983
+
984
+ /**
985
+ * Returns the formatter representing the given formatter name.
986
+ * @param {string} [name] The name of the formatter to load.
987
+ * The following values are allowed:
988
+ * - `undefined` ... Load `stylish` builtin formatter.
989
+ * - A builtin formatter name ... Load the builtin formatter.
990
+ * - A third-party formatter name:
991
+ * - `foo` → `eslint-formatter-foo`
992
+ * - `@foo` → `@foo/eslint-formatter`
993
+ * - `@foo/bar` → `@foo/eslint-formatter-bar`
994
+ * - A file path ... Load the file.
995
+ * @returns {Promise<Formatter>} A promise resolving to the formatter object.
996
+ * This promise will be rejected if the given formatter was not found or not
997
+ * a function.
998
+ */
999
+ async loadFormatter(name = "stylish") {
1000
+ if (typeof name !== "string") {
1001
+ throw new Error("'name' must be a string");
1002
+ }
1003
+
1004
+ // replace \ with / for Windows compatibility
1005
+ const normalizedFormatName = name.replace(/\\/gu, "/");
1006
+ const namespace = naming.getNamespaceFromTerm(normalizedFormatName);
1007
+
1008
+ // grab our options
1009
+ const { cwd } = privateMembers.get(this).options;
1010
+
1011
+
1012
+ let formatterPath;
1013
+
1014
+ // if there's a slash, then it's a file (TODO: this check seems dubious for scoped npm packages)
1015
+ if (!namespace && normalizedFormatName.includes("/")) {
1016
+ formatterPath = path.resolve(cwd, normalizedFormatName);
1017
+ } else {
1018
+ try {
1019
+ const npmFormat = naming.normalizePackageName(normalizedFormatName, "eslint-formatter");
1020
+
1021
+ // TODO: This is pretty dirty...would be nice to clean up at some point.
1022
+ formatterPath = ModuleResolver.resolve(npmFormat, getPlaceholderPath(cwd));
1023
+ } catch {
1024
+ formatterPath = path.resolve(__dirname, "../", "cli-engine", "formatters", `${normalizedFormatName}.js`);
1025
+ }
1026
+ }
1027
+
1028
+ let formatter;
1029
+
1030
+ try {
1031
+ formatter = (await import(pathToFileURL(formatterPath))).default;
1032
+ } catch (ex) {
1033
+
1034
+ // check for formatters that have been removed
1035
+ if (removedFormatters.has(name)) {
1036
+ ex.message = `The ${name} formatter is no longer part of core ESLint. Install it manually with \`npm install -D eslint-formatter-${name}\``;
1037
+ } else {
1038
+ ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`;
1039
+ }
1040
+
1041
+ throw ex;
1042
+ }
1043
+
1044
+
1045
+ if (typeof formatter !== "function") {
1046
+ throw new TypeError(`Formatter must be a function, but got a ${typeof formatter}.`);
1047
+ }
1048
+
1049
+ const eslint = this;
1050
+
1051
+ return {
1052
+
1053
+ /**
1054
+ * The main formatter method.
1055
+ * @param {LintResults[]} results The lint results to format.
1056
+ * @param {ResultsMeta} resultsMeta Warning count and max threshold.
1057
+ * @returns {string} The formatted lint results.
1058
+ */
1059
+ format(results, resultsMeta) {
1060
+ let rulesMeta = null;
1061
+
1062
+ results.sort(compareResultsByFilePath);
1063
+
1064
+ return formatter(results, {
1065
+ ...resultsMeta,
1066
+ cwd,
1067
+ get rulesMeta() {
1068
+ if (!rulesMeta) {
1069
+ rulesMeta = eslint.getRulesMetaForResults(results);
1070
+ }
1071
+
1072
+ return rulesMeta;
1073
+ }
1074
+ });
1075
+ }
1076
+ };
1077
+ }
1078
+
1079
+ /**
1080
+ * Returns a configuration object for the given file based on the CLI options.
1081
+ * This is the same logic used by the ESLint CLI executable to determine
1082
+ * configuration for each file it processes.
1083
+ * @param {string} filePath The path of the file to retrieve a config object for.
1084
+ * @returns {Promise<ConfigData|undefined>} A configuration object for the file
1085
+ * or `undefined` if there is no configuration data for the object.
1086
+ */
1087
+ async calculateConfigForFile(filePath) {
1088
+ if (!isNonEmptyString(filePath)) {
1089
+ throw new Error("'filePath' must be a non-empty string");
1090
+ }
1091
+ const options = privateMembers.get(this).options;
1092
+ const absolutePath = path.resolve(options.cwd, filePath);
1093
+ const configs = await calculateConfigArray(this, options);
1094
+
1095
+ return configs.getConfig(absolutePath);
1096
+ }
1097
+
1098
+ /**
1099
+ * Finds the config file being used by this instance based on the options
1100
+ * passed to the constructor.
1101
+ * @returns {string|undefined} The path to the config file being used or
1102
+ * `undefined` if no config file is being used.
1103
+ */
1104
+ async findConfigFile() {
1105
+ const options = privateMembers.get(this).options;
1106
+ const { configFilePath } = await locateConfigFileToUse(options);
1107
+
1108
+ return configFilePath;
1109
+ }
1110
+
1111
+ /**
1112
+ * Checks if a given path is ignored by ESLint.
1113
+ * @param {string} filePath The path of the file to check.
1114
+ * @returns {Promise<boolean>} Whether or not the given path is ignored.
1115
+ */
1116
+ async isPathIgnored(filePath) {
1117
+ const config = await this.calculateConfigForFile(filePath);
1118
+
1119
+ return config === void 0;
1120
+ }
1121
+ }
1122
+
1123
+ /**
1124
+ * The type of configuration used by this class.
1125
+ * @type {string}
1126
+ * @static
1127
+ */
1128
+ FlatESLint.configType = "flat";
1129
+
1130
+ /**
1131
+ * Returns whether flat config should be used.
1132
+ * @param {Object} [options] The options for this function.
1133
+ * @param {string} [options.cwd] The current working directory.
1134
+ * @returns {Promise<boolean>} Whether flat config should be used.
1135
+ */
1136
+ async function shouldUseFlatConfig({ cwd = process.cwd() } = {}) {
1137
+ switch (process.env.ESLINT_USE_FLAT_CONFIG) {
1138
+ case "true":
1139
+ return true;
1140
+ case "false":
1141
+ return false;
1142
+ default:
1143
+
1144
+ /*
1145
+ * If neither explicitly enabled nor disabled, then use the presence
1146
+ * of a flat config file to determine enablement.
1147
+ */
1148
+ return !!(await findFlatConfigFile(cwd));
1149
+ }
1150
+ }
1151
+
1152
+ //------------------------------------------------------------------------------
1153
+ // Public Interface
1154
+ //------------------------------------------------------------------------------
1155
+
1156
+ module.exports = {
1157
+ FlatESLint,
1158
+ shouldUseFlatConfig
1159
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/eslint/index.js ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ "use strict";
2
+
3
+ const { ESLint } = require("./eslint");
4
+ const { FlatESLint } = require("./flat-eslint");
5
+
6
+ module.exports = {
7
+ ESLint,
8
+ FlatESLint
9
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/apply-disable-directives.js ADDED
@@ -0,0 +1,465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview A module that filters reported problems based on `eslint-disable` and `eslint-enable` comments
3
+ * @author Teddy Katz
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //------------------------------------------------------------------------------
9
+ // Typedefs
10
+ //------------------------------------------------------------------------------
11
+
12
+ /** @typedef {import("../shared/types").LintMessage} LintMessage */
13
+
14
+ //------------------------------------------------------------------------------
15
+ // Module Definition
16
+ //------------------------------------------------------------------------------
17
+
18
+ const escapeRegExp = require("escape-string-regexp");
19
+
20
+ /**
21
+ * Compares the locations of two objects in a source file
22
+ * @param {{line: number, column: number}} itemA The first object
23
+ * @param {{line: number, column: number}} itemB The second object
24
+ * @returns {number} A value less than 1 if itemA appears before itemB in the source file, greater than 1 if
25
+ * itemA appears after itemB in the source file, or 0 if itemA and itemB have the same location.
26
+ */
27
+ function compareLocations(itemA, itemB) {
28
+ return itemA.line - itemB.line || itemA.column - itemB.column;
29
+ }
30
+
31
+ /**
32
+ * Groups a set of directives into sub-arrays by their parent comment.
33
+ * @param {Iterable<Directive>} directives Unused directives to be removed.
34
+ * @returns {Directive[][]} Directives grouped by their parent comment.
35
+ */
36
+ function groupByParentComment(directives) {
37
+ const groups = new Map();
38
+
39
+ for (const directive of directives) {
40
+ const { unprocessedDirective: { parentComment } } = directive;
41
+
42
+ if (groups.has(parentComment)) {
43
+ groups.get(parentComment).push(directive);
44
+ } else {
45
+ groups.set(parentComment, [directive]);
46
+ }
47
+ }
48
+
49
+ return [...groups.values()];
50
+ }
51
+
52
+ /**
53
+ * Creates removal details for a set of directives within the same comment.
54
+ * @param {Directive[]} directives Unused directives to be removed.
55
+ * @param {Token} commentToken The backing Comment token.
56
+ * @returns {{ description, fix, unprocessedDirective }[]} Details for later creation of output Problems.
57
+ */
58
+ function createIndividualDirectivesRemoval(directives, commentToken) {
59
+
60
+ /*
61
+ * `commentToken.value` starts right after `//` or `/*`.
62
+ * All calculated offsets will be relative to this index.
63
+ */
64
+ const commentValueStart = commentToken.range[0] + "//".length;
65
+
66
+ // Find where the list of rules starts. `\S+` matches with the directive name (e.g. `eslint-disable-line`)
67
+ const listStartOffset = /^\s*\S+\s+/u.exec(commentToken.value)[0].length;
68
+
69
+ /*
70
+ * Get the list text without any surrounding whitespace. In order to preserve the original
71
+ * formatting, we don't want to change that whitespace.
72
+ *
73
+ * // eslint-disable-line rule-one , rule-two , rule-three -- comment
74
+ * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
75
+ */
76
+ const listText = commentToken.value
77
+ .slice(listStartOffset) // remove directive name and all whitespace before the list
78
+ .split(/\s-{2,}\s/u)[0] // remove `-- comment`, if it exists
79
+ .trimEnd(); // remove all whitespace after the list
80
+
81
+ /*
82
+ * We can assume that `listText` contains multiple elements.
83
+ * Otherwise, this function wouldn't be called - if there is
84
+ * only one rule in the list, then the whole comment must be removed.
85
+ */
86
+
87
+ return directives.map(directive => {
88
+ const { ruleId } = directive;
89
+
90
+ const regex = new RegExp(String.raw`(?:^|\s*,\s*)(?<quote>['"]?)${escapeRegExp(ruleId)}\k<quote>(?:\s*,\s*|$)`, "u");
91
+ const match = regex.exec(listText);
92
+ const matchedText = match[0];
93
+ const matchStartOffset = listStartOffset + match.index;
94
+ const matchEndOffset = matchStartOffset + matchedText.length;
95
+
96
+ const firstIndexOfComma = matchedText.indexOf(",");
97
+ const lastIndexOfComma = matchedText.lastIndexOf(",");
98
+
99
+ let removalStartOffset, removalEndOffset;
100
+
101
+ if (firstIndexOfComma !== lastIndexOfComma) {
102
+
103
+ /*
104
+ * Since there are two commas, this must one of the elements in the middle of the list.
105
+ * Matched range starts where the previous rule name ends, and ends where the next rule name starts.
106
+ *
107
+ * // eslint-disable-line rule-one , rule-two , rule-three -- comment
108
+ * ^^^^^^^^^^^^^^
109
+ *
110
+ * We want to remove only the content between the two commas, and also one of the commas.
111
+ *
112
+ * // eslint-disable-line rule-one , rule-two , rule-three -- comment
113
+ * ^^^^^^^^^^^
114
+ */
115
+ removalStartOffset = matchStartOffset + firstIndexOfComma;
116
+ removalEndOffset = matchStartOffset + lastIndexOfComma;
117
+
118
+ } else {
119
+
120
+ /*
121
+ * This is either the first element or the last element.
122
+ *
123
+ * If this is the first element, matched range starts where the first rule name starts
124
+ * and ends where the second rule name starts. This is exactly the range we want
125
+ * to remove so that the second rule name will start where the first one was starting
126
+ * and thus preserve the original formatting.
127
+ *
128
+ * // eslint-disable-line rule-one , rule-two , rule-three -- comment
129
+ * ^^^^^^^^^^^
130
+ *
131
+ * Similarly, if this is the last element, we've already matched the range we want to
132
+ * remove. The previous rule name will end where the last one was ending, relative
133
+ * to the content on the right side.
134
+ *
135
+ * // eslint-disable-line rule-one , rule-two , rule-three -- comment
136
+ * ^^^^^^^^^^^^^
137
+ */
138
+ removalStartOffset = matchStartOffset;
139
+ removalEndOffset = matchEndOffset;
140
+ }
141
+
142
+ return {
143
+ description: `'${ruleId}'`,
144
+ fix: {
145
+ range: [
146
+ commentValueStart + removalStartOffset,
147
+ commentValueStart + removalEndOffset
148
+ ],
149
+ text: ""
150
+ },
151
+ unprocessedDirective: directive.unprocessedDirective
152
+ };
153
+ });
154
+ }
155
+
156
+ /**
157
+ * Creates a description of deleting an entire unused disable comment.
158
+ * @param {Directive[]} directives Unused directives to be removed.
159
+ * @param {Token} commentToken The backing Comment token.
160
+ * @returns {{ description, fix, unprocessedDirective }} Details for later creation of an output Problem.
161
+ */
162
+ function createCommentRemoval(directives, commentToken) {
163
+ const { range } = commentToken;
164
+ const ruleIds = directives.filter(directive => directive.ruleId).map(directive => `'${directive.ruleId}'`);
165
+
166
+ return {
167
+ description: ruleIds.length <= 2
168
+ ? ruleIds.join(" or ")
169
+ : `${ruleIds.slice(0, ruleIds.length - 1).join(", ")}, or ${ruleIds[ruleIds.length - 1]}`,
170
+ fix: {
171
+ range,
172
+ text: " "
173
+ },
174
+ unprocessedDirective: directives[0].unprocessedDirective
175
+ };
176
+ }
177
+
178
+ /**
179
+ * Parses details from directives to create output Problems.
180
+ * @param {Iterable<Directive>} allDirectives Unused directives to be removed.
181
+ * @returns {{ description, fix, unprocessedDirective }[]} Details for later creation of output Problems.
182
+ */
183
+ function processUnusedDirectives(allDirectives) {
184
+ const directiveGroups = groupByParentComment(allDirectives);
185
+
186
+ return directiveGroups.flatMap(
187
+ directives => {
188
+ const { parentComment } = directives[0].unprocessedDirective;
189
+ const remainingRuleIds = new Set(parentComment.ruleIds);
190
+
191
+ for (const directive of directives) {
192
+ remainingRuleIds.delete(directive.ruleId);
193
+ }
194
+
195
+ return remainingRuleIds.size
196
+ ? createIndividualDirectivesRemoval(directives, parentComment.commentToken)
197
+ : [createCommentRemoval(directives, parentComment.commentToken)];
198
+ }
199
+ );
200
+ }
201
+
202
+ /**
203
+ * Collect eslint-enable comments that are removing suppressions by eslint-disable comments.
204
+ * @param {Directive[]} directives The directives to check.
205
+ * @returns {Set<Directive>} The used eslint-enable comments
206
+ */
207
+ function collectUsedEnableDirectives(directives) {
208
+
209
+ /**
210
+ * A Map of `eslint-enable` keyed by ruleIds that may be marked as used.
211
+ * If `eslint-enable` does not have a ruleId, the key will be `null`.
212
+ * @type {Map<string|null, Directive>}
213
+ */
214
+ const enabledRules = new Map();
215
+
216
+ /**
217
+ * A Set of `eslint-enable` marked as used.
218
+ * It is also the return value of `collectUsedEnableDirectives` function.
219
+ * @type {Set<Directive>}
220
+ */
221
+ const usedEnableDirectives = new Set();
222
+
223
+ /*
224
+ * Checks the directives backwards to see if the encountered `eslint-enable` is used by the previous `eslint-disable`,
225
+ * and if so, stores the `eslint-enable` in `usedEnableDirectives`.
226
+ */
227
+ for (let index = directives.length - 1; index >= 0; index--) {
228
+ const directive = directives[index];
229
+
230
+ if (directive.type === "disable") {
231
+ if (enabledRules.size === 0) {
232
+ continue;
233
+ }
234
+ if (directive.ruleId === null) {
235
+
236
+ // If encounter `eslint-disable` without ruleId,
237
+ // mark all `eslint-enable` currently held in enabledRules as used.
238
+ // e.g.
239
+ // /* eslint-disable */ <- current directive
240
+ // /* eslint-enable rule-id1 */ <- used
241
+ // /* eslint-enable rule-id2 */ <- used
242
+ // /* eslint-enable */ <- used
243
+ for (const enableDirective of enabledRules.values()) {
244
+ usedEnableDirectives.add(enableDirective);
245
+ }
246
+ enabledRules.clear();
247
+ } else {
248
+ const enableDirective = enabledRules.get(directive.ruleId);
249
+
250
+ if (enableDirective) {
251
+
252
+ // If encounter `eslint-disable` with ruleId, and there is an `eslint-enable` with the same ruleId in enabledRules,
253
+ // mark `eslint-enable` with ruleId as used.
254
+ // e.g.
255
+ // /* eslint-disable rule-id */ <- current directive
256
+ // /* eslint-enable rule-id */ <- used
257
+ usedEnableDirectives.add(enableDirective);
258
+ } else {
259
+ const enabledDirectiveWithoutRuleId = enabledRules.get(null);
260
+
261
+ if (enabledDirectiveWithoutRuleId) {
262
+
263
+ // If encounter `eslint-disable` with ruleId, and there is no `eslint-enable` with the same ruleId in enabledRules,
264
+ // mark `eslint-enable` without ruleId as used.
265
+ // e.g.
266
+ // /* eslint-disable rule-id */ <- current directive
267
+ // /* eslint-enable */ <- used
268
+ usedEnableDirectives.add(enabledDirectiveWithoutRuleId);
269
+ }
270
+ }
271
+ }
272
+ } else if (directive.type === "enable") {
273
+ if (directive.ruleId === null) {
274
+
275
+ // If encounter `eslint-enable` without ruleId, the `eslint-enable` that follows it are unused.
276
+ // So clear enabledRules.
277
+ // e.g.
278
+ // /* eslint-enable */ <- current directive
279
+ // /* eslint-enable rule-id *// <- unused
280
+ // /* eslint-enable */ <- unused
281
+ enabledRules.clear();
282
+ enabledRules.set(null, directive);
283
+ } else {
284
+ enabledRules.set(directive.ruleId, directive);
285
+ }
286
+ }
287
+ }
288
+ return usedEnableDirectives;
289
+ }
290
+
291
+ /**
292
+ * This is the same as the exported function, except that it
293
+ * doesn't handle disable-line and disable-next-line directives, and it always reports unused
294
+ * disable directives.
295
+ * @param {Object} options options for applying directives. This is the same as the options
296
+ * for the exported function, except that `reportUnusedDisableDirectives` is not supported
297
+ * (this function always reports unused disable directives).
298
+ * @returns {{problems: LintMessage[], unusedDirectives: LintMessage[]}} An object with a list
299
+ * of problems (including suppressed ones) and unused eslint-disable directives
300
+ */
301
+ function applyDirectives(options) {
302
+ const problems = [];
303
+ const usedDisableDirectives = new Set();
304
+
305
+ for (const problem of options.problems) {
306
+ let disableDirectivesForProblem = [];
307
+ let nextDirectiveIndex = 0;
308
+
309
+ while (
310
+ nextDirectiveIndex < options.directives.length &&
311
+ compareLocations(options.directives[nextDirectiveIndex], problem) <= 0
312
+ ) {
313
+ const directive = options.directives[nextDirectiveIndex++];
314
+
315
+ if (directive.ruleId === null || directive.ruleId === problem.ruleId) {
316
+ switch (directive.type) {
317
+ case "disable":
318
+ disableDirectivesForProblem.push(directive);
319
+ break;
320
+
321
+ case "enable":
322
+ disableDirectivesForProblem = [];
323
+ break;
324
+
325
+ // no default
326
+ }
327
+ }
328
+ }
329
+
330
+ if (disableDirectivesForProblem.length > 0) {
331
+ const suppressions = disableDirectivesForProblem.map(directive => ({
332
+ kind: "directive",
333
+ justification: directive.unprocessedDirective.justification
334
+ }));
335
+
336
+ if (problem.suppressions) {
337
+ problem.suppressions = problem.suppressions.concat(suppressions);
338
+ } else {
339
+ problem.suppressions = suppressions;
340
+ usedDisableDirectives.add(disableDirectivesForProblem[disableDirectivesForProblem.length - 1]);
341
+ }
342
+ }
343
+
344
+ problems.push(problem);
345
+ }
346
+
347
+ const unusedDisableDirectivesToReport = options.directives
348
+ .filter(directive => directive.type === "disable" && !usedDisableDirectives.has(directive));
349
+
350
+
351
+ const unusedEnableDirectivesToReport = new Set(
352
+ options.directives.filter(directive => directive.unprocessedDirective.type === "enable")
353
+ );
354
+
355
+ /*
356
+ * If directives has the eslint-enable directive,
357
+ * check whether the eslint-enable comment is used.
358
+ */
359
+ if (unusedEnableDirectivesToReport.size > 0) {
360
+ for (const directive of collectUsedEnableDirectives(options.directives)) {
361
+ unusedEnableDirectivesToReport.delete(directive);
362
+ }
363
+ }
364
+
365
+ const processed = processUnusedDirectives(unusedDisableDirectivesToReport)
366
+ .concat(processUnusedDirectives(unusedEnableDirectivesToReport));
367
+
368
+ const unusedDirectives = processed
369
+ .map(({ description, fix, unprocessedDirective }) => {
370
+ const { parentComment, type, line, column } = unprocessedDirective;
371
+
372
+ let message;
373
+
374
+ if (type === "enable") {
375
+ message = description
376
+ ? `Unused eslint-enable directive (no matching eslint-disable directives were found for ${description}).`
377
+ : "Unused eslint-enable directive (no matching eslint-disable directives were found).";
378
+ } else {
379
+ message = description
380
+ ? `Unused eslint-disable directive (no problems were reported from ${description}).`
381
+ : "Unused eslint-disable directive (no problems were reported).";
382
+ }
383
+ return {
384
+ ruleId: null,
385
+ message,
386
+ line: type === "disable-next-line" ? parentComment.commentToken.loc.start.line : line,
387
+ column: type === "disable-next-line" ? parentComment.commentToken.loc.start.column + 1 : column,
388
+ severity: options.reportUnusedDisableDirectives === "warn" ? 1 : 2,
389
+ nodeType: null,
390
+ ...options.disableFixes ? {} : { fix }
391
+ };
392
+ });
393
+
394
+ return { problems, unusedDirectives };
395
+ }
396
+
397
+ /**
398
+ * Given a list of directive comments (i.e. metadata about eslint-disable and eslint-enable comments) and a list
399
+ * of reported problems, adds the suppression information to the problems.
400
+ * @param {Object} options Information about directives and problems
401
+ * @param {{
402
+ * type: ("disable"|"enable"|"disable-line"|"disable-next-line"),
403
+ * ruleId: (string|null),
404
+ * line: number,
405
+ * column: number,
406
+ * justification: string
407
+ * }} options.directives Directive comments found in the file, with one-based columns.
408
+ * Two directive comments can only have the same location if they also have the same type (e.g. a single eslint-disable
409
+ * comment for two different rules is represented as two directives).
410
+ * @param {{ruleId: (string|null), line: number, column: number}[]} options.problems
411
+ * A list of problems reported by rules, sorted by increasing location in the file, with one-based columns.
412
+ * @param {"off" | "warn" | "error"} options.reportUnusedDisableDirectives If `"warn"` or `"error"`, adds additional problems for unused directives
413
+ * @param {boolean} options.disableFixes If true, it doesn't make `fix` properties.
414
+ * @returns {{ruleId: (string|null), line: number, column: number, suppressions?: {kind: string, justification: string}}[]}
415
+ * An object with a list of reported problems, the suppressed of which contain the suppression information.
416
+ */
417
+ module.exports = ({ directives, disableFixes, problems, reportUnusedDisableDirectives = "off" }) => {
418
+ const blockDirectives = directives
419
+ .filter(directive => directive.type === "disable" || directive.type === "enable")
420
+ .map(directive => Object.assign({}, directive, { unprocessedDirective: directive }))
421
+ .sort(compareLocations);
422
+
423
+ const lineDirectives = directives.flatMap(directive => {
424
+ switch (directive.type) {
425
+ case "disable":
426
+ case "enable":
427
+ return [];
428
+
429
+ case "disable-line":
430
+ return [
431
+ { type: "disable", line: directive.line, column: 1, ruleId: directive.ruleId, unprocessedDirective: directive },
432
+ { type: "enable", line: directive.line + 1, column: 0, ruleId: directive.ruleId, unprocessedDirective: directive }
433
+ ];
434
+
435
+ case "disable-next-line":
436
+ return [
437
+ { type: "disable", line: directive.line + 1, column: 1, ruleId: directive.ruleId, unprocessedDirective: directive },
438
+ { type: "enable", line: directive.line + 2, column: 0, ruleId: directive.ruleId, unprocessedDirective: directive }
439
+ ];
440
+
441
+ default:
442
+ throw new TypeError(`Unrecognized directive type '${directive.type}'`);
443
+ }
444
+ }).sort(compareLocations);
445
+
446
+ const blockDirectivesResult = applyDirectives({
447
+ problems,
448
+ directives: blockDirectives,
449
+ disableFixes,
450
+ reportUnusedDisableDirectives
451
+ });
452
+ const lineDirectivesResult = applyDirectives({
453
+ problems: blockDirectivesResult.problems,
454
+ directives: lineDirectives,
455
+ disableFixes,
456
+ reportUnusedDisableDirectives
457
+ });
458
+
459
+ return reportUnusedDisableDirectives !== "off"
460
+ ? lineDirectivesResult.problems
461
+ .concat(blockDirectivesResult.unusedDirectives)
462
+ .concat(lineDirectivesResult.unusedDirectives)
463
+ .sort(compareLocations)
464
+ : lineDirectivesResult.problems;
465
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js ADDED
@@ -0,0 +1,852 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview A class of the code path analyzer.
3
+ * @author Toru Nagashima
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //------------------------------------------------------------------------------
9
+ // Requirements
10
+ //------------------------------------------------------------------------------
11
+
12
+ const assert = require("assert"),
13
+ { breakableTypePattern } = require("../../shared/ast-utils"),
14
+ CodePath = require("./code-path"),
15
+ CodePathSegment = require("./code-path-segment"),
16
+ IdGenerator = require("./id-generator"),
17
+ debug = require("./debug-helpers");
18
+
19
+ //------------------------------------------------------------------------------
20
+ // Helpers
21
+ //------------------------------------------------------------------------------
22
+
23
+ /**
24
+ * Checks whether or not a given node is a `case` node (not `default` node).
25
+ * @param {ASTNode} node A `SwitchCase` node to check.
26
+ * @returns {boolean} `true` if the node is a `case` node (not `default` node).
27
+ */
28
+ function isCaseNode(node) {
29
+ return Boolean(node.test);
30
+ }
31
+
32
+ /**
33
+ * Checks if a given node appears as the value of a PropertyDefinition node.
34
+ * @param {ASTNode} node THe node to check.
35
+ * @returns {boolean} `true` if the node is a PropertyDefinition value,
36
+ * false if not.
37
+ */
38
+ function isPropertyDefinitionValue(node) {
39
+ const parent = node.parent;
40
+
41
+ return parent && parent.type === "PropertyDefinition" && parent.value === node;
42
+ }
43
+
44
+ /**
45
+ * Checks whether the given logical operator is taken into account for the code
46
+ * path analysis.
47
+ * @param {string} operator The operator found in the LogicalExpression node
48
+ * @returns {boolean} `true` if the operator is "&&" or "||" or "??"
49
+ */
50
+ function isHandledLogicalOperator(operator) {
51
+ return operator === "&&" || operator === "||" || operator === "??";
52
+ }
53
+
54
+ /**
55
+ * Checks whether the given assignment operator is a logical assignment operator.
56
+ * Logical assignments are taken into account for the code path analysis
57
+ * because of their short-circuiting semantics.
58
+ * @param {string} operator The operator found in the AssignmentExpression node
59
+ * @returns {boolean} `true` if the operator is "&&=" or "||=" or "??="
60
+ */
61
+ function isLogicalAssignmentOperator(operator) {
62
+ return operator === "&&=" || operator === "||=" || operator === "??=";
63
+ }
64
+
65
+ /**
66
+ * Gets the label if the parent node of a given node is a LabeledStatement.
67
+ * @param {ASTNode} node A node to get.
68
+ * @returns {string|null} The label or `null`.
69
+ */
70
+ function getLabel(node) {
71
+ if (node.parent.type === "LabeledStatement") {
72
+ return node.parent.label.name;
73
+ }
74
+ return null;
75
+ }
76
+
77
+ /**
78
+ * Checks whether or not a given logical expression node goes different path
79
+ * between the `true` case and the `false` case.
80
+ * @param {ASTNode} node A node to check.
81
+ * @returns {boolean} `true` if the node is a test of a choice statement.
82
+ */
83
+ function isForkingByTrueOrFalse(node) {
84
+ const parent = node.parent;
85
+
86
+ switch (parent.type) {
87
+ case "ConditionalExpression":
88
+ case "IfStatement":
89
+ case "WhileStatement":
90
+ case "DoWhileStatement":
91
+ case "ForStatement":
92
+ return parent.test === node;
93
+
94
+ case "LogicalExpression":
95
+ return isHandledLogicalOperator(parent.operator);
96
+
97
+ case "AssignmentExpression":
98
+ return isLogicalAssignmentOperator(parent.operator);
99
+
100
+ default:
101
+ return false;
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Gets the boolean value of a given literal node.
107
+ *
108
+ * This is used to detect infinity loops (e.g. `while (true) {}`).
109
+ * Statements preceded by an infinity loop are unreachable if the loop didn't
110
+ * have any `break` statement.
111
+ * @param {ASTNode} node A node to get.
112
+ * @returns {boolean|undefined} a boolean value if the node is a Literal node,
113
+ * otherwise `undefined`.
114
+ */
115
+ function getBooleanValueIfSimpleConstant(node) {
116
+ if (node.type === "Literal") {
117
+ return Boolean(node.value);
118
+ }
119
+ return void 0;
120
+ }
121
+
122
+ /**
123
+ * Checks that a given identifier node is a reference or not.
124
+ *
125
+ * This is used to detect the first throwable node in a `try` block.
126
+ * @param {ASTNode} node An Identifier node to check.
127
+ * @returns {boolean} `true` if the node is a reference.
128
+ */
129
+ function isIdentifierReference(node) {
130
+ const parent = node.parent;
131
+
132
+ switch (parent.type) {
133
+ case "LabeledStatement":
134
+ case "BreakStatement":
135
+ case "ContinueStatement":
136
+ case "ArrayPattern":
137
+ case "RestElement":
138
+ case "ImportSpecifier":
139
+ case "ImportDefaultSpecifier":
140
+ case "ImportNamespaceSpecifier":
141
+ case "CatchClause":
142
+ return false;
143
+
144
+ case "FunctionDeclaration":
145
+ case "FunctionExpression":
146
+ case "ArrowFunctionExpression":
147
+ case "ClassDeclaration":
148
+ case "ClassExpression":
149
+ case "VariableDeclarator":
150
+ return parent.id !== node;
151
+
152
+ case "Property":
153
+ case "PropertyDefinition":
154
+ case "MethodDefinition":
155
+ return (
156
+ parent.key !== node ||
157
+ parent.computed ||
158
+ parent.shorthand
159
+ );
160
+
161
+ case "AssignmentPattern":
162
+ return parent.key !== node;
163
+
164
+ default:
165
+ return true;
166
+ }
167
+ }
168
+
169
+ /**
170
+ * Updates the current segment with the head segment.
171
+ * This is similar to local branches and tracking branches of git.
172
+ *
173
+ * To separate the current and the head is in order to not make useless segments.
174
+ *
175
+ * In this process, both "onCodePathSegmentStart" and "onCodePathSegmentEnd"
176
+ * events are fired.
177
+ * @param {CodePathAnalyzer} analyzer The instance.
178
+ * @param {ASTNode} node The current AST node.
179
+ * @returns {void}
180
+ */
181
+ function forwardCurrentToHead(analyzer, node) {
182
+ const codePath = analyzer.codePath;
183
+ const state = CodePath.getState(codePath);
184
+ const currentSegments = state.currentSegments;
185
+ const headSegments = state.headSegments;
186
+ const end = Math.max(currentSegments.length, headSegments.length);
187
+ let i, currentSegment, headSegment;
188
+
189
+ // Fires leaving events.
190
+ for (i = 0; i < end; ++i) {
191
+ currentSegment = currentSegments[i];
192
+ headSegment = headSegments[i];
193
+
194
+ if (currentSegment !== headSegment && currentSegment) {
195
+
196
+ const eventName = currentSegment.reachable
197
+ ? "onCodePathSegmentEnd"
198
+ : "onUnreachableCodePathSegmentEnd";
199
+
200
+ debug.dump(`${eventName} ${currentSegment.id}`);
201
+
202
+ analyzer.emitter.emit(
203
+ eventName,
204
+ currentSegment,
205
+ node
206
+ );
207
+ }
208
+ }
209
+
210
+ // Update state.
211
+ state.currentSegments = headSegments;
212
+
213
+ // Fires entering events.
214
+ for (i = 0; i < end; ++i) {
215
+ currentSegment = currentSegments[i];
216
+ headSegment = headSegments[i];
217
+
218
+ if (currentSegment !== headSegment && headSegment) {
219
+
220
+ const eventName = headSegment.reachable
221
+ ? "onCodePathSegmentStart"
222
+ : "onUnreachableCodePathSegmentStart";
223
+
224
+ debug.dump(`${eventName} ${headSegment.id}`);
225
+
226
+ CodePathSegment.markUsed(headSegment);
227
+ analyzer.emitter.emit(
228
+ eventName,
229
+ headSegment,
230
+ node
231
+ );
232
+ }
233
+ }
234
+
235
+ }
236
+
237
+ /**
238
+ * Updates the current segment with empty.
239
+ * This is called at the last of functions or the program.
240
+ * @param {CodePathAnalyzer} analyzer The instance.
241
+ * @param {ASTNode} node The current AST node.
242
+ * @returns {void}
243
+ */
244
+ function leaveFromCurrentSegment(analyzer, node) {
245
+ const state = CodePath.getState(analyzer.codePath);
246
+ const currentSegments = state.currentSegments;
247
+
248
+ for (let i = 0; i < currentSegments.length; ++i) {
249
+ const currentSegment = currentSegments[i];
250
+ const eventName = currentSegment.reachable
251
+ ? "onCodePathSegmentEnd"
252
+ : "onUnreachableCodePathSegmentEnd";
253
+
254
+ debug.dump(`${eventName} ${currentSegment.id}`);
255
+
256
+ analyzer.emitter.emit(
257
+ eventName,
258
+ currentSegment,
259
+ node
260
+ );
261
+ }
262
+
263
+ state.currentSegments = [];
264
+ }
265
+
266
+ /**
267
+ * Updates the code path due to the position of a given node in the parent node
268
+ * thereof.
269
+ *
270
+ * For example, if the node is `parent.consequent`, this creates a fork from the
271
+ * current path.
272
+ * @param {CodePathAnalyzer} analyzer The instance.
273
+ * @param {ASTNode} node The current AST node.
274
+ * @returns {void}
275
+ */
276
+ function preprocess(analyzer, node) {
277
+ const codePath = analyzer.codePath;
278
+ const state = CodePath.getState(codePath);
279
+ const parent = node.parent;
280
+
281
+ switch (parent.type) {
282
+
283
+ // The `arguments.length == 0` case is in `postprocess` function.
284
+ case "CallExpression":
285
+ if (parent.optional === true && parent.arguments.length >= 1 && parent.arguments[0] === node) {
286
+ state.makeOptionalRight();
287
+ }
288
+ break;
289
+ case "MemberExpression":
290
+ if (parent.optional === true && parent.property === node) {
291
+ state.makeOptionalRight();
292
+ }
293
+ break;
294
+
295
+ case "LogicalExpression":
296
+ if (
297
+ parent.right === node &&
298
+ isHandledLogicalOperator(parent.operator)
299
+ ) {
300
+ state.makeLogicalRight();
301
+ }
302
+ break;
303
+
304
+ case "AssignmentExpression":
305
+ if (
306
+ parent.right === node &&
307
+ isLogicalAssignmentOperator(parent.operator)
308
+ ) {
309
+ state.makeLogicalRight();
310
+ }
311
+ break;
312
+
313
+ case "ConditionalExpression":
314
+ case "IfStatement":
315
+
316
+ /*
317
+ * Fork if this node is at `consequent`/`alternate`.
318
+ * `popForkContext()` exists at `IfStatement:exit` and
319
+ * `ConditionalExpression:exit`.
320
+ */
321
+ if (parent.consequent === node) {
322
+ state.makeIfConsequent();
323
+ } else if (parent.alternate === node) {
324
+ state.makeIfAlternate();
325
+ }
326
+ break;
327
+
328
+ case "SwitchCase":
329
+ if (parent.consequent[0] === node) {
330
+ state.makeSwitchCaseBody(false, !parent.test);
331
+ }
332
+ break;
333
+
334
+ case "TryStatement":
335
+ if (parent.handler === node) {
336
+ state.makeCatchBlock();
337
+ } else if (parent.finalizer === node) {
338
+ state.makeFinallyBlock();
339
+ }
340
+ break;
341
+
342
+ case "WhileStatement":
343
+ if (parent.test === node) {
344
+ state.makeWhileTest(getBooleanValueIfSimpleConstant(node));
345
+ } else {
346
+ assert(parent.body === node);
347
+ state.makeWhileBody();
348
+ }
349
+ break;
350
+
351
+ case "DoWhileStatement":
352
+ if (parent.body === node) {
353
+ state.makeDoWhileBody();
354
+ } else {
355
+ assert(parent.test === node);
356
+ state.makeDoWhileTest(getBooleanValueIfSimpleConstant(node));
357
+ }
358
+ break;
359
+
360
+ case "ForStatement":
361
+ if (parent.test === node) {
362
+ state.makeForTest(getBooleanValueIfSimpleConstant(node));
363
+ } else if (parent.update === node) {
364
+ state.makeForUpdate();
365
+ } else if (parent.body === node) {
366
+ state.makeForBody();
367
+ }
368
+ break;
369
+
370
+ case "ForInStatement":
371
+ case "ForOfStatement":
372
+ if (parent.left === node) {
373
+ state.makeForInOfLeft();
374
+ } else if (parent.right === node) {
375
+ state.makeForInOfRight();
376
+ } else {
377
+ assert(parent.body === node);
378
+ state.makeForInOfBody();
379
+ }
380
+ break;
381
+
382
+ case "AssignmentPattern":
383
+
384
+ /*
385
+ * Fork if this node is at `right`.
386
+ * `left` is executed always, so it uses the current path.
387
+ * `popForkContext()` exists at `AssignmentPattern:exit`.
388
+ */
389
+ if (parent.right === node) {
390
+ state.pushForkContext();
391
+ state.forkBypassPath();
392
+ state.forkPath();
393
+ }
394
+ break;
395
+
396
+ default:
397
+ break;
398
+ }
399
+ }
400
+
401
+ /**
402
+ * Updates the code path due to the type of a given node in entering.
403
+ * @param {CodePathAnalyzer} analyzer The instance.
404
+ * @param {ASTNode} node The current AST node.
405
+ * @returns {void}
406
+ */
407
+ function processCodePathToEnter(analyzer, node) {
408
+ let codePath = analyzer.codePath;
409
+ let state = codePath && CodePath.getState(codePath);
410
+ const parent = node.parent;
411
+
412
+ /**
413
+ * Creates a new code path and trigger the onCodePathStart event
414
+ * based on the currently selected node.
415
+ * @param {string} origin The reason the code path was started.
416
+ * @returns {void}
417
+ */
418
+ function startCodePath(origin) {
419
+ if (codePath) {
420
+
421
+ // Emits onCodePathSegmentStart events if updated.
422
+ forwardCurrentToHead(analyzer, node);
423
+ debug.dumpState(node, state, false);
424
+ }
425
+
426
+ // Create the code path of this scope.
427
+ codePath = analyzer.codePath = new CodePath({
428
+ id: analyzer.idGenerator.next(),
429
+ origin,
430
+ upper: codePath,
431
+ onLooped: analyzer.onLooped
432
+ });
433
+ state = CodePath.getState(codePath);
434
+
435
+ // Emits onCodePathStart events.
436
+ debug.dump(`onCodePathStart ${codePath.id}`);
437
+ analyzer.emitter.emit("onCodePathStart", codePath, node);
438
+ }
439
+
440
+ /*
441
+ * Special case: The right side of class field initializer is considered
442
+ * to be its own function, so we need to start a new code path in this
443
+ * case.
444
+ */
445
+ if (isPropertyDefinitionValue(node)) {
446
+ startCodePath("class-field-initializer");
447
+
448
+ /*
449
+ * Intentional fall through because `node` needs to also be
450
+ * processed by the code below. For example, if we have:
451
+ *
452
+ * class Foo {
453
+ * a = () => {}
454
+ * }
455
+ *
456
+ * In this case, we also need start a second code path.
457
+ */
458
+
459
+ }
460
+
461
+ switch (node.type) {
462
+ case "Program":
463
+ startCodePath("program");
464
+ break;
465
+
466
+ case "FunctionDeclaration":
467
+ case "FunctionExpression":
468
+ case "ArrowFunctionExpression":
469
+ startCodePath("function");
470
+ break;
471
+
472
+ case "StaticBlock":
473
+ startCodePath("class-static-block");
474
+ break;
475
+
476
+ case "ChainExpression":
477
+ state.pushChainContext();
478
+ break;
479
+ case "CallExpression":
480
+ if (node.optional === true) {
481
+ state.makeOptionalNode();
482
+ }
483
+ break;
484
+ case "MemberExpression":
485
+ if (node.optional === true) {
486
+ state.makeOptionalNode();
487
+ }
488
+ break;
489
+
490
+ case "LogicalExpression":
491
+ if (isHandledLogicalOperator(node.operator)) {
492
+ state.pushChoiceContext(
493
+ node.operator,
494
+ isForkingByTrueOrFalse(node)
495
+ );
496
+ }
497
+ break;
498
+
499
+ case "AssignmentExpression":
500
+ if (isLogicalAssignmentOperator(node.operator)) {
501
+ state.pushChoiceContext(
502
+ node.operator.slice(0, -1), // removes `=` from the end
503
+ isForkingByTrueOrFalse(node)
504
+ );
505
+ }
506
+ break;
507
+
508
+ case "ConditionalExpression":
509
+ case "IfStatement":
510
+ state.pushChoiceContext("test", false);
511
+ break;
512
+
513
+ case "SwitchStatement":
514
+ state.pushSwitchContext(
515
+ node.cases.some(isCaseNode),
516
+ getLabel(node)
517
+ );
518
+ break;
519
+
520
+ case "TryStatement":
521
+ state.pushTryContext(Boolean(node.finalizer));
522
+ break;
523
+
524
+ case "SwitchCase":
525
+
526
+ /*
527
+ * Fork if this node is after the 2st node in `cases`.
528
+ * It's similar to `else` blocks.
529
+ * The next `test` node is processed in this path.
530
+ */
531
+ if (parent.discriminant !== node && parent.cases[0] !== node) {
532
+ state.forkPath();
533
+ }
534
+ break;
535
+
536
+ case "WhileStatement":
537
+ case "DoWhileStatement":
538
+ case "ForStatement":
539
+ case "ForInStatement":
540
+ case "ForOfStatement":
541
+ state.pushLoopContext(node.type, getLabel(node));
542
+ break;
543
+
544
+ case "LabeledStatement":
545
+ if (!breakableTypePattern.test(node.body.type)) {
546
+ state.pushBreakContext(false, node.label.name);
547
+ }
548
+ break;
549
+
550
+ default:
551
+ break;
552
+ }
553
+
554
+ // Emits onCodePathSegmentStart events if updated.
555
+ forwardCurrentToHead(analyzer, node);
556
+ debug.dumpState(node, state, false);
557
+ }
558
+
559
+ /**
560
+ * Updates the code path due to the type of a given node in leaving.
561
+ * @param {CodePathAnalyzer} analyzer The instance.
562
+ * @param {ASTNode} node The current AST node.
563
+ * @returns {void}
564
+ */
565
+ function processCodePathToExit(analyzer, node) {
566
+
567
+ const codePath = analyzer.codePath;
568
+ const state = CodePath.getState(codePath);
569
+ let dontForward = false;
570
+
571
+ switch (node.type) {
572
+ case "ChainExpression":
573
+ state.popChainContext();
574
+ break;
575
+
576
+ case "IfStatement":
577
+ case "ConditionalExpression":
578
+ state.popChoiceContext();
579
+ break;
580
+
581
+ case "LogicalExpression":
582
+ if (isHandledLogicalOperator(node.operator)) {
583
+ state.popChoiceContext();
584
+ }
585
+ break;
586
+
587
+ case "AssignmentExpression":
588
+ if (isLogicalAssignmentOperator(node.operator)) {
589
+ state.popChoiceContext();
590
+ }
591
+ break;
592
+
593
+ case "SwitchStatement":
594
+ state.popSwitchContext();
595
+ break;
596
+
597
+ case "SwitchCase":
598
+
599
+ /*
600
+ * This is the same as the process at the 1st `consequent` node in
601
+ * `preprocess` function.
602
+ * Must do if this `consequent` is empty.
603
+ */
604
+ if (node.consequent.length === 0) {
605
+ state.makeSwitchCaseBody(true, !node.test);
606
+ }
607
+ if (state.forkContext.reachable) {
608
+ dontForward = true;
609
+ }
610
+ break;
611
+
612
+ case "TryStatement":
613
+ state.popTryContext();
614
+ break;
615
+
616
+ case "BreakStatement":
617
+ forwardCurrentToHead(analyzer, node);
618
+ state.makeBreak(node.label && node.label.name);
619
+ dontForward = true;
620
+ break;
621
+
622
+ case "ContinueStatement":
623
+ forwardCurrentToHead(analyzer, node);
624
+ state.makeContinue(node.label && node.label.name);
625
+ dontForward = true;
626
+ break;
627
+
628
+ case "ReturnStatement":
629
+ forwardCurrentToHead(analyzer, node);
630
+ state.makeReturn();
631
+ dontForward = true;
632
+ break;
633
+
634
+ case "ThrowStatement":
635
+ forwardCurrentToHead(analyzer, node);
636
+ state.makeThrow();
637
+ dontForward = true;
638
+ break;
639
+
640
+ case "Identifier":
641
+ if (isIdentifierReference(node)) {
642
+ state.makeFirstThrowablePathInTryBlock();
643
+ dontForward = true;
644
+ }
645
+ break;
646
+
647
+ case "CallExpression":
648
+ case "ImportExpression":
649
+ case "MemberExpression":
650
+ case "NewExpression":
651
+ case "YieldExpression":
652
+ state.makeFirstThrowablePathInTryBlock();
653
+ break;
654
+
655
+ case "WhileStatement":
656
+ case "DoWhileStatement":
657
+ case "ForStatement":
658
+ case "ForInStatement":
659
+ case "ForOfStatement":
660
+ state.popLoopContext();
661
+ break;
662
+
663
+ case "AssignmentPattern":
664
+ state.popForkContext();
665
+ break;
666
+
667
+ case "LabeledStatement":
668
+ if (!breakableTypePattern.test(node.body.type)) {
669
+ state.popBreakContext();
670
+ }
671
+ break;
672
+
673
+ default:
674
+ break;
675
+ }
676
+
677
+ // Emits onCodePathSegmentStart events if updated.
678
+ if (!dontForward) {
679
+ forwardCurrentToHead(analyzer, node);
680
+ }
681
+ debug.dumpState(node, state, true);
682
+ }
683
+
684
+ /**
685
+ * Updates the code path to finalize the current code path.
686
+ * @param {CodePathAnalyzer} analyzer The instance.
687
+ * @param {ASTNode} node The current AST node.
688
+ * @returns {void}
689
+ */
690
+ function postprocess(analyzer, node) {
691
+
692
+ /**
693
+ * Ends the code path for the current node.
694
+ * @returns {void}
695
+ */
696
+ function endCodePath() {
697
+ let codePath = analyzer.codePath;
698
+
699
+ // Mark the current path as the final node.
700
+ CodePath.getState(codePath).makeFinal();
701
+
702
+ // Emits onCodePathSegmentEnd event of the current segments.
703
+ leaveFromCurrentSegment(analyzer, node);
704
+
705
+ // Emits onCodePathEnd event of this code path.
706
+ debug.dump(`onCodePathEnd ${codePath.id}`);
707
+ analyzer.emitter.emit("onCodePathEnd", codePath, node);
708
+ debug.dumpDot(codePath);
709
+
710
+ codePath = analyzer.codePath = analyzer.codePath.upper;
711
+ if (codePath) {
712
+ debug.dumpState(node, CodePath.getState(codePath), true);
713
+ }
714
+
715
+ }
716
+
717
+ switch (node.type) {
718
+ case "Program":
719
+ case "FunctionDeclaration":
720
+ case "FunctionExpression":
721
+ case "ArrowFunctionExpression":
722
+ case "StaticBlock": {
723
+ endCodePath();
724
+ break;
725
+ }
726
+
727
+ // The `arguments.length >= 1` case is in `preprocess` function.
728
+ case "CallExpression":
729
+ if (node.optional === true && node.arguments.length === 0) {
730
+ CodePath.getState(analyzer.codePath).makeOptionalRight();
731
+ }
732
+ break;
733
+
734
+ default:
735
+ break;
736
+ }
737
+
738
+ /*
739
+ * Special case: The right side of class field initializer is considered
740
+ * to be its own function, so we need to end a code path in this
741
+ * case.
742
+ *
743
+ * We need to check after the other checks in order to close the
744
+ * code paths in the correct order for code like this:
745
+ *
746
+ *
747
+ * class Foo {
748
+ * a = () => {}
749
+ * }
750
+ *
751
+ * In this case, The ArrowFunctionExpression code path is closed first
752
+ * and then we need to close the code path for the PropertyDefinition
753
+ * value.
754
+ */
755
+ if (isPropertyDefinitionValue(node)) {
756
+ endCodePath();
757
+ }
758
+ }
759
+
760
+ //------------------------------------------------------------------------------
761
+ // Public Interface
762
+ //------------------------------------------------------------------------------
763
+
764
+ /**
765
+ * The class to analyze code paths.
766
+ * This class implements the EventGenerator interface.
767
+ */
768
+ class CodePathAnalyzer {
769
+
770
+ /**
771
+ * @param {EventGenerator} eventGenerator An event generator to wrap.
772
+ */
773
+ constructor(eventGenerator) {
774
+ this.original = eventGenerator;
775
+ this.emitter = eventGenerator.emitter;
776
+ this.codePath = null;
777
+ this.idGenerator = new IdGenerator("s");
778
+ this.currentNode = null;
779
+ this.onLooped = this.onLooped.bind(this);
780
+ }
781
+
782
+ /**
783
+ * Does the process to enter a given AST node.
784
+ * This updates state of analysis and calls `enterNode` of the wrapped.
785
+ * @param {ASTNode} node A node which is entering.
786
+ * @returns {void}
787
+ */
788
+ enterNode(node) {
789
+ this.currentNode = node;
790
+
791
+ // Updates the code path due to node's position in its parent node.
792
+ if (node.parent) {
793
+ preprocess(this, node);
794
+ }
795
+
796
+ /*
797
+ * Updates the code path.
798
+ * And emits onCodePathStart/onCodePathSegmentStart events.
799
+ */
800
+ processCodePathToEnter(this, node);
801
+
802
+ // Emits node events.
803
+ this.original.enterNode(node);
804
+
805
+ this.currentNode = null;
806
+ }
807
+
808
+ /**
809
+ * Does the process to leave a given AST node.
810
+ * This updates state of analysis and calls `leaveNode` of the wrapped.
811
+ * @param {ASTNode} node A node which is leaving.
812
+ * @returns {void}
813
+ */
814
+ leaveNode(node) {
815
+ this.currentNode = node;
816
+
817
+ /*
818
+ * Updates the code path.
819
+ * And emits onCodePathStart/onCodePathSegmentStart events.
820
+ */
821
+ processCodePathToExit(this, node);
822
+
823
+ // Emits node events.
824
+ this.original.leaveNode(node);
825
+
826
+ // Emits the last onCodePathStart/onCodePathSegmentStart events.
827
+ postprocess(this, node);
828
+
829
+ this.currentNode = null;
830
+ }
831
+
832
+ /**
833
+ * This is called on a code path looped.
834
+ * Then this raises a looped event.
835
+ * @param {CodePathSegment} fromSegment A segment of prev.
836
+ * @param {CodePathSegment} toSegment A segment of next.
837
+ * @returns {void}
838
+ */
839
+ onLooped(fromSegment, toSegment) {
840
+ if (fromSegment.reachable && toSegment.reachable) {
841
+ debug.dump(`onCodePathSegmentLoop ${fromSegment.id} -> ${toSegment.id}`);
842
+ this.emitter.emit(
843
+ "onCodePathSegmentLoop",
844
+ fromSegment,
845
+ toSegment,
846
+ this.currentNode
847
+ );
848
+ }
849
+ }
850
+ }
851
+
852
+ module.exports = CodePathAnalyzer;
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/code-path-analysis/code-path-segment.js ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview The CodePathSegment class.
3
+ * @author Toru Nagashima
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //------------------------------------------------------------------------------
9
+ // Requirements
10
+ //------------------------------------------------------------------------------
11
+
12
+ const debug = require("./debug-helpers");
13
+
14
+ //------------------------------------------------------------------------------
15
+ // Helpers
16
+ //------------------------------------------------------------------------------
17
+
18
+ /**
19
+ * Checks whether or not a given segment is reachable.
20
+ * @param {CodePathSegment} segment A segment to check.
21
+ * @returns {boolean} `true` if the segment is reachable.
22
+ */
23
+ function isReachable(segment) {
24
+ return segment.reachable;
25
+ }
26
+
27
+ //------------------------------------------------------------------------------
28
+ // Public Interface
29
+ //------------------------------------------------------------------------------
30
+
31
+ /**
32
+ * A code path segment.
33
+ *
34
+ * Each segment is arranged in a series of linked lists (implemented by arrays)
35
+ * that keep track of the previous and next segments in a code path. In this way,
36
+ * you can navigate between all segments in any code path so long as you have a
37
+ * reference to any segment in that code path.
38
+ *
39
+ * When first created, the segment is in a detached state, meaning that it knows the
40
+ * segments that came before it but those segments don't know that this new segment
41
+ * follows it. Only when `CodePathSegment#markUsed()` is called on a segment does it
42
+ * officially become part of the code path by updating the previous segments to know
43
+ * that this new segment follows.
44
+ */
45
+ class CodePathSegment {
46
+
47
+ /**
48
+ * Creates a new instance.
49
+ * @param {string} id An identifier.
50
+ * @param {CodePathSegment[]} allPrevSegments An array of the previous segments.
51
+ * This array includes unreachable segments.
52
+ * @param {boolean} reachable A flag which shows this is reachable.
53
+ */
54
+ constructor(id, allPrevSegments, reachable) {
55
+
56
+ /**
57
+ * The identifier of this code path.
58
+ * Rules use it to store additional information of each rule.
59
+ * @type {string}
60
+ */
61
+ this.id = id;
62
+
63
+ /**
64
+ * An array of the next reachable segments.
65
+ * @type {CodePathSegment[]}
66
+ */
67
+ this.nextSegments = [];
68
+
69
+ /**
70
+ * An array of the previous reachable segments.
71
+ * @type {CodePathSegment[]}
72
+ */
73
+ this.prevSegments = allPrevSegments.filter(isReachable);
74
+
75
+ /**
76
+ * An array of all next segments including reachable and unreachable.
77
+ * @type {CodePathSegment[]}
78
+ */
79
+ this.allNextSegments = [];
80
+
81
+ /**
82
+ * An array of all previous segments including reachable and unreachable.
83
+ * @type {CodePathSegment[]}
84
+ */
85
+ this.allPrevSegments = allPrevSegments;
86
+
87
+ /**
88
+ * A flag which shows this is reachable.
89
+ * @type {boolean}
90
+ */
91
+ this.reachable = reachable;
92
+
93
+ // Internal data.
94
+ Object.defineProperty(this, "internal", {
95
+ value: {
96
+
97
+ // determines if the segment has been attached to the code path
98
+ used: false,
99
+
100
+ // array of previous segments coming from the end of a loop
101
+ loopedPrevSegments: []
102
+ }
103
+ });
104
+
105
+ /* c8 ignore start */
106
+ if (debug.enabled) {
107
+ this.internal.nodes = [];
108
+ }/* c8 ignore stop */
109
+ }
110
+
111
+ /**
112
+ * Checks a given previous segment is coming from the end of a loop.
113
+ * @param {CodePathSegment} segment A previous segment to check.
114
+ * @returns {boolean} `true` if the segment is coming from the end of a loop.
115
+ */
116
+ isLoopedPrevSegment(segment) {
117
+ return this.internal.loopedPrevSegments.includes(segment);
118
+ }
119
+
120
+ /**
121
+ * Creates the root segment.
122
+ * @param {string} id An identifier.
123
+ * @returns {CodePathSegment} The created segment.
124
+ */
125
+ static newRoot(id) {
126
+ return new CodePathSegment(id, [], true);
127
+ }
128
+
129
+ /**
130
+ * Creates a new segment and appends it after the given segments.
131
+ * @param {string} id An identifier.
132
+ * @param {CodePathSegment[]} allPrevSegments An array of the previous segments
133
+ * to append to.
134
+ * @returns {CodePathSegment} The created segment.
135
+ */
136
+ static newNext(id, allPrevSegments) {
137
+ return new CodePathSegment(
138
+ id,
139
+ CodePathSegment.flattenUnusedSegments(allPrevSegments),
140
+ allPrevSegments.some(isReachable)
141
+ );
142
+ }
143
+
144
+ /**
145
+ * Creates an unreachable segment and appends it after the given segments.
146
+ * @param {string} id An identifier.
147
+ * @param {CodePathSegment[]} allPrevSegments An array of the previous segments.
148
+ * @returns {CodePathSegment} The created segment.
149
+ */
150
+ static newUnreachable(id, allPrevSegments) {
151
+ const segment = new CodePathSegment(id, CodePathSegment.flattenUnusedSegments(allPrevSegments), false);
152
+
153
+ /*
154
+ * In `if (a) return a; foo();` case, the unreachable segment preceded by
155
+ * the return statement is not used but must not be removed.
156
+ */
157
+ CodePathSegment.markUsed(segment);
158
+
159
+ return segment;
160
+ }
161
+
162
+ /**
163
+ * Creates a segment that follows given segments.
164
+ * This factory method does not connect with `allPrevSegments`.
165
+ * But this inherits `reachable` flag.
166
+ * @param {string} id An identifier.
167
+ * @param {CodePathSegment[]} allPrevSegments An array of the previous segments.
168
+ * @returns {CodePathSegment} The created segment.
169
+ */
170
+ static newDisconnected(id, allPrevSegments) {
171
+ return new CodePathSegment(id, [], allPrevSegments.some(isReachable));
172
+ }
173
+
174
+ /**
175
+ * Marks a given segment as used.
176
+ *
177
+ * And this function registers the segment into the previous segments as a next.
178
+ * @param {CodePathSegment} segment A segment to mark.
179
+ * @returns {void}
180
+ */
181
+ static markUsed(segment) {
182
+ if (segment.internal.used) {
183
+ return;
184
+ }
185
+ segment.internal.used = true;
186
+
187
+ let i;
188
+
189
+ if (segment.reachable) {
190
+
191
+ /*
192
+ * If the segment is reachable, then it's officially part of the
193
+ * code path. This loops through all previous segments to update
194
+ * their list of next segments. Because the segment is reachable,
195
+ * it's added to both `nextSegments` and `allNextSegments`.
196
+ */
197
+ for (i = 0; i < segment.allPrevSegments.length; ++i) {
198
+ const prevSegment = segment.allPrevSegments[i];
199
+
200
+ prevSegment.allNextSegments.push(segment);
201
+ prevSegment.nextSegments.push(segment);
202
+ }
203
+ } else {
204
+
205
+ /*
206
+ * If the segment is not reachable, then it's not officially part of the
207
+ * code path. This loops through all previous segments to update
208
+ * their list of next segments. Because the segment is not reachable,
209
+ * it's added only to `allNextSegments`.
210
+ */
211
+ for (i = 0; i < segment.allPrevSegments.length; ++i) {
212
+ segment.allPrevSegments[i].allNextSegments.push(segment);
213
+ }
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Marks a previous segment as looped.
219
+ * @param {CodePathSegment} segment A segment.
220
+ * @param {CodePathSegment} prevSegment A previous segment to mark.
221
+ * @returns {void}
222
+ */
223
+ static markPrevSegmentAsLooped(segment, prevSegment) {
224
+ segment.internal.loopedPrevSegments.push(prevSegment);
225
+ }
226
+
227
+ /**
228
+ * Creates a new array based on an array of segments. If any segment in the
229
+ * array is unused, then it is replaced by all of its previous segments.
230
+ * All used segments are returned as-is without replacement.
231
+ * @param {CodePathSegment[]} segments The array of segments to flatten.
232
+ * @returns {CodePathSegment[]} The flattened array.
233
+ */
234
+ static flattenUnusedSegments(segments) {
235
+ const done = new Set();
236
+
237
+ for (let i = 0; i < segments.length; ++i) {
238
+ const segment = segments[i];
239
+
240
+ // Ignores duplicated.
241
+ if (done.has(segment)) {
242
+ continue;
243
+ }
244
+
245
+ // Use previous segments if unused.
246
+ if (!segment.internal.used) {
247
+ for (let j = 0; j < segment.allPrevSegments.length; ++j) {
248
+ const prevSegment = segment.allPrevSegments[j];
249
+
250
+ if (!done.has(prevSegment)) {
251
+ done.add(prevSegment);
252
+ }
253
+ }
254
+ } else {
255
+ done.add(segment);
256
+ }
257
+ }
258
+
259
+ return [...done];
260
+ }
261
+ }
262
+
263
+ module.exports = CodePathSegment;
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/code-path-analysis/code-path-state.js ADDED
@@ -0,0 +1,2348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview A class to manage state of generating a code path.
3
+ * @author Toru Nagashima
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //------------------------------------------------------------------------------
9
+ // Requirements
10
+ //------------------------------------------------------------------------------
11
+
12
+ const CodePathSegment = require("./code-path-segment"),
13
+ ForkContext = require("./fork-context");
14
+
15
+ //-----------------------------------------------------------------------------
16
+ // Contexts
17
+ //-----------------------------------------------------------------------------
18
+
19
+ /**
20
+ * Represents the context in which a `break` statement can be used.
21
+ *
22
+ * A `break` statement without a label is only valid in a few places in
23
+ * JavaScript: any type of loop or a `switch` statement. Otherwise, `break`
24
+ * without a label causes a syntax error. For these contexts, `breakable` is
25
+ * set to `true` to indicate that a `break` without a label is valid.
26
+ *
27
+ * However, a `break` statement with a label is also valid inside of a labeled
28
+ * statement. For example, this is valid:
29
+ *
30
+ * a : {
31
+ * break a;
32
+ * }
33
+ *
34
+ * The `breakable` property is set false for labeled statements to indicate
35
+ * that `break` without a label is invalid.
36
+ */
37
+ class BreakContext {
38
+
39
+ /**
40
+ * Creates a new instance.
41
+ * @param {BreakContext} upperContext The previous `BreakContext`.
42
+ * @param {boolean} breakable Indicates if we are inside a statement where
43
+ * `break` without a label will exit the statement.
44
+ * @param {string|null} label The label for the statement.
45
+ * @param {ForkContext} forkContext The current fork context.
46
+ */
47
+ constructor(upperContext, breakable, label, forkContext) {
48
+
49
+ /**
50
+ * The previous `BreakContext`
51
+ * @type {BreakContext}
52
+ */
53
+ this.upper = upperContext;
54
+
55
+ /**
56
+ * Indicates if we are inside a statement where `break` without a label
57
+ * will exit the statement.
58
+ * @type {boolean}
59
+ */
60
+ this.breakable = breakable;
61
+
62
+ /**
63
+ * The label associated with the statement.
64
+ * @type {string|null}
65
+ */
66
+ this.label = label;
67
+
68
+ /**
69
+ * The fork context for the `break`.
70
+ * @type {ForkContext}
71
+ */
72
+ this.brokenForkContext = ForkContext.newEmpty(forkContext);
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Represents the context for `ChainExpression` nodes.
78
+ */
79
+ class ChainContext {
80
+
81
+ /**
82
+ * Creates a new instance.
83
+ * @param {ChainContext} upperContext The previous `ChainContext`.
84
+ */
85
+ constructor(upperContext) {
86
+
87
+ /**
88
+ * The previous `ChainContext`
89
+ * @type {ChainContext}
90
+ */
91
+ this.upper = upperContext;
92
+
93
+ /**
94
+ * The number of choice contexts inside of the `ChainContext`.
95
+ * @type {number}
96
+ */
97
+ this.choiceContextCount = 0;
98
+
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Represents a choice in the code path.
104
+ *
105
+ * Choices are created by logical operators such as `&&`, loops, conditionals,
106
+ * and `if` statements. This is the point at which the code path has a choice of
107
+ * which direction to go.
108
+ *
109
+ * The result of a choice might be in the left (test) expression of another choice,
110
+ * and in that case, may create a new fork. For example, `a || b` is a choice
111
+ * but does not create a new fork because the result of the expression is
112
+ * not used as the test expression in another expression. In this case,
113
+ * `isForkingAsResult` is false. In the expression `a || b || c`, the `a || b`
114
+ * expression appears as the test expression for `|| c`, so the
115
+ * result of `a || b` creates a fork because execution may or may not
116
+ * continue to `|| c`. `isForkingAsResult` for `a || b` in this case is true
117
+ * while `isForkingAsResult` for `|| c` is false. (`isForkingAsResult` is always
118
+ * false for `if` statements, conditional expressions, and loops.)
119
+ *
120
+ * All of the choices except one (`??`) operate on a true/false fork, meaning if
121
+ * true go one way and if false go the other (tracked by `trueForkContext` and
122
+ * `falseForkContext`). The `??` operator doesn't operate on true/false because
123
+ * the left expression is evaluated to be nullish or not, so only if nullish do
124
+ * we fork to the right expression (tracked by `nullishForkContext`).
125
+ */
126
+ class ChoiceContext {
127
+
128
+ /**
129
+ * Creates a new instance.
130
+ * @param {ChoiceContext} upperContext The previous `ChoiceContext`.
131
+ * @param {string} kind The kind of choice. If it's a logical or assignment expression, this
132
+ * is `"&&"` or `"||"` or `"??"`; if it's an `if` statement or
133
+ * conditional expression, this is `"test"`; otherwise, this is `"loop"`.
134
+ * @param {boolean} isForkingAsResult Indicates if the result of the choice
135
+ * creates a fork.
136
+ * @param {ForkContext} forkContext The containing `ForkContext`.
137
+ */
138
+ constructor(upperContext, kind, isForkingAsResult, forkContext) {
139
+
140
+ /**
141
+ * The previous `ChoiceContext`
142
+ * @type {ChoiceContext}
143
+ */
144
+ this.upper = upperContext;
145
+
146
+ /**
147
+ * The kind of choice. If it's a logical or assignment expression, this
148
+ * is `"&&"` or `"||"` or `"??"`; if it's an `if` statement or
149
+ * conditional expression, this is `"test"`; otherwise, this is `"loop"`.
150
+ * @type {string}
151
+ */
152
+ this.kind = kind;
153
+
154
+ /**
155
+ * Indicates if the result of the choice forks the code path.
156
+ * @type {boolean}
157
+ */
158
+ this.isForkingAsResult = isForkingAsResult;
159
+
160
+ /**
161
+ * The fork context for the `true` path of the choice.
162
+ * @type {ForkContext}
163
+ */
164
+ this.trueForkContext = ForkContext.newEmpty(forkContext);
165
+
166
+ /**
167
+ * The fork context for the `false` path of the choice.
168
+ * @type {ForkContext}
169
+ */
170
+ this.falseForkContext = ForkContext.newEmpty(forkContext);
171
+
172
+ /**
173
+ * The fork context for when the choice result is `null` or `undefined`.
174
+ * @type {ForkContext}
175
+ */
176
+ this.nullishForkContext = ForkContext.newEmpty(forkContext);
177
+
178
+ /**
179
+ * Indicates if any of `trueForkContext`, `falseForkContext`, or
180
+ * `nullishForkContext` have been updated with segments from a child context.
181
+ * @type {boolean}
182
+ */
183
+ this.processed = false;
184
+ }
185
+
186
+ }
187
+
188
+ /**
189
+ * Base class for all loop contexts.
190
+ */
191
+ class LoopContextBase {
192
+
193
+ /**
194
+ * Creates a new instance.
195
+ * @param {LoopContext|null} upperContext The previous `LoopContext`.
196
+ * @param {string} type The AST node's `type` for the loop.
197
+ * @param {string|null} label The label for the loop from an enclosing `LabeledStatement`.
198
+ * @param {BreakContext} breakContext The context for breaking the loop.
199
+ */
200
+ constructor(upperContext, type, label, breakContext) {
201
+
202
+ /**
203
+ * The previous `LoopContext`.
204
+ * @type {LoopContext}
205
+ */
206
+ this.upper = upperContext;
207
+
208
+ /**
209
+ * The AST node's `type` for the loop.
210
+ * @type {string}
211
+ */
212
+ this.type = type;
213
+
214
+ /**
215
+ * The label for the loop from an enclosing `LabeledStatement`.
216
+ * @type {string|null}
217
+ */
218
+ this.label = label;
219
+
220
+ /**
221
+ * The fork context for when `break` is encountered.
222
+ * @type {ForkContext}
223
+ */
224
+ this.brokenForkContext = breakContext.brokenForkContext;
225
+ }
226
+ }
227
+
228
+ /**
229
+ * Represents the context for a `while` loop.
230
+ */
231
+ class WhileLoopContext extends LoopContextBase {
232
+
233
+ /**
234
+ * Creates a new instance.
235
+ * @param {LoopContext|null} upperContext The previous `LoopContext`.
236
+ * @param {string|null} label The label for the loop from an enclosing `LabeledStatement`.
237
+ * @param {BreakContext} breakContext The context for breaking the loop.
238
+ */
239
+ constructor(upperContext, label, breakContext) {
240
+ super(upperContext, "WhileStatement", label, breakContext);
241
+
242
+ /**
243
+ * The hardcoded literal boolean test condition for
244
+ * the loop. Used to catch infinite or skipped loops.
245
+ * @type {boolean|undefined}
246
+ */
247
+ this.test = void 0;
248
+
249
+ /**
250
+ * The segments representing the test condition where `continue` will
251
+ * jump to. The test condition will typically have just one segment but
252
+ * it's possible for there to be more than one.
253
+ * @type {Array<CodePathSegment>|null}
254
+ */
255
+ this.continueDestSegments = null;
256
+ }
257
+ }
258
+
259
+ /**
260
+ * Represents the context for a `do-while` loop.
261
+ */
262
+ class DoWhileLoopContext extends LoopContextBase {
263
+
264
+ /**
265
+ * Creates a new instance.
266
+ * @param {LoopContext|null} upperContext The previous `LoopContext`.
267
+ * @param {string|null} label The label for the loop from an enclosing `LabeledStatement`.
268
+ * @param {BreakContext} breakContext The context for breaking the loop.
269
+ * @param {ForkContext} forkContext The enclosing fork context.
270
+ */
271
+ constructor(upperContext, label, breakContext, forkContext) {
272
+ super(upperContext, "DoWhileStatement", label, breakContext);
273
+
274
+ /**
275
+ * The hardcoded literal boolean test condition for
276
+ * the loop. Used to catch infinite or skipped loops.
277
+ * @type {boolean|undefined}
278
+ */
279
+ this.test = void 0;
280
+
281
+ /**
282
+ * The segments at the start of the loop body. This is the only loop
283
+ * where the test comes at the end, so the first iteration always
284
+ * happens and we need a reference to the first statements.
285
+ * @type {Array<CodePathSegment>|null}
286
+ */
287
+ this.entrySegments = null;
288
+
289
+ /**
290
+ * The fork context to follow when a `continue` is found.
291
+ * @type {ForkContext}
292
+ */
293
+ this.continueForkContext = ForkContext.newEmpty(forkContext);
294
+ }
295
+ }
296
+
297
+ /**
298
+ * Represents the context for a `for` loop.
299
+ */
300
+ class ForLoopContext extends LoopContextBase {
301
+
302
+ /**
303
+ * Creates a new instance.
304
+ * @param {LoopContext|null} upperContext The previous `LoopContext`.
305
+ * @param {string|null} label The label for the loop from an enclosing `LabeledStatement`.
306
+ * @param {BreakContext} breakContext The context for breaking the loop.
307
+ */
308
+ constructor(upperContext, label, breakContext) {
309
+ super(upperContext, "ForStatement", label, breakContext);
310
+
311
+ /**
312
+ * The hardcoded literal boolean test condition for
313
+ * the loop. Used to catch infinite or skipped loops.
314
+ * @type {boolean|undefined}
315
+ */
316
+ this.test = void 0;
317
+
318
+ /**
319
+ * The end of the init expression. This may change during the lifetime
320
+ * of the instance as we traverse the loop because some loops don't have
321
+ * an init expression.
322
+ * @type {Array<CodePathSegment>|null}
323
+ */
324
+ this.endOfInitSegments = null;
325
+
326
+ /**
327
+ * The start of the test expression. This may change during the lifetime
328
+ * of the instance as we traverse the loop because some loops don't have
329
+ * a test expression.
330
+ * @type {Array<CodePathSegment>|null}
331
+ */
332
+ this.testSegments = null;
333
+
334
+ /**
335
+ * The end of the test expression. This may change during the lifetime
336
+ * of the instance as we traverse the loop because some loops don't have
337
+ * a test expression.
338
+ * @type {Array<CodePathSegment>|null}
339
+ */
340
+ this.endOfTestSegments = null;
341
+
342
+ /**
343
+ * The start of the update expression. This may change during the lifetime
344
+ * of the instance as we traverse the loop because some loops don't have
345
+ * an update expression.
346
+ * @type {Array<CodePathSegment>|null}
347
+ */
348
+ this.updateSegments = null;
349
+
350
+ /**
351
+ * The end of the update expresion. This may change during the lifetime
352
+ * of the instance as we traverse the loop because some loops don't have
353
+ * an update expression.
354
+ * @type {Array<CodePathSegment>|null}
355
+ */
356
+ this.endOfUpdateSegments = null;
357
+
358
+ /**
359
+ * The segments representing the test condition where `continue` will
360
+ * jump to. The test condition will typically have just one segment but
361
+ * it's possible for there to be more than one. This may change during the
362
+ * lifetime of the instance as we traverse the loop because some loops
363
+ * don't have an update expression. When there is an update expression, this
364
+ * will end up pointing to that expression; otherwise it will end up pointing
365
+ * to the test expression.
366
+ * @type {Array<CodePathSegment>|null}
367
+ */
368
+ this.continueDestSegments = null;
369
+ }
370
+ }
371
+
372
+ /**
373
+ * Represents the context for a `for-in` loop.
374
+ *
375
+ * Terminology:
376
+ * - "left" means the part of the loop to the left of the `in` keyword. For
377
+ * example, in `for (var x in y)`, the left is `var x`.
378
+ * - "right" means the part of the loop to the right of the `in` keyword. For
379
+ * example, in `for (var x in y)`, the right is `y`.
380
+ */
381
+ class ForInLoopContext extends LoopContextBase {
382
+
383
+ /**
384
+ * Creates a new instance.
385
+ * @param {LoopContext|null} upperContext The previous `LoopContext`.
386
+ * @param {string|null} label The label for the loop from an enclosing `LabeledStatement`.
387
+ * @param {BreakContext} breakContext The context for breaking the loop.
388
+ */
389
+ constructor(upperContext, label, breakContext) {
390
+ super(upperContext, "ForInStatement", label, breakContext);
391
+
392
+ /**
393
+ * The segments that came immediately before the start of the loop.
394
+ * This allows you to traverse backwards out of the loop into the
395
+ * surrounding code. This is necessary to evaluate the right expression
396
+ * correctly, as it must be evaluated in the same way as the left
397
+ * expression, but the pointer to these segments would otherwise be
398
+ * lost if not stored on the instance. Once the right expression has
399
+ * been evaluated, this property is no longer used.
400
+ * @type {Array<CodePathSegment>|null}
401
+ */
402
+ this.prevSegments = null;
403
+
404
+ /**
405
+ * Segments representing the start of everything to the left of the
406
+ * `in` keyword. This can be used to move forward towards
407
+ * `endOfLeftSegments`. `leftSegments` and `endOfLeftSegments` are
408
+ * effectively the head and tail of a doubly-linked list.
409
+ * @type {Array<CodePathSegment>|null}
410
+ */
411
+ this.leftSegments = null;
412
+
413
+ /**
414
+ * Segments representing the end of everything to the left of the
415
+ * `in` keyword. This can be used to move backward towards `leftSegments`.
416
+ * `leftSegments` and `endOfLeftSegments` are effectively the head
417
+ * and tail of a doubly-linked list.
418
+ * @type {Array<CodePathSegment>|null}
419
+ */
420
+ this.endOfLeftSegments = null;
421
+
422
+ /**
423
+ * The segments representing the left expression where `continue` will
424
+ * jump to. In `for-in` loops, `continue` must always re-execute the
425
+ * left expression each time through the loop. This contains the same
426
+ * segments as `leftSegments`, but is duplicated here so each loop
427
+ * context has the same property pointing to where `continue` should
428
+ * end up.
429
+ * @type {Array<CodePathSegment>|null}
430
+ */
431
+ this.continueDestSegments = null;
432
+ }
433
+ }
434
+
435
+ /**
436
+ * Represents the context for a `for-of` loop.
437
+ */
438
+ class ForOfLoopContext extends LoopContextBase {
439
+
440
+ /**
441
+ * Creates a new instance.
442
+ * @param {LoopContext|null} upperContext The previous `LoopContext`.
443
+ * @param {string|null} label The label for the loop from an enclosing `LabeledStatement`.
444
+ * @param {BreakContext} breakContext The context for breaking the loop.
445
+ */
446
+ constructor(upperContext, label, breakContext) {
447
+ super(upperContext, "ForOfStatement", label, breakContext);
448
+
449
+ /**
450
+ * The segments that came immediately before the start of the loop.
451
+ * This allows you to traverse backwards out of the loop into the
452
+ * surrounding code. This is necessary to evaluate the right expression
453
+ * correctly, as it must be evaluated in the same way as the left
454
+ * expression, but the pointer to these segments would otherwise be
455
+ * lost if not stored on the instance. Once the right expression has
456
+ * been evaluated, this property is no longer used.
457
+ * @type {Array<CodePathSegment>|null}
458
+ */
459
+ this.prevSegments = null;
460
+
461
+ /**
462
+ * Segments representing the start of everything to the left of the
463
+ * `of` keyword. This can be used to move forward towards
464
+ * `endOfLeftSegments`. `leftSegments` and `endOfLeftSegments` are
465
+ * effectively the head and tail of a doubly-linked list.
466
+ * @type {Array<CodePathSegment>|null}
467
+ */
468
+ this.leftSegments = null;
469
+
470
+ /**
471
+ * Segments representing the end of everything to the left of the
472
+ * `of` keyword. This can be used to move backward towards `leftSegments`.
473
+ * `leftSegments` and `endOfLeftSegments` are effectively the head
474
+ * and tail of a doubly-linked list.
475
+ * @type {Array<CodePathSegment>|null}
476
+ */
477
+ this.endOfLeftSegments = null;
478
+
479
+ /**
480
+ * The segments representing the left expression where `continue` will
481
+ * jump to. In `for-in` loops, `continue` must always re-execute the
482
+ * left expression each time through the loop. This contains the same
483
+ * segments as `leftSegments`, but is duplicated here so each loop
484
+ * context has the same property pointing to where `continue` should
485
+ * end up.
486
+ * @type {Array<CodePathSegment>|null}
487
+ */
488
+ this.continueDestSegments = null;
489
+ }
490
+ }
491
+
492
+ /**
493
+ * Represents the context for any loop.
494
+ * @typedef {WhileLoopContext|DoWhileLoopContext|ForLoopContext|ForInLoopContext|ForOfLoopContext} LoopContext
495
+ */
496
+
497
+ /**
498
+ * Represents the context for a `switch` statement.
499
+ */
500
+ class SwitchContext {
501
+
502
+ /**
503
+ * Creates a new instance.
504
+ * @param {SwitchContext} upperContext The previous context.
505
+ * @param {boolean} hasCase Indicates if there is at least one `case` statement.
506
+ * `default` doesn't count.
507
+ */
508
+ constructor(upperContext, hasCase) {
509
+
510
+ /**
511
+ * The previous context.
512
+ * @type {SwitchContext}
513
+ */
514
+ this.upper = upperContext;
515
+
516
+ /**
517
+ * Indicates if there is at least one `case` statement. `default` doesn't count.
518
+ * @type {boolean}
519
+ */
520
+ this.hasCase = hasCase;
521
+
522
+ /**
523
+ * The `default` keyword.
524
+ * @type {Array<CodePathSegment>|null}
525
+ */
526
+ this.defaultSegments = null;
527
+
528
+ /**
529
+ * The default case body starting segments.
530
+ * @type {Array<CodePathSegment>|null}
531
+ */
532
+ this.defaultBodySegments = null;
533
+
534
+ /**
535
+ * Indicates if a `default` case and is empty exists.
536
+ * @type {boolean}
537
+ */
538
+ this.foundEmptyDefault = false;
539
+
540
+ /**
541
+ * Indicates that a `default` exists and is the last case.
542
+ * @type {boolean}
543
+ */
544
+ this.lastIsDefault = false;
545
+
546
+ /**
547
+ * The number of fork contexts created. This is equivalent to the
548
+ * number of `case` statements plus a `default` statement (if present).
549
+ * @type {number}
550
+ */
551
+ this.forkCount = 0;
552
+ }
553
+ }
554
+
555
+ /**
556
+ * Represents the context for a `try` statement.
557
+ */
558
+ class TryContext {
559
+
560
+ /**
561
+ * Creates a new instance.
562
+ * @param {TryContext} upperContext The previous context.
563
+ * @param {boolean} hasFinalizer Indicates if the `try` statement has a
564
+ * `finally` block.
565
+ * @param {ForkContext} forkContext The enclosing fork context.
566
+ */
567
+ constructor(upperContext, hasFinalizer, forkContext) {
568
+
569
+ /**
570
+ * The previous context.
571
+ * @type {TryContext}
572
+ */
573
+ this.upper = upperContext;
574
+
575
+ /**
576
+ * Indicates if the `try` statement has a `finally` block.
577
+ * @type {boolean}
578
+ */
579
+ this.hasFinalizer = hasFinalizer;
580
+
581
+ /**
582
+ * Tracks the traversal position inside of the `try` statement. This is
583
+ * used to help determine the context necessary to create paths because
584
+ * a `try` statement may or may not have `catch` or `finally` blocks,
585
+ * and code paths behave differently in those blocks.
586
+ * @type {"try"|"catch"|"finally"}
587
+ */
588
+ this.position = "try";
589
+
590
+ /**
591
+ * If the `try` statement has a `finally` block, this affects how a
592
+ * `return` statement behaves in the `try` block. Without `finally`,
593
+ * `return` behaves as usual and doesn't require a fork; with `finally`,
594
+ * `return` forks into the `finally` block, so we need a fork context
595
+ * to track it.
596
+ * @type {ForkContext|null}
597
+ */
598
+ this.returnedForkContext = hasFinalizer
599
+ ? ForkContext.newEmpty(forkContext)
600
+ : null;
601
+
602
+ /**
603
+ * When a `throw` occurs inside of a `try` block, the code path forks
604
+ * into the `catch` or `finally` blocks, and this fork context tracks
605
+ * that path.
606
+ * @type {ForkContext}
607
+ */
608
+ this.thrownForkContext = ForkContext.newEmpty(forkContext);
609
+
610
+ /**
611
+ * Indicates if the last segment in the `try` block is reachable.
612
+ * @type {boolean}
613
+ */
614
+ this.lastOfTryIsReachable = false;
615
+
616
+ /**
617
+ * Indicates if the last segment in the `catch` block is reachable.
618
+ * @type {boolean}
619
+ */
620
+ this.lastOfCatchIsReachable = false;
621
+ }
622
+ }
623
+
624
+ //------------------------------------------------------------------------------
625
+ // Helpers
626
+ //------------------------------------------------------------------------------
627
+
628
+ /**
629
+ * Adds given segments into the `dest` array.
630
+ * If the `others` array does not include the given segments, adds to the `all`
631
+ * array as well.
632
+ *
633
+ * This adds only reachable and used segments.
634
+ * @param {CodePathSegment[]} dest A destination array (`returnedSegments` or `thrownSegments`).
635
+ * @param {CodePathSegment[]} others Another destination array (`returnedSegments` or `thrownSegments`).
636
+ * @param {CodePathSegment[]} all The unified destination array (`finalSegments`).
637
+ * @param {CodePathSegment[]} segments Segments to add.
638
+ * @returns {void}
639
+ */
640
+ function addToReturnedOrThrown(dest, others, all, segments) {
641
+ for (let i = 0; i < segments.length; ++i) {
642
+ const segment = segments[i];
643
+
644
+ dest.push(segment);
645
+ if (!others.includes(segment)) {
646
+ all.push(segment);
647
+ }
648
+ }
649
+ }
650
+
651
+ /**
652
+ * Gets a loop context for a `continue` statement based on a given label.
653
+ * @param {CodePathState} state The state to search within.
654
+ * @param {string|null} label The label of a `continue` statement.
655
+ * @returns {LoopContext} A loop-context for a `continue` statement.
656
+ */
657
+ function getContinueContext(state, label) {
658
+ if (!label) {
659
+ return state.loopContext;
660
+ }
661
+
662
+ let context = state.loopContext;
663
+
664
+ while (context) {
665
+ if (context.label === label) {
666
+ return context;
667
+ }
668
+ context = context.upper;
669
+ }
670
+
671
+ /* c8 ignore next */
672
+ return null;
673
+ }
674
+
675
+ /**
676
+ * Gets a context for a `break` statement.
677
+ * @param {CodePathState} state The state to search within.
678
+ * @param {string|null} label The label of a `break` statement.
679
+ * @returns {BreakContext} A context for a `break` statement.
680
+ */
681
+ function getBreakContext(state, label) {
682
+ let context = state.breakContext;
683
+
684
+ while (context) {
685
+ if (label ? context.label === label : context.breakable) {
686
+ return context;
687
+ }
688
+ context = context.upper;
689
+ }
690
+
691
+ /* c8 ignore next */
692
+ return null;
693
+ }
694
+
695
+ /**
696
+ * Gets a context for a `return` statement. There is just one special case:
697
+ * if there is a `try` statement with a `finally` block, because that alters
698
+ * how `return` behaves; otherwise, this just passes through the given state.
699
+ * @param {CodePathState} state The state to search within
700
+ * @returns {TryContext|CodePathState} A context for a `return` statement.
701
+ */
702
+ function getReturnContext(state) {
703
+ let context = state.tryContext;
704
+
705
+ while (context) {
706
+ if (context.hasFinalizer && context.position !== "finally") {
707
+ return context;
708
+ }
709
+ context = context.upper;
710
+ }
711
+
712
+ return state;
713
+ }
714
+
715
+ /**
716
+ * Gets a context for a `throw` statement. There is just one special case:
717
+ * if there is a `try` statement with a `finally` block and we are inside of
718
+ * a `catch` because that changes how `throw` behaves; otherwise, this just
719
+ * passes through the given state.
720
+ * @param {CodePathState} state The state to search within.
721
+ * @returns {TryContext|CodePathState} A context for a `throw` statement.
722
+ */
723
+ function getThrowContext(state) {
724
+ let context = state.tryContext;
725
+
726
+ while (context) {
727
+ if (context.position === "try" ||
728
+ (context.hasFinalizer && context.position === "catch")
729
+ ) {
730
+ return context;
731
+ }
732
+ context = context.upper;
733
+ }
734
+
735
+ return state;
736
+ }
737
+
738
+ /**
739
+ * Removes a given value from a given array.
740
+ * @param {any[]} elements An array to remove the specific element.
741
+ * @param {any} value The value to be removed.
742
+ * @returns {void}
743
+ */
744
+ function removeFromArray(elements, value) {
745
+ elements.splice(elements.indexOf(value), 1);
746
+ }
747
+
748
+ /**
749
+ * Disconnect given segments.
750
+ *
751
+ * This is used in a process for switch statements.
752
+ * If there is the "default" chunk before other cases, the order is different
753
+ * between node's and running's.
754
+ * @param {CodePathSegment[]} prevSegments Forward segments to disconnect.
755
+ * @param {CodePathSegment[]} nextSegments Backward segments to disconnect.
756
+ * @returns {void}
757
+ */
758
+ function disconnectSegments(prevSegments, nextSegments) {
759
+ for (let i = 0; i < prevSegments.length; ++i) {
760
+ const prevSegment = prevSegments[i];
761
+ const nextSegment = nextSegments[i];
762
+
763
+ removeFromArray(prevSegment.nextSegments, nextSegment);
764
+ removeFromArray(prevSegment.allNextSegments, nextSegment);
765
+ removeFromArray(nextSegment.prevSegments, prevSegment);
766
+ removeFromArray(nextSegment.allPrevSegments, prevSegment);
767
+ }
768
+ }
769
+
770
+ /**
771
+ * Creates looping path between two arrays of segments, ensuring that there are
772
+ * paths going between matching segments in the arrays.
773
+ * @param {CodePathState} state The state to operate on.
774
+ * @param {CodePathSegment[]} unflattenedFromSegments Segments which are source.
775
+ * @param {CodePathSegment[]} unflattenedToSegments Segments which are destination.
776
+ * @returns {void}
777
+ */
778
+ function makeLooped(state, unflattenedFromSegments, unflattenedToSegments) {
779
+
780
+ const fromSegments = CodePathSegment.flattenUnusedSegments(unflattenedFromSegments);
781
+ const toSegments = CodePathSegment.flattenUnusedSegments(unflattenedToSegments);
782
+ const end = Math.min(fromSegments.length, toSegments.length);
783
+
784
+ /*
785
+ * This loop effectively updates a doubly-linked list between two collections
786
+ * of segments making sure that segments in the same array indices are
787
+ * combined to create a path.
788
+ */
789
+ for (let i = 0; i < end; ++i) {
790
+
791
+ // get the segments in matching array indices
792
+ const fromSegment = fromSegments[i];
793
+ const toSegment = toSegments[i];
794
+
795
+ /*
796
+ * If the destination segment is reachable, then create a path from the
797
+ * source segment to the destination segment.
798
+ */
799
+ if (toSegment.reachable) {
800
+ fromSegment.nextSegments.push(toSegment);
801
+ }
802
+
803
+ /*
804
+ * If the source segment is reachable, then create a path from the
805
+ * destination segment back to the source segment.
806
+ */
807
+ if (fromSegment.reachable) {
808
+ toSegment.prevSegments.push(fromSegment);
809
+ }
810
+
811
+ /*
812
+ * Also update the arrays that don't care if the segments are reachable
813
+ * or not. This should always happen regardless of anything else.
814
+ */
815
+ fromSegment.allNextSegments.push(toSegment);
816
+ toSegment.allPrevSegments.push(fromSegment);
817
+
818
+ /*
819
+ * If the destination segment has at least two previous segments in its
820
+ * path then that means there was one previous segment before this iteration
821
+ * of the loop was executed. So, we need to mark the source segment as
822
+ * looped.
823
+ */
824
+ if (toSegment.allPrevSegments.length >= 2) {
825
+ CodePathSegment.markPrevSegmentAsLooped(toSegment, fromSegment);
826
+ }
827
+
828
+ // let the code path analyzer know that there's been a loop created
829
+ state.notifyLooped(fromSegment, toSegment);
830
+ }
831
+ }
832
+
833
+ /**
834
+ * Finalizes segments of `test` chunk of a ForStatement.
835
+ *
836
+ * - Adds `false` paths to paths which are leaving from the loop.
837
+ * - Sets `true` paths to paths which go to the body.
838
+ * @param {LoopContext} context A loop context to modify.
839
+ * @param {ChoiceContext} choiceContext A choice context of this loop.
840
+ * @param {CodePathSegment[]} head The current head paths.
841
+ * @returns {void}
842
+ */
843
+ function finalizeTestSegmentsOfFor(context, choiceContext, head) {
844
+
845
+ /*
846
+ * If this choice context doesn't already contain paths from a
847
+ * child context, then add the current head to each potential path.
848
+ */
849
+ if (!choiceContext.processed) {
850
+ choiceContext.trueForkContext.add(head);
851
+ choiceContext.falseForkContext.add(head);
852
+ choiceContext.nullishForkContext.add(head);
853
+ }
854
+
855
+ /*
856
+ * If the test condition isn't a hardcoded truthy value, then `break`
857
+ * must follow the same path as if the test condition is false. To represent
858
+ * that, we append the path for when the loop test is false (represented by
859
+ * `falseForkContext`) to the `brokenForkContext`.
860
+ */
861
+ if (context.test !== true) {
862
+ context.brokenForkContext.addAll(choiceContext.falseForkContext);
863
+ }
864
+
865
+ context.endOfTestSegments = choiceContext.trueForkContext.makeNext(0, -1);
866
+ }
867
+
868
+ //------------------------------------------------------------------------------
869
+ // Public Interface
870
+ //------------------------------------------------------------------------------
871
+
872
+ /**
873
+ * A class which manages state to analyze code paths.
874
+ */
875
+ class CodePathState {
876
+
877
+ /**
878
+ * Creates a new instance.
879
+ * @param {IdGenerator} idGenerator An id generator to generate id for code
880
+ * path segments.
881
+ * @param {Function} onLooped A callback function to notify looping.
882
+ */
883
+ constructor(idGenerator, onLooped) {
884
+
885
+ /**
886
+ * The ID generator to use when creating new segments.
887
+ * @type {IdGenerator}
888
+ */
889
+ this.idGenerator = idGenerator;
890
+
891
+ /**
892
+ * A callback function to call when there is a loop.
893
+ * @type {Function}
894
+ */
895
+ this.notifyLooped = onLooped;
896
+
897
+ /**
898
+ * The root fork context for this state.
899
+ * @type {ForkContext}
900
+ */
901
+ this.forkContext = ForkContext.newRoot(idGenerator);
902
+
903
+ /**
904
+ * Context for logical expressions, conditional expressions, `if` statements,
905
+ * and loops.
906
+ * @type {ChoiceContext}
907
+ */
908
+ this.choiceContext = null;
909
+
910
+ /**
911
+ * Context for `switch` statements.
912
+ * @type {SwitchContext}
913
+ */
914
+ this.switchContext = null;
915
+
916
+ /**
917
+ * Context for `try` statements.
918
+ * @type {TryContext}
919
+ */
920
+ this.tryContext = null;
921
+
922
+ /**
923
+ * Context for loop statements.
924
+ * @type {LoopContext}
925
+ */
926
+ this.loopContext = null;
927
+
928
+ /**
929
+ * Context for `break` statements.
930
+ * @type {BreakContext}
931
+ */
932
+ this.breakContext = null;
933
+
934
+ /**
935
+ * Context for `ChainExpression` nodes.
936
+ * @type {ChainContext}
937
+ */
938
+ this.chainContext = null;
939
+
940
+ /**
941
+ * An array that tracks the current segments in the state. The array
942
+ * starts empty and segments are added with each `onCodePathSegmentStart`
943
+ * event and removed with each `onCodePathSegmentEnd` event. Effectively,
944
+ * this is tracking the code path segment traversal as the state is
945
+ * modified.
946
+ * @type {Array<CodePathSegment>}
947
+ */
948
+ this.currentSegments = [];
949
+
950
+ /**
951
+ * Tracks the starting segment for this path. This value never changes.
952
+ * @type {CodePathSegment}
953
+ */
954
+ this.initialSegment = this.forkContext.head[0];
955
+
956
+ /**
957
+ * The final segments of the code path which are either `return` or `throw`.
958
+ * This is a union of the segments in `returnedForkContext` and `thrownForkContext`.
959
+ * @type {Array<CodePathSegment>}
960
+ */
961
+ this.finalSegments = [];
962
+
963
+ /**
964
+ * The final segments of the code path which are `return`. These
965
+ * segments are also contained in `finalSegments`.
966
+ * @type {Array<CodePathSegment>}
967
+ */
968
+ this.returnedForkContext = [];
969
+
970
+ /**
971
+ * The final segments of the code path which are `throw`. These
972
+ * segments are also contained in `finalSegments`.
973
+ * @type {Array<CodePathSegment>}
974
+ */
975
+ this.thrownForkContext = [];
976
+
977
+ /*
978
+ * We add an `add` method so that these look more like fork contexts and
979
+ * can be used interchangeably when a fork context is needed to add more
980
+ * segments to a path.
981
+ *
982
+ * Ultimately, we want anything added to `returned` or `thrown` to also
983
+ * be added to `final`. We only add reachable and used segments to these
984
+ * arrays.
985
+ */
986
+ const final = this.finalSegments;
987
+ const returned = this.returnedForkContext;
988
+ const thrown = this.thrownForkContext;
989
+
990
+ returned.add = addToReturnedOrThrown.bind(null, returned, thrown, final);
991
+ thrown.add = addToReturnedOrThrown.bind(null, thrown, returned, final);
992
+ }
993
+
994
+ /**
995
+ * A passthrough property exposing the current pointer as part of the API.
996
+ * @type {CodePathSegment[]}
997
+ */
998
+ get headSegments() {
999
+ return this.forkContext.head;
1000
+ }
1001
+
1002
+ /**
1003
+ * The parent forking context.
1004
+ * This is used for the root of new forks.
1005
+ * @type {ForkContext}
1006
+ */
1007
+ get parentForkContext() {
1008
+ const current = this.forkContext;
1009
+
1010
+ return current && current.upper;
1011
+ }
1012
+
1013
+ /**
1014
+ * Creates and stacks new forking context.
1015
+ * @param {boolean} forkLeavingPath A flag which shows being in a
1016
+ * "finally" block.
1017
+ * @returns {ForkContext} The created context.
1018
+ */
1019
+ pushForkContext(forkLeavingPath) {
1020
+ this.forkContext = ForkContext.newEmpty(
1021
+ this.forkContext,
1022
+ forkLeavingPath
1023
+ );
1024
+
1025
+ return this.forkContext;
1026
+ }
1027
+
1028
+ /**
1029
+ * Pops and merges the last forking context.
1030
+ * @returns {ForkContext} The last context.
1031
+ */
1032
+ popForkContext() {
1033
+ const lastContext = this.forkContext;
1034
+
1035
+ this.forkContext = lastContext.upper;
1036
+ this.forkContext.replaceHead(lastContext.makeNext(0, -1));
1037
+
1038
+ return lastContext;
1039
+ }
1040
+
1041
+ /**
1042
+ * Creates a new path.
1043
+ * @returns {void}
1044
+ */
1045
+ forkPath() {
1046
+ this.forkContext.add(this.parentForkContext.makeNext(-1, -1));
1047
+ }
1048
+
1049
+ /**
1050
+ * Creates a bypass path.
1051
+ * This is used for such as IfStatement which does not have "else" chunk.
1052
+ * @returns {void}
1053
+ */
1054
+ forkBypassPath() {
1055
+ this.forkContext.add(this.parentForkContext.head);
1056
+ }
1057
+
1058
+ //--------------------------------------------------------------------------
1059
+ // ConditionalExpression, LogicalExpression, IfStatement
1060
+ //--------------------------------------------------------------------------
1061
+
1062
+ /**
1063
+ * Creates a context for ConditionalExpression, LogicalExpression, AssignmentExpression (logical assignments only),
1064
+ * IfStatement, WhileStatement, DoWhileStatement, or ForStatement.
1065
+ *
1066
+ * LogicalExpressions have cases that it goes different paths between the
1067
+ * `true` case and the `false` case.
1068
+ *
1069
+ * For Example:
1070
+ *
1071
+ * if (a || b) {
1072
+ * foo();
1073
+ * } else {
1074
+ * bar();
1075
+ * }
1076
+ *
1077
+ * In this case, `b` is evaluated always in the code path of the `else`
1078
+ * block, but it's not so in the code path of the `if` block.
1079
+ * So there are 3 paths.
1080
+ *
1081
+ * a -> foo();
1082
+ * a -> b -> foo();
1083
+ * a -> b -> bar();
1084
+ * @param {string} kind A kind string.
1085
+ * If the new context is LogicalExpression's or AssignmentExpression's, this is `"&&"` or `"||"` or `"??"`.
1086
+ * If it's IfStatement's or ConditionalExpression's, this is `"test"`.
1087
+ * Otherwise, this is `"loop"`.
1088
+ * @param {boolean} isForkingAsResult Indicates if the result of the choice
1089
+ * creates a fork.
1090
+ * @returns {void}
1091
+ */
1092
+ pushChoiceContext(kind, isForkingAsResult) {
1093
+ this.choiceContext = new ChoiceContext(this.choiceContext, kind, isForkingAsResult, this.forkContext);
1094
+ }
1095
+
1096
+ /**
1097
+ * Pops the last choice context and finalizes it.
1098
+ * This is called upon leaving a node that represents a choice.
1099
+ * @throws {Error} (Unreachable.)
1100
+ * @returns {ChoiceContext} The popped context.
1101
+ */
1102
+ popChoiceContext() {
1103
+ const poppedChoiceContext = this.choiceContext;
1104
+ const forkContext = this.forkContext;
1105
+ const head = forkContext.head;
1106
+
1107
+ this.choiceContext = poppedChoiceContext.upper;
1108
+
1109
+ switch (poppedChoiceContext.kind) {
1110
+ case "&&":
1111
+ case "||":
1112
+ case "??":
1113
+
1114
+ /*
1115
+ * The `head` are the path of the right-hand operand.
1116
+ * If we haven't previously added segments from child contexts,
1117
+ * then we add these segments to all possible forks.
1118
+ */
1119
+ if (!poppedChoiceContext.processed) {
1120
+ poppedChoiceContext.trueForkContext.add(head);
1121
+ poppedChoiceContext.falseForkContext.add(head);
1122
+ poppedChoiceContext.nullishForkContext.add(head);
1123
+ }
1124
+
1125
+ /*
1126
+ * If this context is the left (test) expression for another choice
1127
+ * context, such as `a || b` in the expression `a || b || c`,
1128
+ * then we take the segments for this context and move them up
1129
+ * to the parent context.
1130
+ */
1131
+ if (poppedChoiceContext.isForkingAsResult) {
1132
+ const parentContext = this.choiceContext;
1133
+
1134
+ parentContext.trueForkContext.addAll(poppedChoiceContext.trueForkContext);
1135
+ parentContext.falseForkContext.addAll(poppedChoiceContext.falseForkContext);
1136
+ parentContext.nullishForkContext.addAll(poppedChoiceContext.nullishForkContext);
1137
+ parentContext.processed = true;
1138
+
1139
+ // Exit early so we don't collapse all paths into one.
1140
+ return poppedChoiceContext;
1141
+ }
1142
+
1143
+ break;
1144
+
1145
+ case "test":
1146
+ if (!poppedChoiceContext.processed) {
1147
+
1148
+ /*
1149
+ * The head segments are the path of the `if` block here.
1150
+ * Updates the `true` path with the end of the `if` block.
1151
+ */
1152
+ poppedChoiceContext.trueForkContext.clear();
1153
+ poppedChoiceContext.trueForkContext.add(head);
1154
+ } else {
1155
+
1156
+ /*
1157
+ * The head segments are the path of the `else` block here.
1158
+ * Updates the `false` path with the end of the `else`
1159
+ * block.
1160
+ */
1161
+ poppedChoiceContext.falseForkContext.clear();
1162
+ poppedChoiceContext.falseForkContext.add(head);
1163
+ }
1164
+
1165
+ break;
1166
+
1167
+ case "loop":
1168
+
1169
+ /*
1170
+ * Loops are addressed in `popLoopContext()` so just return
1171
+ * the context without modification.
1172
+ */
1173
+ return poppedChoiceContext;
1174
+
1175
+ /* c8 ignore next */
1176
+ default:
1177
+ throw new Error("unreachable");
1178
+ }
1179
+
1180
+ /*
1181
+ * Merge the true path with the false path to create a single path.
1182
+ */
1183
+ const combinedForkContext = poppedChoiceContext.trueForkContext;
1184
+
1185
+ combinedForkContext.addAll(poppedChoiceContext.falseForkContext);
1186
+ forkContext.replaceHead(combinedForkContext.makeNext(0, -1));
1187
+
1188
+ return poppedChoiceContext;
1189
+ }
1190
+
1191
+ /**
1192
+ * Creates a code path segment to represent right-hand operand of a logical
1193
+ * expression.
1194
+ * This is called in the preprocessing phase when entering a node.
1195
+ * @throws {Error} (Unreachable.)
1196
+ * @returns {void}
1197
+ */
1198
+ makeLogicalRight() {
1199
+ const currentChoiceContext = this.choiceContext;
1200
+ const forkContext = this.forkContext;
1201
+
1202
+ if (currentChoiceContext.processed) {
1203
+
1204
+ /*
1205
+ * This context was already assigned segments from a child
1206
+ * choice context. In this case, we are concerned only about
1207
+ * the path that does not short-circuit and so ends up on the
1208
+ * right-hand operand of the logical expression.
1209
+ */
1210
+ let prevForkContext;
1211
+
1212
+ switch (currentChoiceContext.kind) {
1213
+ case "&&": // if true then go to the right-hand side.
1214
+ prevForkContext = currentChoiceContext.trueForkContext;
1215
+ break;
1216
+ case "||": // if false then go to the right-hand side.
1217
+ prevForkContext = currentChoiceContext.falseForkContext;
1218
+ break;
1219
+ case "??": // Both true/false can short-circuit, so needs the third path to go to the right-hand side. That's nullishForkContext.
1220
+ prevForkContext = currentChoiceContext.nullishForkContext;
1221
+ break;
1222
+ default:
1223
+ throw new Error("unreachable");
1224
+ }
1225
+
1226
+ /*
1227
+ * Create the segment for the right-hand operand of the logical expression
1228
+ * and adjust the fork context pointer to point there. The right-hand segment
1229
+ * is added at the end of all segments in `prevForkContext`.
1230
+ */
1231
+ forkContext.replaceHead(prevForkContext.makeNext(0, -1));
1232
+
1233
+ /*
1234
+ * We no longer need this list of segments.
1235
+ *
1236
+ * Reset `processed` because we've removed the segments from the child
1237
+ * choice context. This allows `popChoiceContext()` to continue adding
1238
+ * segments later.
1239
+ */
1240
+ prevForkContext.clear();
1241
+ currentChoiceContext.processed = false;
1242
+
1243
+ } else {
1244
+
1245
+ /*
1246
+ * This choice context was not assigned segments from a child
1247
+ * choice context, which means that it's a terminal logical
1248
+ * expression.
1249
+ *
1250
+ * `head` is the segments for the left-hand operand of the
1251
+ * logical expression.
1252
+ *
1253
+ * Each of the fork contexts below are empty at this point. We choose
1254
+ * the path(s) that will short-circuit and add the segment for the
1255
+ * left-hand operand to it. Ultimately, this will be the only segment
1256
+ * in that path due to the short-circuting, so we are just seeding
1257
+ * these paths to start.
1258
+ */
1259
+ switch (currentChoiceContext.kind) {
1260
+ case "&&":
1261
+
1262
+ /*
1263
+ * In most contexts, when a && expression evaluates to false,
1264
+ * it short circuits, so we need to account for that by setting
1265
+ * the `falseForkContext` to the left operand.
1266
+ *
1267
+ * When a && expression is the left-hand operand for a ??
1268
+ * expression, such as `(a && b) ?? c`, a nullish value will
1269
+ * also short-circuit in a different way than a false value,
1270
+ * so we also set the `nullishForkContext` to the left operand.
1271
+ * This path is only used with a ?? expression and is thrown
1272
+ * away for any other type of logical expression, so it's safe
1273
+ * to always add.
1274
+ */
1275
+ currentChoiceContext.falseForkContext.add(forkContext.head);
1276
+ currentChoiceContext.nullishForkContext.add(forkContext.head);
1277
+ break;
1278
+ case "||": // the true path can short-circuit.
1279
+ currentChoiceContext.trueForkContext.add(forkContext.head);
1280
+ break;
1281
+ case "??": // both can short-circuit.
1282
+ currentChoiceContext.trueForkContext.add(forkContext.head);
1283
+ currentChoiceContext.falseForkContext.add(forkContext.head);
1284
+ break;
1285
+ default:
1286
+ throw new Error("unreachable");
1287
+ }
1288
+
1289
+ /*
1290
+ * Create the segment for the right-hand operand of the logical expression
1291
+ * and adjust the fork context pointer to point there.
1292
+ */
1293
+ forkContext.replaceHead(forkContext.makeNext(-1, -1));
1294
+ }
1295
+ }
1296
+
1297
+ /**
1298
+ * Makes a code path segment of the `if` block.
1299
+ * @returns {void}
1300
+ */
1301
+ makeIfConsequent() {
1302
+ const context = this.choiceContext;
1303
+ const forkContext = this.forkContext;
1304
+
1305
+ /*
1306
+ * If any result were not transferred from child contexts,
1307
+ * this sets the head segments to both cases.
1308
+ * The head segments are the path of the test expression.
1309
+ */
1310
+ if (!context.processed) {
1311
+ context.trueForkContext.add(forkContext.head);
1312
+ context.falseForkContext.add(forkContext.head);
1313
+ context.nullishForkContext.add(forkContext.head);
1314
+ }
1315
+
1316
+ context.processed = false;
1317
+
1318
+ // Creates new path from the `true` case.
1319
+ forkContext.replaceHead(
1320
+ context.trueForkContext.makeNext(0, -1)
1321
+ );
1322
+ }
1323
+
1324
+ /**
1325
+ * Makes a code path segment of the `else` block.
1326
+ * @returns {void}
1327
+ */
1328
+ makeIfAlternate() {
1329
+ const context = this.choiceContext;
1330
+ const forkContext = this.forkContext;
1331
+
1332
+ /*
1333
+ * The head segments are the path of the `if` block.
1334
+ * Updates the `true` path with the end of the `if` block.
1335
+ */
1336
+ context.trueForkContext.clear();
1337
+ context.trueForkContext.add(forkContext.head);
1338
+ context.processed = true;
1339
+
1340
+ // Creates new path from the `false` case.
1341
+ forkContext.replaceHead(
1342
+ context.falseForkContext.makeNext(0, -1)
1343
+ );
1344
+ }
1345
+
1346
+ //--------------------------------------------------------------------------
1347
+ // ChainExpression
1348
+ //--------------------------------------------------------------------------
1349
+
1350
+ /**
1351
+ * Pushes a new `ChainExpression` context to the stack. This method is
1352
+ * called when entering a `ChainExpression` node. A chain context is used to
1353
+ * count forking in the optional chain then merge them on the exiting from the
1354
+ * `ChainExpression` node.
1355
+ * @returns {void}
1356
+ */
1357
+ pushChainContext() {
1358
+ this.chainContext = new ChainContext(this.chainContext);
1359
+ }
1360
+
1361
+ /**
1362
+ * Pop a `ChainExpression` context from the stack. This method is called on
1363
+ * exiting from each `ChainExpression` node. This merges all forks of the
1364
+ * last optional chaining.
1365
+ * @returns {void}
1366
+ */
1367
+ popChainContext() {
1368
+ const context = this.chainContext;
1369
+
1370
+ this.chainContext = context.upper;
1371
+
1372
+ // pop all choice contexts of this.
1373
+ for (let i = context.choiceContextCount; i > 0; --i) {
1374
+ this.popChoiceContext();
1375
+ }
1376
+ }
1377
+
1378
+ /**
1379
+ * Create a choice context for optional access.
1380
+ * This method is called on entering to each `(Call|Member)Expression[optional=true]` node.
1381
+ * This creates a choice context as similar to `LogicalExpression[operator="??"]` node.
1382
+ * @returns {void}
1383
+ */
1384
+ makeOptionalNode() {
1385
+ if (this.chainContext) {
1386
+ this.chainContext.choiceContextCount += 1;
1387
+ this.pushChoiceContext("??", false);
1388
+ }
1389
+ }
1390
+
1391
+ /**
1392
+ * Create a fork.
1393
+ * This method is called on entering to the `arguments|property` property of each `(Call|Member)Expression` node.
1394
+ * @returns {void}
1395
+ */
1396
+ makeOptionalRight() {
1397
+ if (this.chainContext) {
1398
+ this.makeLogicalRight();
1399
+ }
1400
+ }
1401
+
1402
+ //--------------------------------------------------------------------------
1403
+ // SwitchStatement
1404
+ //--------------------------------------------------------------------------
1405
+
1406
+ /**
1407
+ * Creates a context object of SwitchStatement and stacks it.
1408
+ * @param {boolean} hasCase `true` if the switch statement has one or more
1409
+ * case parts.
1410
+ * @param {string|null} label The label text.
1411
+ * @returns {void}
1412
+ */
1413
+ pushSwitchContext(hasCase, label) {
1414
+ this.switchContext = new SwitchContext(this.switchContext, hasCase);
1415
+ this.pushBreakContext(true, label);
1416
+ }
1417
+
1418
+ /**
1419
+ * Pops the last context of SwitchStatement and finalizes it.
1420
+ *
1421
+ * - Disposes all forking stack for `case` and `default`.
1422
+ * - Creates the next code path segment from `context.brokenForkContext`.
1423
+ * - If the last `SwitchCase` node is not a `default` part, creates a path
1424
+ * to the `default` body.
1425
+ * @returns {void}
1426
+ */
1427
+ popSwitchContext() {
1428
+ const context = this.switchContext;
1429
+
1430
+ this.switchContext = context.upper;
1431
+
1432
+ const forkContext = this.forkContext;
1433
+ const brokenForkContext = this.popBreakContext().brokenForkContext;
1434
+
1435
+ if (context.forkCount === 0) {
1436
+
1437
+ /*
1438
+ * When there is only one `default` chunk and there is one or more
1439
+ * `break` statements, even if forks are nothing, it needs to merge
1440
+ * those.
1441
+ */
1442
+ if (!brokenForkContext.empty) {
1443
+ brokenForkContext.add(forkContext.makeNext(-1, -1));
1444
+ forkContext.replaceHead(brokenForkContext.makeNext(0, -1));
1445
+ }
1446
+
1447
+ return;
1448
+ }
1449
+
1450
+ const lastSegments = forkContext.head;
1451
+
1452
+ this.forkBypassPath();
1453
+ const lastCaseSegments = forkContext.head;
1454
+
1455
+ /*
1456
+ * `brokenForkContext` is used to make the next segment.
1457
+ * It must add the last segment into `brokenForkContext`.
1458
+ */
1459
+ brokenForkContext.add(lastSegments);
1460
+
1461
+ /*
1462
+ * Any value that doesn't match a `case` test should flow to the default
1463
+ * case. That happens normally when the default case is last in the `switch`,
1464
+ * but if it's not, we need to rewire some of the paths to be correct.
1465
+ */
1466
+ if (!context.lastIsDefault) {
1467
+ if (context.defaultBodySegments) {
1468
+
1469
+ /*
1470
+ * There is a non-empty default case, so remove the path from the `default`
1471
+ * label to its body for an accurate representation.
1472
+ */
1473
+ disconnectSegments(context.defaultSegments, context.defaultBodySegments);
1474
+
1475
+ /*
1476
+ * Connect the path from the last non-default case to the body of the
1477
+ * default case.
1478
+ */
1479
+ makeLooped(this, lastCaseSegments, context.defaultBodySegments);
1480
+
1481
+ } else {
1482
+
1483
+ /*
1484
+ * There is no default case, so we treat this as if the last case
1485
+ * had a `break` in it.
1486
+ */
1487
+ brokenForkContext.add(lastCaseSegments);
1488
+ }
1489
+ }
1490
+
1491
+ // Traverse up to the original fork context for the `switch` statement
1492
+ for (let i = 0; i < context.forkCount; ++i) {
1493
+ this.forkContext = this.forkContext.upper;
1494
+ }
1495
+
1496
+ /*
1497
+ * Creates a path from all `brokenForkContext` paths.
1498
+ * This is a path after `switch` statement.
1499
+ */
1500
+ this.forkContext.replaceHead(brokenForkContext.makeNext(0, -1));
1501
+ }
1502
+
1503
+ /**
1504
+ * Makes a code path segment for a `SwitchCase` node.
1505
+ * @param {boolean} isCaseBodyEmpty `true` if the body is empty.
1506
+ * @param {boolean} isDefaultCase `true` if the body is the default case.
1507
+ * @returns {void}
1508
+ */
1509
+ makeSwitchCaseBody(isCaseBodyEmpty, isDefaultCase) {
1510
+ const context = this.switchContext;
1511
+
1512
+ if (!context.hasCase) {
1513
+ return;
1514
+ }
1515
+
1516
+ /*
1517
+ * Merge forks.
1518
+ * The parent fork context has two segments.
1519
+ * Those are from the current `case` and the body of the previous case.
1520
+ */
1521
+ const parentForkContext = this.forkContext;
1522
+ const forkContext = this.pushForkContext();
1523
+
1524
+ forkContext.add(parentForkContext.makeNext(0, -1));
1525
+
1526
+ /*
1527
+ * Add information about the default case.
1528
+ *
1529
+ * The purpose of this is to identify the starting segments for the
1530
+ * default case to make sure there is a path there.
1531
+ */
1532
+ if (isDefaultCase) {
1533
+
1534
+ /*
1535
+ * This is the default case in the `switch`.
1536
+ *
1537
+ * We first save the current pointer as `defaultSegments` to point
1538
+ * to the `default` keyword.
1539
+ */
1540
+ context.defaultSegments = parentForkContext.head;
1541
+
1542
+ /*
1543
+ * If the body of the case is empty then we just set
1544
+ * `foundEmptyDefault` to true; otherwise, we save a reference
1545
+ * to the current pointer as `defaultBodySegments`.
1546
+ */
1547
+ if (isCaseBodyEmpty) {
1548
+ context.foundEmptyDefault = true;
1549
+ } else {
1550
+ context.defaultBodySegments = forkContext.head;
1551
+ }
1552
+
1553
+ } else {
1554
+
1555
+ /*
1556
+ * This is not the default case in the `switch`.
1557
+ *
1558
+ * If it's not empty and there is already an empty default case found,
1559
+ * that means the default case actually comes before this case,
1560
+ * and that it will fall through to this case. So, we can now
1561
+ * ignore the previous default case (reset `foundEmptyDefault` to false)
1562
+ * and set `defaultBodySegments` to the current segments because this is
1563
+ * effectively the new default case.
1564
+ */
1565
+ if (!isCaseBodyEmpty && context.foundEmptyDefault) {
1566
+ context.foundEmptyDefault = false;
1567
+ context.defaultBodySegments = forkContext.head;
1568
+ }
1569
+ }
1570
+
1571
+ // keep track if the default case ends up last
1572
+ context.lastIsDefault = isDefaultCase;
1573
+ context.forkCount += 1;
1574
+ }
1575
+
1576
+ //--------------------------------------------------------------------------
1577
+ // TryStatement
1578
+ //--------------------------------------------------------------------------
1579
+
1580
+ /**
1581
+ * Creates a context object of TryStatement and stacks it.
1582
+ * @param {boolean} hasFinalizer `true` if the try statement has a
1583
+ * `finally` block.
1584
+ * @returns {void}
1585
+ */
1586
+ pushTryContext(hasFinalizer) {
1587
+ this.tryContext = new TryContext(this.tryContext, hasFinalizer, this.forkContext);
1588
+ }
1589
+
1590
+ /**
1591
+ * Pops the last context of TryStatement and finalizes it.
1592
+ * @returns {void}
1593
+ */
1594
+ popTryContext() {
1595
+ const context = this.tryContext;
1596
+
1597
+ this.tryContext = context.upper;
1598
+
1599
+ /*
1600
+ * If we're inside the `catch` block, that means there is no `finally`,
1601
+ * so we can process the `try` and `catch` blocks the simple way and
1602
+ * merge their two paths.
1603
+ */
1604
+ if (context.position === "catch") {
1605
+ this.popForkContext();
1606
+ return;
1607
+ }
1608
+
1609
+ /*
1610
+ * The following process is executed only when there is a `finally`
1611
+ * block.
1612
+ */
1613
+
1614
+ const originalReturnedForkContext = context.returnedForkContext;
1615
+ const originalThrownForkContext = context.thrownForkContext;
1616
+
1617
+ // no `return` or `throw` in `try` or `catch` so there's nothing left to do
1618
+ if (originalReturnedForkContext.empty && originalThrownForkContext.empty) {
1619
+ return;
1620
+ }
1621
+
1622
+ /*
1623
+ * The following process is executed only when there is a `finally`
1624
+ * block and there was a `return` or `throw` in the `try` or `catch`
1625
+ * blocks.
1626
+ */
1627
+
1628
+ // Separate head to normal paths and leaving paths.
1629
+ const headSegments = this.forkContext.head;
1630
+
1631
+ this.forkContext = this.forkContext.upper;
1632
+ const normalSegments = headSegments.slice(0, headSegments.length / 2 | 0);
1633
+ const leavingSegments = headSegments.slice(headSegments.length / 2 | 0);
1634
+
1635
+ // Forwards the leaving path to upper contexts.
1636
+ if (!originalReturnedForkContext.empty) {
1637
+ getReturnContext(this).returnedForkContext.add(leavingSegments);
1638
+ }
1639
+ if (!originalThrownForkContext.empty) {
1640
+ getThrowContext(this).thrownForkContext.add(leavingSegments);
1641
+ }
1642
+
1643
+ // Sets the normal path as the next.
1644
+ this.forkContext.replaceHead(normalSegments);
1645
+
1646
+ /*
1647
+ * If both paths of the `try` block and the `catch` block are
1648
+ * unreachable, the next path becomes unreachable as well.
1649
+ */
1650
+ if (!context.lastOfTryIsReachable && !context.lastOfCatchIsReachable) {
1651
+ this.forkContext.makeUnreachable();
1652
+ }
1653
+ }
1654
+
1655
+ /**
1656
+ * Makes a code path segment for a `catch` block.
1657
+ * @returns {void}
1658
+ */
1659
+ makeCatchBlock() {
1660
+ const context = this.tryContext;
1661
+ const forkContext = this.forkContext;
1662
+ const originalThrownForkContext = context.thrownForkContext;
1663
+
1664
+ /*
1665
+ * We are now in a catch block so we need to update the context
1666
+ * with that information. This includes creating a new fork
1667
+ * context in case we encounter any `throw` statements here.
1668
+ */
1669
+ context.position = "catch";
1670
+ context.thrownForkContext = ForkContext.newEmpty(forkContext);
1671
+ context.lastOfTryIsReachable = forkContext.reachable;
1672
+
1673
+ // Merge the thrown paths from the `try` and `catch` blocks
1674
+ originalThrownForkContext.add(forkContext.head);
1675
+ const thrownSegments = originalThrownForkContext.makeNext(0, -1);
1676
+
1677
+ // Fork to a bypass and the merged thrown path.
1678
+ this.pushForkContext();
1679
+ this.forkBypassPath();
1680
+ this.forkContext.add(thrownSegments);
1681
+ }
1682
+
1683
+ /**
1684
+ * Makes a code path segment for a `finally` block.
1685
+ *
1686
+ * In the `finally` block, parallel paths are created. The parallel paths
1687
+ * are used as leaving-paths. The leaving-paths are paths from `return`
1688
+ * statements and `throw` statements in a `try` block or a `catch` block.
1689
+ * @returns {void}
1690
+ */
1691
+ makeFinallyBlock() {
1692
+ const context = this.tryContext;
1693
+ let forkContext = this.forkContext;
1694
+ const originalReturnedForkContext = context.returnedForkContext;
1695
+ const originalThrownForContext = context.thrownForkContext;
1696
+ const headOfLeavingSegments = forkContext.head;
1697
+
1698
+ // Update state.
1699
+ if (context.position === "catch") {
1700
+
1701
+ // Merges two paths from the `try` block and `catch` block.
1702
+ this.popForkContext();
1703
+ forkContext = this.forkContext;
1704
+
1705
+ context.lastOfCatchIsReachable = forkContext.reachable;
1706
+ } else {
1707
+ context.lastOfTryIsReachable = forkContext.reachable;
1708
+ }
1709
+
1710
+
1711
+ context.position = "finally";
1712
+
1713
+ /*
1714
+ * If there was no `return` or `throw` in either the `try` or `catch`
1715
+ * blocks, then there's no further code paths to create for `finally`.
1716
+ */
1717
+ if (originalReturnedForkContext.empty && originalThrownForContext.empty) {
1718
+
1719
+ // This path does not leave.
1720
+ return;
1721
+ }
1722
+
1723
+ /*
1724
+ * Create a parallel segment from merging returned and thrown.
1725
+ * This segment will leave at the end of this `finally` block.
1726
+ */
1727
+ const segments = forkContext.makeNext(-1, -1);
1728
+
1729
+ for (let i = 0; i < forkContext.count; ++i) {
1730
+ const prevSegsOfLeavingSegment = [headOfLeavingSegments[i]];
1731
+
1732
+ for (let j = 0; j < originalReturnedForkContext.segmentsList.length; ++j) {
1733
+ prevSegsOfLeavingSegment.push(originalReturnedForkContext.segmentsList[j][i]);
1734
+ }
1735
+ for (let j = 0; j < originalThrownForContext.segmentsList.length; ++j) {
1736
+ prevSegsOfLeavingSegment.push(originalThrownForContext.segmentsList[j][i]);
1737
+ }
1738
+
1739
+ segments.push(
1740
+ CodePathSegment.newNext(
1741
+ this.idGenerator.next(),
1742
+ prevSegsOfLeavingSegment
1743
+ )
1744
+ );
1745
+ }
1746
+
1747
+ this.pushForkContext(true);
1748
+ this.forkContext.add(segments);
1749
+ }
1750
+
1751
+ /**
1752
+ * Makes a code path segment from the first throwable node to the `catch`
1753
+ * block or the `finally` block.
1754
+ * @returns {void}
1755
+ */
1756
+ makeFirstThrowablePathInTryBlock() {
1757
+ const forkContext = this.forkContext;
1758
+
1759
+ if (!forkContext.reachable) {
1760
+ return;
1761
+ }
1762
+
1763
+ const context = getThrowContext(this);
1764
+
1765
+ if (context === this ||
1766
+ context.position !== "try" ||
1767
+ !context.thrownForkContext.empty
1768
+ ) {
1769
+ return;
1770
+ }
1771
+
1772
+ context.thrownForkContext.add(forkContext.head);
1773
+ forkContext.replaceHead(forkContext.makeNext(-1, -1));
1774
+ }
1775
+
1776
+ //--------------------------------------------------------------------------
1777
+ // Loop Statements
1778
+ //--------------------------------------------------------------------------
1779
+
1780
+ /**
1781
+ * Creates a context object of a loop statement and stacks it.
1782
+ * @param {string} type The type of the node which was triggered. One of
1783
+ * `WhileStatement`, `DoWhileStatement`, `ForStatement`, `ForInStatement`,
1784
+ * and `ForStatement`.
1785
+ * @param {string|null} label A label of the node which was triggered.
1786
+ * @throws {Error} (Unreachable - unknown type.)
1787
+ * @returns {void}
1788
+ */
1789
+ pushLoopContext(type, label) {
1790
+ const forkContext = this.forkContext;
1791
+
1792
+ // All loops need a path to account for `break` statements
1793
+ const breakContext = this.pushBreakContext(true, label);
1794
+
1795
+ switch (type) {
1796
+ case "WhileStatement":
1797
+ this.pushChoiceContext("loop", false);
1798
+ this.loopContext = new WhileLoopContext(this.loopContext, label, breakContext);
1799
+ break;
1800
+
1801
+ case "DoWhileStatement":
1802
+ this.pushChoiceContext("loop", false);
1803
+ this.loopContext = new DoWhileLoopContext(this.loopContext, label, breakContext, forkContext);
1804
+ break;
1805
+
1806
+ case "ForStatement":
1807
+ this.pushChoiceContext("loop", false);
1808
+ this.loopContext = new ForLoopContext(this.loopContext, label, breakContext);
1809
+ break;
1810
+
1811
+ case "ForInStatement":
1812
+ this.loopContext = new ForInLoopContext(this.loopContext, label, breakContext);
1813
+ break;
1814
+
1815
+ case "ForOfStatement":
1816
+ this.loopContext = new ForOfLoopContext(this.loopContext, label, breakContext);
1817
+ break;
1818
+
1819
+ /* c8 ignore next */
1820
+ default:
1821
+ throw new Error(`unknown type: "${type}"`);
1822
+ }
1823
+ }
1824
+
1825
+ /**
1826
+ * Pops the last context of a loop statement and finalizes it.
1827
+ * @throws {Error} (Unreachable - unknown type.)
1828
+ * @returns {void}
1829
+ */
1830
+ popLoopContext() {
1831
+ const context = this.loopContext;
1832
+
1833
+ this.loopContext = context.upper;
1834
+
1835
+ const forkContext = this.forkContext;
1836
+ const brokenForkContext = this.popBreakContext().brokenForkContext;
1837
+
1838
+ // Creates a looped path.
1839
+ switch (context.type) {
1840
+ case "WhileStatement":
1841
+ case "ForStatement":
1842
+ this.popChoiceContext();
1843
+
1844
+ /*
1845
+ * Creates the path from the end of the loop body up to the
1846
+ * location where `continue` would jump to.
1847
+ */
1848
+ makeLooped(
1849
+ this,
1850
+ forkContext.head,
1851
+ context.continueDestSegments
1852
+ );
1853
+ break;
1854
+
1855
+ case "DoWhileStatement": {
1856
+ const choiceContext = this.popChoiceContext();
1857
+
1858
+ if (!choiceContext.processed) {
1859
+ choiceContext.trueForkContext.add(forkContext.head);
1860
+ choiceContext.falseForkContext.add(forkContext.head);
1861
+ }
1862
+
1863
+ /*
1864
+ * If this isn't a hardcoded `true` condition, then `break`
1865
+ * should continue down the path as if the condition evaluated
1866
+ * to false.
1867
+ */
1868
+ if (context.test !== true) {
1869
+ brokenForkContext.addAll(choiceContext.falseForkContext);
1870
+ }
1871
+
1872
+ /*
1873
+ * When the condition is true, the loop continues back to the top,
1874
+ * so create a path from each possible true condition back to the
1875
+ * top of the loop.
1876
+ */
1877
+ const segmentsList = choiceContext.trueForkContext.segmentsList;
1878
+
1879
+ for (let i = 0; i < segmentsList.length; ++i) {
1880
+ makeLooped(
1881
+ this,
1882
+ segmentsList[i],
1883
+ context.entrySegments
1884
+ );
1885
+ }
1886
+ break;
1887
+ }
1888
+
1889
+ case "ForInStatement":
1890
+ case "ForOfStatement":
1891
+ brokenForkContext.add(forkContext.head);
1892
+
1893
+ /*
1894
+ * Creates the path from the end of the loop body up to the
1895
+ * left expression (left of `in` or `of`) of the loop.
1896
+ */
1897
+ makeLooped(
1898
+ this,
1899
+ forkContext.head,
1900
+ context.leftSegments
1901
+ );
1902
+ break;
1903
+
1904
+ /* c8 ignore next */
1905
+ default:
1906
+ throw new Error("unreachable");
1907
+ }
1908
+
1909
+ /*
1910
+ * If there wasn't a `break` statement in the loop, then we're at
1911
+ * the end of the loop's path, so we make an unreachable segment
1912
+ * to mark that.
1913
+ *
1914
+ * If there was a `break` statement, then we continue on into the
1915
+ * `brokenForkContext`.
1916
+ */
1917
+ if (brokenForkContext.empty) {
1918
+ forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
1919
+ } else {
1920
+ forkContext.replaceHead(brokenForkContext.makeNext(0, -1));
1921
+ }
1922
+ }
1923
+
1924
+ /**
1925
+ * Makes a code path segment for the test part of a WhileStatement.
1926
+ * @param {boolean|undefined} test The test value (only when constant).
1927
+ * @returns {void}
1928
+ */
1929
+ makeWhileTest(test) {
1930
+ const context = this.loopContext;
1931
+ const forkContext = this.forkContext;
1932
+ const testSegments = forkContext.makeNext(0, -1);
1933
+
1934
+ // Update state.
1935
+ context.test = test;
1936
+ context.continueDestSegments = testSegments;
1937
+ forkContext.replaceHead(testSegments);
1938
+ }
1939
+
1940
+ /**
1941
+ * Makes a code path segment for the body part of a WhileStatement.
1942
+ * @returns {void}
1943
+ */
1944
+ makeWhileBody() {
1945
+ const context = this.loopContext;
1946
+ const choiceContext = this.choiceContext;
1947
+ const forkContext = this.forkContext;
1948
+
1949
+ if (!choiceContext.processed) {
1950
+ choiceContext.trueForkContext.add(forkContext.head);
1951
+ choiceContext.falseForkContext.add(forkContext.head);
1952
+ }
1953
+
1954
+ /*
1955
+ * If this isn't a hardcoded `true` condition, then `break`
1956
+ * should continue down the path as if the condition evaluated
1957
+ * to false.
1958
+ */
1959
+ if (context.test !== true) {
1960
+ context.brokenForkContext.addAll(choiceContext.falseForkContext);
1961
+ }
1962
+ forkContext.replaceHead(choiceContext.trueForkContext.makeNext(0, -1));
1963
+ }
1964
+
1965
+ /**
1966
+ * Makes a code path segment for the body part of a DoWhileStatement.
1967
+ * @returns {void}
1968
+ */
1969
+ makeDoWhileBody() {
1970
+ const context = this.loopContext;
1971
+ const forkContext = this.forkContext;
1972
+ const bodySegments = forkContext.makeNext(-1, -1);
1973
+
1974
+ // Update state.
1975
+ context.entrySegments = bodySegments;
1976
+ forkContext.replaceHead(bodySegments);
1977
+ }
1978
+
1979
+ /**
1980
+ * Makes a code path segment for the test part of a DoWhileStatement.
1981
+ * @param {boolean|undefined} test The test value (only when constant).
1982
+ * @returns {void}
1983
+ */
1984
+ makeDoWhileTest(test) {
1985
+ const context = this.loopContext;
1986
+ const forkContext = this.forkContext;
1987
+
1988
+ context.test = test;
1989
+
1990
+ /*
1991
+ * If there is a `continue` statement in the loop then `continueForkContext`
1992
+ * won't be empty. We wire up the path from `continue` to the loop
1993
+ * test condition and then continue the traversal in the root fork context.
1994
+ */
1995
+ if (!context.continueForkContext.empty) {
1996
+ context.continueForkContext.add(forkContext.head);
1997
+ const testSegments = context.continueForkContext.makeNext(0, -1);
1998
+
1999
+ forkContext.replaceHead(testSegments);
2000
+ }
2001
+ }
2002
+
2003
+ /**
2004
+ * Makes a code path segment for the test part of a ForStatement.
2005
+ * @param {boolean|undefined} test The test value (only when constant).
2006
+ * @returns {void}
2007
+ */
2008
+ makeForTest(test) {
2009
+ const context = this.loopContext;
2010
+ const forkContext = this.forkContext;
2011
+ const endOfInitSegments = forkContext.head;
2012
+ const testSegments = forkContext.makeNext(-1, -1);
2013
+
2014
+ /*
2015
+ * Update the state.
2016
+ *
2017
+ * The `continueDestSegments` are set to `testSegments` because we
2018
+ * don't yet know if there is an update expression in this loop. So,
2019
+ * from what we already know at this point, a `continue` statement
2020
+ * will jump back to the test expression.
2021
+ */
2022
+ context.test = test;
2023
+ context.endOfInitSegments = endOfInitSegments;
2024
+ context.continueDestSegments = context.testSegments = testSegments;
2025
+ forkContext.replaceHead(testSegments);
2026
+ }
2027
+
2028
+ /**
2029
+ * Makes a code path segment for the update part of a ForStatement.
2030
+ * @returns {void}
2031
+ */
2032
+ makeForUpdate() {
2033
+ const context = this.loopContext;
2034
+ const choiceContext = this.choiceContext;
2035
+ const forkContext = this.forkContext;
2036
+
2037
+ // Make the next paths of the test.
2038
+ if (context.testSegments) {
2039
+ finalizeTestSegmentsOfFor(
2040
+ context,
2041
+ choiceContext,
2042
+ forkContext.head
2043
+ );
2044
+ } else {
2045
+ context.endOfInitSegments = forkContext.head;
2046
+ }
2047
+
2048
+ /*
2049
+ * Update the state.
2050
+ *
2051
+ * The `continueDestSegments` are now set to `updateSegments` because we
2052
+ * know there is an update expression in this loop. So, a `continue` statement
2053
+ * in the loop will jump to the update expression first, and then to any
2054
+ * test expression the loop might have.
2055
+ */
2056
+ const updateSegments = forkContext.makeDisconnected(-1, -1);
2057
+
2058
+ context.continueDestSegments = context.updateSegments = updateSegments;
2059
+ forkContext.replaceHead(updateSegments);
2060
+ }
2061
+
2062
+ /**
2063
+ * Makes a code path segment for the body part of a ForStatement.
2064
+ * @returns {void}
2065
+ */
2066
+ makeForBody() {
2067
+ const context = this.loopContext;
2068
+ const choiceContext = this.choiceContext;
2069
+ const forkContext = this.forkContext;
2070
+
2071
+ /*
2072
+ * Determine what to do based on which part of the `for` loop are present.
2073
+ * 1. If there is an update expression, then `updateSegments` is not null and
2074
+ * we need to assign `endOfUpdateSegments`, and if there is a test
2075
+ * expression, we then need to create the looped path to get back to
2076
+ * the test condition.
2077
+ * 2. If there is no update expression but there is a test expression,
2078
+ * then we only need to update the test segment information.
2079
+ * 3. If there is no update expression and no test expression, then we
2080
+ * just save `endOfInitSegments`.
2081
+ */
2082
+ if (context.updateSegments) {
2083
+ context.endOfUpdateSegments = forkContext.head;
2084
+
2085
+ /*
2086
+ * In a `for` loop that has both an update expression and a test
2087
+ * condition, execution flows from the test expression into the
2088
+ * loop body, to the update expression, and then back to the test
2089
+ * expression to determine if the loop should continue.
2090
+ *
2091
+ * To account for that, we need to make a path from the end of the
2092
+ * update expression to the start of the test expression. This is
2093
+ * effectively what creates the loop in the code path.
2094
+ */
2095
+ if (context.testSegments) {
2096
+ makeLooped(
2097
+ this,
2098
+ context.endOfUpdateSegments,
2099
+ context.testSegments
2100
+ );
2101
+ }
2102
+ } else if (context.testSegments) {
2103
+ finalizeTestSegmentsOfFor(
2104
+ context,
2105
+ choiceContext,
2106
+ forkContext.head
2107
+ );
2108
+ } else {
2109
+ context.endOfInitSegments = forkContext.head;
2110
+ }
2111
+
2112
+ let bodySegments = context.endOfTestSegments;
2113
+
2114
+ /*
2115
+ * If there is a test condition, then there `endOfTestSegments` is also
2116
+ * the start of the loop body. If there isn't a test condition then
2117
+ * `bodySegments` will be null and we need to look elsewhere to find
2118
+ * the start of the body.
2119
+ *
2120
+ * The body starts at the end of the init expression and ends at the end
2121
+ * of the update expression, so we use those locations to determine the
2122
+ * body segments.
2123
+ */
2124
+ if (!bodySegments) {
2125
+
2126
+ const prevForkContext = ForkContext.newEmpty(forkContext);
2127
+
2128
+ prevForkContext.add(context.endOfInitSegments);
2129
+ if (context.endOfUpdateSegments) {
2130
+ prevForkContext.add(context.endOfUpdateSegments);
2131
+ }
2132
+
2133
+ bodySegments = prevForkContext.makeNext(0, -1);
2134
+ }
2135
+
2136
+ /*
2137
+ * If there was no test condition and no update expression, then
2138
+ * `continueDestSegments` will be null. In that case, a
2139
+ * `continue` should skip directly to the body of the loop.
2140
+ * Otherwise, we want to keep the current `continueDestSegments`.
2141
+ */
2142
+ context.continueDestSegments = context.continueDestSegments || bodySegments;
2143
+
2144
+ // move pointer to the body
2145
+ forkContext.replaceHead(bodySegments);
2146
+ }
2147
+
2148
+ /**
2149
+ * Makes a code path segment for the left part of a ForInStatement and a
2150
+ * ForOfStatement.
2151
+ * @returns {void}
2152
+ */
2153
+ makeForInOfLeft() {
2154
+ const context = this.loopContext;
2155
+ const forkContext = this.forkContext;
2156
+ const leftSegments = forkContext.makeDisconnected(-1, -1);
2157
+
2158
+ // Update state.
2159
+ context.prevSegments = forkContext.head;
2160
+ context.leftSegments = context.continueDestSegments = leftSegments;
2161
+ forkContext.replaceHead(leftSegments);
2162
+ }
2163
+
2164
+ /**
2165
+ * Makes a code path segment for the right part of a ForInStatement and a
2166
+ * ForOfStatement.
2167
+ * @returns {void}
2168
+ */
2169
+ makeForInOfRight() {
2170
+ const context = this.loopContext;
2171
+ const forkContext = this.forkContext;
2172
+ const temp = ForkContext.newEmpty(forkContext);
2173
+
2174
+ temp.add(context.prevSegments);
2175
+ const rightSegments = temp.makeNext(-1, -1);
2176
+
2177
+ // Update state.
2178
+ context.endOfLeftSegments = forkContext.head;
2179
+ forkContext.replaceHead(rightSegments);
2180
+ }
2181
+
2182
+ /**
2183
+ * Makes a code path segment for the body part of a ForInStatement and a
2184
+ * ForOfStatement.
2185
+ * @returns {void}
2186
+ */
2187
+ makeForInOfBody() {
2188
+ const context = this.loopContext;
2189
+ const forkContext = this.forkContext;
2190
+ const temp = ForkContext.newEmpty(forkContext);
2191
+
2192
+ temp.add(context.endOfLeftSegments);
2193
+ const bodySegments = temp.makeNext(-1, -1);
2194
+
2195
+ // Make a path: `right` -> `left`.
2196
+ makeLooped(this, forkContext.head, context.leftSegments);
2197
+
2198
+ // Update state.
2199
+ context.brokenForkContext.add(forkContext.head);
2200
+ forkContext.replaceHead(bodySegments);
2201
+ }
2202
+
2203
+ //--------------------------------------------------------------------------
2204
+ // Control Statements
2205
+ //--------------------------------------------------------------------------
2206
+
2207
+ /**
2208
+ * Creates new context in which a `break` statement can be used. This occurs inside of a loop,
2209
+ * labeled statement, or switch statement.
2210
+ * @param {boolean} breakable Indicates if we are inside a statement where
2211
+ * `break` without a label will exit the statement.
2212
+ * @param {string|null} label The label associated with the statement.
2213
+ * @returns {BreakContext} The new context.
2214
+ */
2215
+ pushBreakContext(breakable, label) {
2216
+ this.breakContext = new BreakContext(this.breakContext, breakable, label, this.forkContext);
2217
+ return this.breakContext;
2218
+ }
2219
+
2220
+ /**
2221
+ * Removes the top item of the break context stack.
2222
+ * @returns {Object} The removed context.
2223
+ */
2224
+ popBreakContext() {
2225
+ const context = this.breakContext;
2226
+ const forkContext = this.forkContext;
2227
+
2228
+ this.breakContext = context.upper;
2229
+
2230
+ // Process this context here for other than switches and loops.
2231
+ if (!context.breakable) {
2232
+ const brokenForkContext = context.brokenForkContext;
2233
+
2234
+ if (!brokenForkContext.empty) {
2235
+ brokenForkContext.add(forkContext.head);
2236
+ forkContext.replaceHead(brokenForkContext.makeNext(0, -1));
2237
+ }
2238
+ }
2239
+
2240
+ return context;
2241
+ }
2242
+
2243
+ /**
2244
+ * Makes a path for a `break` statement.
2245
+ *
2246
+ * It registers the head segment to a context of `break`.
2247
+ * It makes new unreachable segment, then it set the head with the segment.
2248
+ * @param {string|null} label A label of the break statement.
2249
+ * @returns {void}
2250
+ */
2251
+ makeBreak(label) {
2252
+ const forkContext = this.forkContext;
2253
+
2254
+ if (!forkContext.reachable) {
2255
+ return;
2256
+ }
2257
+
2258
+ const context = getBreakContext(this, label);
2259
+
2260
+
2261
+ if (context) {
2262
+ context.brokenForkContext.add(forkContext.head);
2263
+ }
2264
+
2265
+ /* c8 ignore next */
2266
+ forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
2267
+ }
2268
+
2269
+ /**
2270
+ * Makes a path for a `continue` statement.
2271
+ *
2272
+ * It makes a looping path.
2273
+ * It makes new unreachable segment, then it set the head with the segment.
2274
+ * @param {string|null} label A label of the continue statement.
2275
+ * @returns {void}
2276
+ */
2277
+ makeContinue(label) {
2278
+ const forkContext = this.forkContext;
2279
+
2280
+ if (!forkContext.reachable) {
2281
+ return;
2282
+ }
2283
+
2284
+ const context = getContinueContext(this, label);
2285
+
2286
+ if (context) {
2287
+ if (context.continueDestSegments) {
2288
+ makeLooped(this, forkContext.head, context.continueDestSegments);
2289
+
2290
+ // If the context is a for-in/of loop, this affects a break also.
2291
+ if (context.type === "ForInStatement" ||
2292
+ context.type === "ForOfStatement"
2293
+ ) {
2294
+ context.brokenForkContext.add(forkContext.head);
2295
+ }
2296
+ } else {
2297
+ context.continueForkContext.add(forkContext.head);
2298
+ }
2299
+ }
2300
+ forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
2301
+ }
2302
+
2303
+ /**
2304
+ * Makes a path for a `return` statement.
2305
+ *
2306
+ * It registers the head segment to a context of `return`.
2307
+ * It makes new unreachable segment, then it set the head with the segment.
2308
+ * @returns {void}
2309
+ */
2310
+ makeReturn() {
2311
+ const forkContext = this.forkContext;
2312
+
2313
+ if (forkContext.reachable) {
2314
+ getReturnContext(this).returnedForkContext.add(forkContext.head);
2315
+ forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
2316
+ }
2317
+ }
2318
+
2319
+ /**
2320
+ * Makes a path for a `throw` statement.
2321
+ *
2322
+ * It registers the head segment to a context of `throw`.
2323
+ * It makes new unreachable segment, then it set the head with the segment.
2324
+ * @returns {void}
2325
+ */
2326
+ makeThrow() {
2327
+ const forkContext = this.forkContext;
2328
+
2329
+ if (forkContext.reachable) {
2330
+ getThrowContext(this).thrownForkContext.add(forkContext.head);
2331
+ forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
2332
+ }
2333
+ }
2334
+
2335
+ /**
2336
+ * Makes the final path.
2337
+ * @returns {void}
2338
+ */
2339
+ makeFinal() {
2340
+ const segments = this.currentSegments;
2341
+
2342
+ if (segments.length > 0 && segments[0].reachable) {
2343
+ this.returnedForkContext.add(segments);
2344
+ }
2345
+ }
2346
+ }
2347
+
2348
+ module.exports = CodePathState;
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/code-path-analysis/code-path.js ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview A class of the code path.
3
+ * @author Toru Nagashima
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //------------------------------------------------------------------------------
9
+ // Requirements
10
+ //------------------------------------------------------------------------------
11
+
12
+ const CodePathState = require("./code-path-state");
13
+ const IdGenerator = require("./id-generator");
14
+
15
+ //------------------------------------------------------------------------------
16
+ // Public Interface
17
+ //------------------------------------------------------------------------------
18
+
19
+ /**
20
+ * A code path.
21
+ */
22
+ class CodePath {
23
+
24
+ /**
25
+ * Creates a new instance.
26
+ * @param {Object} options Options for the function (see below).
27
+ * @param {string} options.id An identifier.
28
+ * @param {string} options.origin The type of code path origin.
29
+ * @param {CodePath|null} options.upper The code path of the upper function scope.
30
+ * @param {Function} options.onLooped A callback function to notify looping.
31
+ */
32
+ constructor({ id, origin, upper, onLooped }) {
33
+
34
+ /**
35
+ * The identifier of this code path.
36
+ * Rules use it to store additional information of each rule.
37
+ * @type {string}
38
+ */
39
+ this.id = id;
40
+
41
+ /**
42
+ * The reason that this code path was started. May be "program",
43
+ * "function", "class-field-initializer", or "class-static-block".
44
+ * @type {string}
45
+ */
46
+ this.origin = origin;
47
+
48
+ /**
49
+ * The code path of the upper function scope.
50
+ * @type {CodePath|null}
51
+ */
52
+ this.upper = upper;
53
+
54
+ /**
55
+ * The code paths of nested function scopes.
56
+ * @type {CodePath[]}
57
+ */
58
+ this.childCodePaths = [];
59
+
60
+ // Initializes internal state.
61
+ Object.defineProperty(
62
+ this,
63
+ "internal",
64
+ { value: new CodePathState(new IdGenerator(`${id}_`), onLooped) }
65
+ );
66
+
67
+ // Adds this into `childCodePaths` of `upper`.
68
+ if (upper) {
69
+ upper.childCodePaths.push(this);
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Gets the state of a given code path.
75
+ * @param {CodePath} codePath A code path to get.
76
+ * @returns {CodePathState} The state of the code path.
77
+ */
78
+ static getState(codePath) {
79
+ return codePath.internal;
80
+ }
81
+
82
+ /**
83
+ * The initial code path segment. This is the segment that is at the head
84
+ * of the code path.
85
+ * This is a passthrough to the underlying `CodePathState`.
86
+ * @type {CodePathSegment}
87
+ */
88
+ get initialSegment() {
89
+ return this.internal.initialSegment;
90
+ }
91
+
92
+ /**
93
+ * Final code path segments. These are the terminal (tail) segments in the
94
+ * code path, which is the combination of `returnedSegments` and `thrownSegments`.
95
+ * All segments in this array are reachable.
96
+ * This is a passthrough to the underlying `CodePathState`.
97
+ * @type {CodePathSegment[]}
98
+ */
99
+ get finalSegments() {
100
+ return this.internal.finalSegments;
101
+ }
102
+
103
+ /**
104
+ * Final code path segments that represent normal completion of the code path.
105
+ * For functions, this means both explicit `return` statements and implicit returns,
106
+ * such as the last reachable segment in a function that does not have an
107
+ * explicit `return` as this implicitly returns `undefined`. For scripts,
108
+ * modules, class field initializers, and class static blocks, this means
109
+ * all lines of code have been executed.
110
+ * These segments are also present in `finalSegments`.
111
+ * This is a passthrough to the underlying `CodePathState`.
112
+ * @type {CodePathSegment[]}
113
+ */
114
+ get returnedSegments() {
115
+ return this.internal.returnedForkContext;
116
+ }
117
+
118
+ /**
119
+ * Final code path segments that represent `throw` statements.
120
+ * This is a passthrough to the underlying `CodePathState`.
121
+ * These segments are also present in `finalSegments`.
122
+ * @type {CodePathSegment[]}
123
+ */
124
+ get thrownSegments() {
125
+ return this.internal.thrownForkContext;
126
+ }
127
+
128
+ /**
129
+ * Tracks the traversal of the code path through each segment. This array
130
+ * starts empty and segments are added or removed as the code path is
131
+ * traversed. This array always ends up empty at the end of a code path
132
+ * traversal. The `CodePathState` uses this to track its progress through
133
+ * the code path.
134
+ * This is a passthrough to the underlying `CodePathState`.
135
+ * @type {CodePathSegment[]}
136
+ * @deprecated
137
+ */
138
+ get currentSegments() {
139
+ return this.internal.currentSegments;
140
+ }
141
+
142
+ /**
143
+ * Traverses all segments in this code path.
144
+ *
145
+ * codePath.traverseSegments((segment, controller) => {
146
+ * // do something.
147
+ * });
148
+ *
149
+ * This method enumerates segments in order from the head.
150
+ *
151
+ * The `controller` argument has two methods:
152
+ *
153
+ * - `skip()` - skips the following segments in this branch
154
+ * - `break()` - skips all following segments in the traversal
155
+ *
156
+ * A note on the parameters: the `options` argument is optional. This means
157
+ * the first argument might be an options object or the callback function.
158
+ * @param {Object} [optionsOrCallback] Optional first and last segments to traverse.
159
+ * @param {CodePathSegment} [optionsOrCallback.first] The first segment to traverse.
160
+ * @param {CodePathSegment} [optionsOrCallback.last] The last segment to traverse.
161
+ * @param {Function} callback A callback function.
162
+ * @returns {void}
163
+ */
164
+ traverseSegments(optionsOrCallback, callback) {
165
+
166
+ // normalize the arguments into a callback and options
167
+ let resolvedOptions;
168
+ let resolvedCallback;
169
+
170
+ if (typeof optionsOrCallback === "function") {
171
+ resolvedCallback = optionsOrCallback;
172
+ resolvedOptions = {};
173
+ } else {
174
+ resolvedOptions = optionsOrCallback || {};
175
+ resolvedCallback = callback;
176
+ }
177
+
178
+ // determine where to start traversing from based on the options
179
+ const startSegment = resolvedOptions.first || this.internal.initialSegment;
180
+ const lastSegment = resolvedOptions.last;
181
+
182
+ // set up initial location information
183
+ let record = null;
184
+ let index = 0;
185
+ let end = 0;
186
+ let segment = null;
187
+
188
+ // segments that have already been visited during traversal
189
+ const visited = new Set();
190
+
191
+ // tracks the traversal steps
192
+ const stack = [[startSegment, 0]];
193
+
194
+ // tracks the last skipped segment during traversal
195
+ let skippedSegment = null;
196
+
197
+ // indicates if we exited early from the traversal
198
+ let broken = false;
199
+
200
+ /**
201
+ * Maintains traversal state.
202
+ */
203
+ const controller = {
204
+
205
+ /**
206
+ * Skip the following segments in this branch.
207
+ * @returns {void}
208
+ */
209
+ skip() {
210
+ if (stack.length <= 1) {
211
+ broken = true;
212
+ } else {
213
+ skippedSegment = stack[stack.length - 2][0];
214
+ }
215
+ },
216
+
217
+ /**
218
+ * Stop traversal completely - do not traverse to any
219
+ * other segments.
220
+ * @returns {void}
221
+ */
222
+ break() {
223
+ broken = true;
224
+ }
225
+ };
226
+
227
+ /**
228
+ * Checks if a given previous segment has been visited.
229
+ * @param {CodePathSegment} prevSegment A previous segment to check.
230
+ * @returns {boolean} `true` if the segment has been visited.
231
+ */
232
+ function isVisited(prevSegment) {
233
+ return (
234
+ visited.has(prevSegment) ||
235
+ segment.isLoopedPrevSegment(prevSegment)
236
+ );
237
+ }
238
+
239
+ // the traversal
240
+ while (stack.length > 0) {
241
+
242
+ /*
243
+ * This isn't a pure stack. We use the top record all the time
244
+ * but don't always pop it off. The record is popped only if
245
+ * one of the following is true:
246
+ *
247
+ * 1) We have already visited the segment.
248
+ * 2) We have not visited *all* of the previous segments.
249
+ * 3) We have traversed past the available next segments.
250
+ *
251
+ * Otherwise, we just read the value and sometimes modify the
252
+ * record as we traverse.
253
+ */
254
+ record = stack[stack.length - 1];
255
+ segment = record[0];
256
+ index = record[1];
257
+
258
+ if (index === 0) {
259
+
260
+ // Skip if this segment has been visited already.
261
+ if (visited.has(segment)) {
262
+ stack.pop();
263
+ continue;
264
+ }
265
+
266
+ // Skip if all previous segments have not been visited.
267
+ if (segment !== startSegment &&
268
+ segment.prevSegments.length > 0 &&
269
+ !segment.prevSegments.every(isVisited)
270
+ ) {
271
+ stack.pop();
272
+ continue;
273
+ }
274
+
275
+ // Reset the skipping flag if all branches have been skipped.
276
+ if (skippedSegment && segment.prevSegments.includes(skippedSegment)) {
277
+ skippedSegment = null;
278
+ }
279
+ visited.add(segment);
280
+
281
+ /*
282
+ * If the most recent segment hasn't been skipped, then we call
283
+ * the callback, passing in the segment and the controller.
284
+ */
285
+ if (!skippedSegment) {
286
+ resolvedCallback.call(this, segment, controller);
287
+
288
+ // exit if we're at the last segment
289
+ if (segment === lastSegment) {
290
+ controller.skip();
291
+ }
292
+
293
+ /*
294
+ * If the previous statement was executed, or if the callback
295
+ * called a method on the controller, we might need to exit the
296
+ * loop, so check for that and break accordingly.
297
+ */
298
+ if (broken) {
299
+ break;
300
+ }
301
+ }
302
+ }
303
+
304
+ // Update the stack.
305
+ end = segment.nextSegments.length - 1;
306
+ if (index < end) {
307
+
308
+ /*
309
+ * If we haven't yet visited all of the next segments, update
310
+ * the current top record on the stack to the next index to visit
311
+ * and then push a record for the current segment on top.
312
+ *
313
+ * Setting the current top record's index lets us know how many
314
+ * times we've been here and ensures that the segment won't be
315
+ * reprocessed (because we only process segments with an index
316
+ * of 0).
317
+ */
318
+ record[1] += 1;
319
+ stack.push([segment.nextSegments[index], 0]);
320
+ } else if (index === end) {
321
+
322
+ /*
323
+ * If we are at the last next segment, then reset the top record
324
+ * in the stack to next segment and set its index to 0 so it will
325
+ * be processed next.
326
+ */
327
+ record[0] = segment.nextSegments[index];
328
+ record[1] = 0;
329
+ } else {
330
+
331
+ /*
332
+ * If index > end, that means we have no more segments that need
333
+ * processing. So, we pop that record off of the stack in order to
334
+ * continue traversing at the next level up.
335
+ */
336
+ stack.pop();
337
+ }
338
+ }
339
+ }
340
+ }
341
+
342
+ module.exports = CodePath;
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/code-path-analysis/debug-helpers.js ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Helpers to debug for code path analysis.
3
+ * @author Toru Nagashima
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //------------------------------------------------------------------------------
9
+ // Requirements
10
+ //------------------------------------------------------------------------------
11
+
12
+ const debug = require("debug")("eslint:code-path");
13
+
14
+ //------------------------------------------------------------------------------
15
+ // Helpers
16
+ //------------------------------------------------------------------------------
17
+
18
+ /**
19
+ * Gets id of a given segment.
20
+ * @param {CodePathSegment} segment A segment to get.
21
+ * @returns {string} Id of the segment.
22
+ */
23
+ /* c8 ignore next */
24
+ function getId(segment) { // eslint-disable-line jsdoc/require-jsdoc -- Ignoring
25
+ return segment.id + (segment.reachable ? "" : "!");
26
+ }
27
+
28
+ /**
29
+ * Get string for the given node and operation.
30
+ * @param {ASTNode} node The node to convert.
31
+ * @param {"enter" | "exit" | undefined} label The operation label.
32
+ * @returns {string} The string representation.
33
+ */
34
+ function nodeToString(node, label) {
35
+ const suffix = label ? `:${label}` : "";
36
+
37
+ switch (node.type) {
38
+ case "Identifier": return `${node.type}${suffix} (${node.name})`;
39
+ case "Literal": return `${node.type}${suffix} (${node.value})`;
40
+ default: return `${node.type}${suffix}`;
41
+ }
42
+ }
43
+
44
+ //------------------------------------------------------------------------------
45
+ // Public Interface
46
+ //------------------------------------------------------------------------------
47
+
48
+ module.exports = {
49
+
50
+ /**
51
+ * A flag that debug dumping is enabled or not.
52
+ * @type {boolean}
53
+ */
54
+ enabled: debug.enabled,
55
+
56
+ /**
57
+ * Dumps given objects.
58
+ * @param {...any} args objects to dump.
59
+ * @returns {void}
60
+ */
61
+ dump: debug,
62
+
63
+ /**
64
+ * Dumps the current analyzing state.
65
+ * @param {ASTNode} node A node to dump.
66
+ * @param {CodePathState} state A state to dump.
67
+ * @param {boolean} leaving A flag whether or not it's leaving
68
+ * @returns {void}
69
+ */
70
+ dumpState: !debug.enabled ? debug : /* c8 ignore next */ function(node, state, leaving) {
71
+ for (let i = 0; i < state.currentSegments.length; ++i) {
72
+ const segInternal = state.currentSegments[i].internal;
73
+
74
+ if (leaving) {
75
+ const last = segInternal.nodes.length - 1;
76
+
77
+ if (last >= 0 && segInternal.nodes[last] === nodeToString(node, "enter")) {
78
+ segInternal.nodes[last] = nodeToString(node, void 0);
79
+ } else {
80
+ segInternal.nodes.push(nodeToString(node, "exit"));
81
+ }
82
+ } else {
83
+ segInternal.nodes.push(nodeToString(node, "enter"));
84
+ }
85
+ }
86
+
87
+ debug([
88
+ `${state.currentSegments.map(getId).join(",")})`,
89
+ `${node.type}${leaving ? ":exit" : ""}`
90
+ ].join(" "));
91
+ },
92
+
93
+ /**
94
+ * Dumps a DOT code of a given code path.
95
+ * The DOT code can be visualized with Graphvis.
96
+ * @param {CodePath} codePath A code path to dump.
97
+ * @returns {void}
98
+ * @see http://www.graphviz.org
99
+ * @see http://www.webgraphviz.com
100
+ */
101
+ dumpDot: !debug.enabled ? debug : /* c8 ignore next */ function(codePath) {
102
+ let text =
103
+ "\n" +
104
+ "digraph {\n" +
105
+ "node[shape=box,style=\"rounded,filled\",fillcolor=white];\n" +
106
+ "initial[label=\"\",shape=circle,style=filled,fillcolor=black,width=0.25,height=0.25];\n";
107
+
108
+ if (codePath.returnedSegments.length > 0) {
109
+ text += "final[label=\"\",shape=doublecircle,style=filled,fillcolor=black,width=0.25,height=0.25];\n";
110
+ }
111
+ if (codePath.thrownSegments.length > 0) {
112
+ text += "thrown[label=\"✘\",shape=circle,width=0.3,height=0.3,fixedsize=true];\n";
113
+ }
114
+
115
+ const traceMap = Object.create(null);
116
+ const arrows = this.makeDotArrows(codePath, traceMap);
117
+
118
+ for (const id in traceMap) { // eslint-disable-line guard-for-in -- Want ability to traverse prototype
119
+ const segment = traceMap[id];
120
+
121
+ text += `${id}[`;
122
+
123
+ if (segment.reachable) {
124
+ text += "label=\"";
125
+ } else {
126
+ text += "style=\"rounded,dashed,filled\",fillcolor=\"#FF9800\",label=\"<<unreachable>>\\n";
127
+ }
128
+
129
+ if (segment.internal.nodes.length > 0) {
130
+ text += segment.internal.nodes.join("\\n");
131
+ } else {
132
+ text += "????";
133
+ }
134
+
135
+ text += "\"];\n";
136
+ }
137
+
138
+ text += `${arrows}\n`;
139
+ text += "}";
140
+ debug("DOT", text);
141
+ },
142
+
143
+ /**
144
+ * Makes a DOT code of a given code path.
145
+ * The DOT code can be visualized with Graphvis.
146
+ * @param {CodePath} codePath A code path to make DOT.
147
+ * @param {Object} traceMap Optional. A map to check whether or not segments had been done.
148
+ * @returns {string} A DOT code of the code path.
149
+ */
150
+ makeDotArrows(codePath, traceMap) {
151
+ const stack = [[codePath.initialSegment, 0]];
152
+ const done = traceMap || Object.create(null);
153
+ let lastId = codePath.initialSegment.id;
154
+ let text = `initial->${codePath.initialSegment.id}`;
155
+
156
+ while (stack.length > 0) {
157
+ const item = stack.pop();
158
+ const segment = item[0];
159
+ const index = item[1];
160
+
161
+ if (done[segment.id] && index === 0) {
162
+ continue;
163
+ }
164
+ done[segment.id] = segment;
165
+
166
+ const nextSegment = segment.allNextSegments[index];
167
+
168
+ if (!nextSegment) {
169
+ continue;
170
+ }
171
+
172
+ if (lastId === segment.id) {
173
+ text += `->${nextSegment.id}`;
174
+ } else {
175
+ text += `;\n${segment.id}->${nextSegment.id}`;
176
+ }
177
+ lastId = nextSegment.id;
178
+
179
+ stack.unshift([segment, 1 + index]);
180
+ stack.push([nextSegment, 0]);
181
+ }
182
+
183
+ codePath.returnedSegments.forEach(finalSegment => {
184
+ if (lastId === finalSegment.id) {
185
+ text += "->final";
186
+ } else {
187
+ text += `;\n${finalSegment.id}->final`;
188
+ }
189
+ lastId = null;
190
+ });
191
+
192
+ codePath.thrownSegments.forEach(finalSegment => {
193
+ if (lastId === finalSegment.id) {
194
+ text += "->thrown";
195
+ } else {
196
+ text += `;\n${finalSegment.id}->thrown`;
197
+ }
198
+ lastId = null;
199
+ });
200
+
201
+ return `${text};`;
202
+ }
203
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/code-path-analysis/fork-context.js ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview A class to operate forking.
3
+ *
4
+ * This is state of forking.
5
+ * This has a fork list and manages it.
6
+ *
7
+ * @author Toru Nagashima
8
+ */
9
+
10
+ "use strict";
11
+
12
+ //------------------------------------------------------------------------------
13
+ // Requirements
14
+ //------------------------------------------------------------------------------
15
+
16
+ const assert = require("assert"),
17
+ CodePathSegment = require("./code-path-segment");
18
+
19
+ //------------------------------------------------------------------------------
20
+ // Helpers
21
+ //------------------------------------------------------------------------------
22
+
23
+ /**
24
+ * Determines whether or not a given segment is reachable.
25
+ * @param {CodePathSegment} segment The segment to check.
26
+ * @returns {boolean} `true` if the segment is reachable.
27
+ */
28
+ function isReachable(segment) {
29
+ return segment.reachable;
30
+ }
31
+
32
+ /**
33
+ * Creates a new segment for each fork in the given context and appends it
34
+ * to the end of the specified range of segments. Ultimately, this ends up calling
35
+ * `new CodePathSegment()` for each of the forks using the `create` argument
36
+ * as a wrapper around special behavior.
37
+ *
38
+ * The `startIndex` and `endIndex` arguments specify a range of segments in
39
+ * `context` that should become `allPrevSegments` for the newly created
40
+ * `CodePathSegment` objects.
41
+ *
42
+ * When `context.segmentsList` is `[[a, b], [c, d], [e, f]]`, `begin` is `0`, and
43
+ * `end` is `-1`, this creates two new segments, `[g, h]`. This `g` is appended to
44
+ * the end of the path from `a`, `c`, and `e`. This `h` is appended to the end of
45
+ * `b`, `d`, and `f`.
46
+ * @param {ForkContext} context An instance from which the previous segments
47
+ * will be obtained.
48
+ * @param {number} startIndex The index of the first segment in the context
49
+ * that should be specified as previous segments for the newly created segments.
50
+ * @param {number} endIndex The index of the last segment in the context
51
+ * that should be specified as previous segments for the newly created segments.
52
+ * @param {Function} create A function that creates new `CodePathSegment`
53
+ * instances in a particular way. See the `CodePathSegment.new*` methods.
54
+ * @returns {Array<CodePathSegment>} An array of the newly-created segments.
55
+ */
56
+ function createSegments(context, startIndex, endIndex, create) {
57
+
58
+ /** @type {Array<Array<CodePathSegment>>} */
59
+ const list = context.segmentsList;
60
+
61
+ /*
62
+ * Both `startIndex` and `endIndex` work the same way: if the number is zero
63
+ * or more, then the number is used as-is. If the number is negative,
64
+ * then that number is added to the length of the segments list to
65
+ * determine the index to use. That means -1 for either argument
66
+ * is the last element, -2 is the second to last, and so on.
67
+ *
68
+ * So if `startIndex` is 0, `endIndex` is -1, and `list.length` is 3, the
69
+ * effective `startIndex` is 0 and the effective `endIndex` is 2, so this function
70
+ * will include items at indices 0, 1, and 2.
71
+ *
72
+ * Therefore, if `startIndex` is -1 and `endIndex` is -1, that means we'll only
73
+ * be using the last segment in `list`.
74
+ */
75
+ const normalizedBegin = startIndex >= 0 ? startIndex : list.length + startIndex;
76
+ const normalizedEnd = endIndex >= 0 ? endIndex : list.length + endIndex;
77
+
78
+ /** @type {Array<CodePathSegment>} */
79
+ const segments = [];
80
+
81
+ for (let i = 0; i < context.count; ++i) {
82
+
83
+ // this is passed into `new CodePathSegment` to add to code path.
84
+ const allPrevSegments = [];
85
+
86
+ for (let j = normalizedBegin; j <= normalizedEnd; ++j) {
87
+ allPrevSegments.push(list[j][i]);
88
+ }
89
+
90
+ // note: `create` is just a wrapper that augments `new CodePathSegment`.
91
+ segments.push(create(context.idGenerator.next(), allPrevSegments));
92
+ }
93
+
94
+ return segments;
95
+ }
96
+
97
+ /**
98
+ * Inside of a `finally` block we end up with two parallel paths. If the code path
99
+ * exits by a control statement (such as `break` or `continue`) from the `finally`
100
+ * block, then we need to merge the remaining parallel paths back into one.
101
+ * @param {ForkContext} context The fork context to work on.
102
+ * @param {Array<CodePathSegment>} segments Segments to merge.
103
+ * @returns {Array<CodePathSegment>} The merged segments.
104
+ */
105
+ function mergeExtraSegments(context, segments) {
106
+ let currentSegments = segments;
107
+
108
+ /*
109
+ * We need to ensure that the array returned from this function contains no more
110
+ * than the number of segments that the context allows. `context.count` indicates
111
+ * how many items should be in the returned array to ensure that the new segment
112
+ * entries will line up with the already existing segment entries.
113
+ */
114
+ while (currentSegments.length > context.count) {
115
+ const merged = [];
116
+
117
+ /*
118
+ * Because `context.count` is a factor of 2 inside of a `finally` block,
119
+ * we can divide the segment count by 2 to merge the paths together.
120
+ * This loops through each segment in the list and creates a new `CodePathSegment`
121
+ * that has the segment and the segment two slots away as previous segments.
122
+ *
123
+ * If `currentSegments` is [a,b,c,d], this will create new segments e and f, such
124
+ * that:
125
+ *
126
+ * When `i` is 0:
127
+ * a->e
128
+ * c->e
129
+ *
130
+ * When `i` is 1:
131
+ * b->f
132
+ * d->f
133
+ */
134
+ for (let i = 0, length = Math.floor(currentSegments.length / 2); i < length; ++i) {
135
+ merged.push(CodePathSegment.newNext(
136
+ context.idGenerator.next(),
137
+ [currentSegments[i], currentSegments[i + length]]
138
+ ));
139
+ }
140
+
141
+ /*
142
+ * Go through the loop condition one more time to see if we have the
143
+ * number of segments for the context. If not, we'll keep merging paths
144
+ * of the merged segments until we get there.
145
+ */
146
+ currentSegments = merged;
147
+ }
148
+
149
+ return currentSegments;
150
+ }
151
+
152
+ //------------------------------------------------------------------------------
153
+ // Public Interface
154
+ //------------------------------------------------------------------------------
155
+
156
+ /**
157
+ * Manages the forking of code paths.
158
+ */
159
+ class ForkContext {
160
+
161
+ /**
162
+ * Creates a new instance.
163
+ * @param {IdGenerator} idGenerator An identifier generator for segments.
164
+ * @param {ForkContext|null} upper The preceding fork context.
165
+ * @param {number} count The number of parallel segments in each element
166
+ * of `segmentsList`.
167
+ */
168
+ constructor(idGenerator, upper, count) {
169
+
170
+ /**
171
+ * The ID generator that will generate segment IDs for any new
172
+ * segments that are created.
173
+ * @type {IdGenerator}
174
+ */
175
+ this.idGenerator = idGenerator;
176
+
177
+ /**
178
+ * The preceding fork context.
179
+ * @type {ForkContext|null}
180
+ */
181
+ this.upper = upper;
182
+
183
+ /**
184
+ * The number of elements in each element of `segmentsList`. In most
185
+ * cases, this is 1 but can be 2 when there is a `finally` present,
186
+ * which forks the code path outside of normal flow. In the case of nested
187
+ * `finally` blocks, this can be a multiple of 2.
188
+ * @type {number}
189
+ */
190
+ this.count = count;
191
+
192
+ /**
193
+ * The segments within this context. Each element in this array has
194
+ * `count` elements that represent one step in each fork. For example,
195
+ * when `segmentsList` is `[[a, b], [c, d], [e, f]]`, there is one path
196
+ * a->c->e and one path b->d->f, and `count` is 2 because each element
197
+ * is an array with two elements.
198
+ * @type {Array<Array<CodePathSegment>>}
199
+ */
200
+ this.segmentsList = [];
201
+ }
202
+
203
+ /**
204
+ * The segments that begin this fork context.
205
+ * @type {Array<CodePathSegment>}
206
+ */
207
+ get head() {
208
+ const list = this.segmentsList;
209
+
210
+ return list.length === 0 ? [] : list[list.length - 1];
211
+ }
212
+
213
+ /**
214
+ * Indicates if the context contains no segments.
215
+ * @type {boolean}
216
+ */
217
+ get empty() {
218
+ return this.segmentsList.length === 0;
219
+ }
220
+
221
+ /**
222
+ * Indicates if there are any segments that are reachable.
223
+ * @type {boolean}
224
+ */
225
+ get reachable() {
226
+ const segments = this.head;
227
+
228
+ return segments.length > 0 && segments.some(isReachable);
229
+ }
230
+
231
+ /**
232
+ * Creates new segments in this context and appends them to the end of the
233
+ * already existing `CodePathSegment`s specified by `startIndex` and
234
+ * `endIndex`.
235
+ * @param {number} startIndex The index of the first segment in the context
236
+ * that should be specified as previous segments for the newly created segments.
237
+ * @param {number} endIndex The index of the last segment in the context
238
+ * that should be specified as previous segments for the newly created segments.
239
+ * @returns {Array<CodePathSegment>} An array of the newly created segments.
240
+ */
241
+ makeNext(startIndex, endIndex) {
242
+ return createSegments(this, startIndex, endIndex, CodePathSegment.newNext);
243
+ }
244
+
245
+ /**
246
+ * Creates new unreachable segments in this context and appends them to the end of the
247
+ * already existing `CodePathSegment`s specified by `startIndex` and
248
+ * `endIndex`.
249
+ * @param {number} startIndex The index of the first segment in the context
250
+ * that should be specified as previous segments for the newly created segments.
251
+ * @param {number} endIndex The index of the last segment in the context
252
+ * that should be specified as previous segments for the newly created segments.
253
+ * @returns {Array<CodePathSegment>} An array of the newly created segments.
254
+ */
255
+ makeUnreachable(startIndex, endIndex) {
256
+ return createSegments(this, startIndex, endIndex, CodePathSegment.newUnreachable);
257
+ }
258
+
259
+ /**
260
+ * Creates new segments in this context and does not append them to the end
261
+ * of the already existing `CodePathSegment`s specified by `startIndex` and
262
+ * `endIndex`. The `startIndex` and `endIndex` are only used to determine if
263
+ * the new segments should be reachable. If any of the segments in this range
264
+ * are reachable then the new segments are also reachable; otherwise, the new
265
+ * segments are unreachable.
266
+ * @param {number} startIndex The index of the first segment in the context
267
+ * that should be considered for reachability.
268
+ * @param {number} endIndex The index of the last segment in the context
269
+ * that should be considered for reachability.
270
+ * @returns {Array<CodePathSegment>} An array of the newly created segments.
271
+ */
272
+ makeDisconnected(startIndex, endIndex) {
273
+ return createSegments(this, startIndex, endIndex, CodePathSegment.newDisconnected);
274
+ }
275
+
276
+ /**
277
+ * Adds segments to the head of this context.
278
+ * @param {Array<CodePathSegment>} segments The segments to add.
279
+ * @returns {void}
280
+ */
281
+ add(segments) {
282
+ assert(segments.length >= this.count, `${segments.length} >= ${this.count}`);
283
+ this.segmentsList.push(mergeExtraSegments(this, segments));
284
+ }
285
+
286
+ /**
287
+ * Replaces the head segments with the given segments.
288
+ * The current head segments are removed.
289
+ * @param {Array<CodePathSegment>} replacementHeadSegments The new head segments.
290
+ * @returns {void}
291
+ */
292
+ replaceHead(replacementHeadSegments) {
293
+ assert(
294
+ replacementHeadSegments.length >= this.count,
295
+ `${replacementHeadSegments.length} >= ${this.count}`
296
+ );
297
+ this.segmentsList.splice(-1, 1, mergeExtraSegments(this, replacementHeadSegments));
298
+ }
299
+
300
+ /**
301
+ * Adds all segments of a given fork context into this context.
302
+ * @param {ForkContext} otherForkContext The fork context to add from.
303
+ * @returns {void}
304
+ */
305
+ addAll(otherForkContext) {
306
+ assert(otherForkContext.count === this.count);
307
+ this.segmentsList.push(...otherForkContext.segmentsList);
308
+ }
309
+
310
+ /**
311
+ * Clears all segments in this context.
312
+ * @returns {void}
313
+ */
314
+ clear() {
315
+ this.segmentsList = [];
316
+ }
317
+
318
+ /**
319
+ * Creates a new root context, meaning that there are no parent
320
+ * fork contexts.
321
+ * @param {IdGenerator} idGenerator An identifier generator for segments.
322
+ * @returns {ForkContext} New fork context.
323
+ */
324
+ static newRoot(idGenerator) {
325
+ const context = new ForkContext(idGenerator, null, 1);
326
+
327
+ context.add([CodePathSegment.newRoot(idGenerator.next())]);
328
+
329
+ return context;
330
+ }
331
+
332
+ /**
333
+ * Creates an empty fork context preceded by a given context.
334
+ * @param {ForkContext} parentContext The parent fork context.
335
+ * @param {boolean} shouldForkLeavingPath Indicates that we are inside of
336
+ * a `finally` block and should therefore fork the path that leaves
337
+ * `finally`.
338
+ * @returns {ForkContext} New fork context.
339
+ */
340
+ static newEmpty(parentContext, shouldForkLeavingPath) {
341
+ return new ForkContext(
342
+ parentContext.idGenerator,
343
+ parentContext,
344
+ (shouldForkLeavingPath ? 2 : 1) * parentContext.count
345
+ );
346
+ }
347
+ }
348
+
349
+ module.exports = ForkContext;
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/code-path-analysis/id-generator.js ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview A class of identifiers generator for code path segments.
3
+ *
4
+ * Each rule uses the identifier of code path segments to store additional
5
+ * information of the code path.
6
+ *
7
+ * @author Toru Nagashima
8
+ */
9
+
10
+ "use strict";
11
+
12
+ //------------------------------------------------------------------------------
13
+ // Public Interface
14
+ //------------------------------------------------------------------------------
15
+
16
+ /**
17
+ * A generator for unique ids.
18
+ */
19
+ class IdGenerator {
20
+
21
+ /**
22
+ * @param {string} prefix Optional. A prefix of generated ids.
23
+ */
24
+ constructor(prefix) {
25
+ this.prefix = String(prefix);
26
+ this.n = 0;
27
+ }
28
+
29
+ /**
30
+ * Generates id.
31
+ * @returns {string} A generated id.
32
+ */
33
+ next() {
34
+ this.n = 1 + this.n | 0;
35
+
36
+ /* c8 ignore start */
37
+ if (this.n < 0) {
38
+ this.n = 1;
39
+ }/* c8 ignore stop */
40
+
41
+ return this.prefix + this.n;
42
+ }
43
+ }
44
+
45
+ module.exports = IdGenerator;
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/config-comment-parser.js ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Config Comment Parser
3
+ * @author Nicholas C. Zakas
4
+ */
5
+
6
+ /* eslint class-methods-use-this: off -- Methods desired on instance */
7
+ "use strict";
8
+
9
+ //------------------------------------------------------------------------------
10
+ // Requirements
11
+ //------------------------------------------------------------------------------
12
+
13
+ const levn = require("levn"),
14
+ {
15
+ Legacy: {
16
+ ConfigOps
17
+ }
18
+ } = require("@eslint/eslintrc/universal"),
19
+ {
20
+ directivesPattern
21
+ } = require("../shared/directives");
22
+
23
+ const debug = require("debug")("eslint:config-comment-parser");
24
+
25
+ //------------------------------------------------------------------------------
26
+ // Typedefs
27
+ //------------------------------------------------------------------------------
28
+
29
+ /** @typedef {import("../shared/types").LintMessage} LintMessage */
30
+
31
+ //------------------------------------------------------------------------------
32
+ // Public Interface
33
+ //------------------------------------------------------------------------------
34
+
35
+ /**
36
+ * Object to parse ESLint configuration comments inside JavaScript files.
37
+ * @name ConfigCommentParser
38
+ */
39
+ module.exports = class ConfigCommentParser {
40
+
41
+ /**
42
+ * Parses a list of "name:string_value" or/and "name" options divided by comma or
43
+ * whitespace. Used for "global" and "exported" comments.
44
+ * @param {string} string The string to parse.
45
+ * @param {Comment} comment The comment node which has the string.
46
+ * @returns {Object} Result map object of names and string values, or null values if no value was provided
47
+ */
48
+ parseStringConfig(string, comment) {
49
+ debug("Parsing String config");
50
+
51
+ const items = {};
52
+
53
+ // Collapse whitespace around `:` and `,` to make parsing easier
54
+ const trimmedString = string.replace(/\s*([:,])\s*/gu, "$1");
55
+
56
+ trimmedString.split(/\s|,+/u).forEach(name => {
57
+ if (!name) {
58
+ return;
59
+ }
60
+
61
+ // value defaults to null (if not provided), e.g: "foo" => ["foo", null]
62
+ const [key, value = null] = name.split(":");
63
+
64
+ items[key] = { value, comment };
65
+ });
66
+ return items;
67
+ }
68
+
69
+ /**
70
+ * Parses a JSON-like config.
71
+ * @param {string} string The string to parse.
72
+ * @param {Object} location Start line and column of comments for potential error message.
73
+ * @returns {({success: true, config: Object}|{success: false, error: LintMessage})} Result map object
74
+ */
75
+ parseJsonConfig(string, location) {
76
+ debug("Parsing JSON config");
77
+
78
+ let items = {};
79
+
80
+ // Parses a JSON-like comment by the same way as parsing CLI option.
81
+ try {
82
+ items = levn.parse("Object", string) || {};
83
+
84
+ // Some tests say that it should ignore invalid comments such as `/*eslint no-alert:abc*/`.
85
+ // Also, commaless notations have invalid severity:
86
+ // "no-alert: 2 no-console: 2" --> {"no-alert": "2 no-console: 2"}
87
+ // Should ignore that case as well.
88
+ if (ConfigOps.isEverySeverityValid(items)) {
89
+ return {
90
+ success: true,
91
+ config: items
92
+ };
93
+ }
94
+ } catch {
95
+
96
+ debug("Levn parsing failed; falling back to manual parsing.");
97
+
98
+ // ignore to parse the string by a fallback.
99
+ }
100
+
101
+ /*
102
+ * Optionator cannot parse commaless notations.
103
+ * But we are supporting that. So this is a fallback for that.
104
+ */
105
+ items = {};
106
+ const normalizedString = string.replace(/([-a-zA-Z0-9/]+):/gu, "\"$1\":").replace(/(\]|[0-9])\s+(?=")/u, "$1,");
107
+
108
+ try {
109
+ items = JSON.parse(`{${normalizedString}}`);
110
+ } catch (ex) {
111
+ debug("Manual parsing failed.");
112
+
113
+ return {
114
+ success: false,
115
+ error: {
116
+ ruleId: null,
117
+ fatal: true,
118
+ severity: 2,
119
+ message: `Failed to parse JSON from '${normalizedString}': ${ex.message}`,
120
+ line: location.start.line,
121
+ column: location.start.column + 1,
122
+ nodeType: null
123
+ }
124
+ };
125
+
126
+ }
127
+
128
+ return {
129
+ success: true,
130
+ config: items
131
+ };
132
+ }
133
+
134
+ /**
135
+ * Parses a config of values separated by comma.
136
+ * @param {string} string The string to parse.
137
+ * @returns {Object} Result map of values and true values
138
+ */
139
+ parseListConfig(string) {
140
+ debug("Parsing list config");
141
+
142
+ const items = {};
143
+
144
+ string.split(",").forEach(name => {
145
+ const trimmedName = name.trim().replace(/^(?<quote>['"]?)(?<ruleId>.*)\k<quote>$/us, "$<ruleId>");
146
+
147
+ if (trimmedName) {
148
+ items[trimmedName] = true;
149
+ }
150
+ });
151
+ return items;
152
+ }
153
+
154
+ /**
155
+ * Extract the directive and the justification from a given directive comment and trim them.
156
+ * @param {string} value The comment text to extract.
157
+ * @returns {{directivePart: string, justificationPart: string}} The extracted directive and justification.
158
+ */
159
+ extractDirectiveComment(value) {
160
+ const match = /\s-{2,}\s/u.exec(value);
161
+
162
+ if (!match) {
163
+ return { directivePart: value.trim(), justificationPart: "" };
164
+ }
165
+
166
+ const directive = value.slice(0, match.index).trim();
167
+ const justification = value.slice(match.index + match[0].length).trim();
168
+
169
+ return { directivePart: directive, justificationPart: justification };
170
+ }
171
+
172
+ /**
173
+ * Parses a directive comment into directive text and value.
174
+ * @param {Comment} comment The comment node with the directive to be parsed.
175
+ * @returns {{directiveText: string, directiveValue: string}} The directive text and value.
176
+ */
177
+ parseDirective(comment) {
178
+ const { directivePart } = this.extractDirectiveComment(comment.value);
179
+ const match = directivesPattern.exec(directivePart);
180
+ const directiveText = match[1];
181
+ const directiveValue = directivePart.slice(match.index + directiveText.length);
182
+
183
+ return { directiveText, directiveValue };
184
+ }
185
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/index.js ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use strict";
2
+
3
+ const { Linter } = require("./linter");
4
+ const interpolate = require("./interpolate");
5
+ const SourceCodeFixer = require("./source-code-fixer");
6
+
7
+ module.exports = {
8
+ Linter,
9
+
10
+ // For testers.
11
+ SourceCodeFixer,
12
+ interpolate
13
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/interpolate.js ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Interpolate keys from an object into a string with {{ }} markers.
3
+ * @author Jed Fox
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //------------------------------------------------------------------------------
9
+ // Public Interface
10
+ //------------------------------------------------------------------------------
11
+
12
+ module.exports = (text, data) => {
13
+ if (!data) {
14
+ return text;
15
+ }
16
+
17
+ // Substitution content for any {{ }} markers.
18
+ return text.replace(/\{\{([^{}]+?)\}\}/gu, (fullMatch, termWithWhitespace) => {
19
+ const term = termWithWhitespace.trim();
20
+
21
+ if (term in data) {
22
+ return data[term];
23
+ }
24
+
25
+ // Preserve old behavior: If parameter name not provided, don't replace it.
26
+ return fullMatch;
27
+ });
28
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/linter.js ADDED
@@ -0,0 +1,2119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Main Linter Class
3
+ * @author Gyandeep Singh
4
+ * @author aladdin-add
5
+ */
6
+
7
+ "use strict";
8
+
9
+ //------------------------------------------------------------------------------
10
+ // Requirements
11
+ //------------------------------------------------------------------------------
12
+
13
+ const
14
+ path = require("path"),
15
+ eslintScope = require("eslint-scope"),
16
+ evk = require("eslint-visitor-keys"),
17
+ espree = require("espree"),
18
+ merge = require("lodash.merge"),
19
+ pkg = require("../../package.json"),
20
+ astUtils = require("../shared/ast-utils"),
21
+ {
22
+ directivesPattern
23
+ } = require("../shared/directives"),
24
+ {
25
+ Legacy: {
26
+ ConfigOps,
27
+ ConfigValidator,
28
+ environments: BuiltInEnvironments
29
+ }
30
+ } = require("@eslint/eslintrc/universal"),
31
+ Traverser = require("../shared/traverser"),
32
+ { SourceCode } = require("../source-code"),
33
+ CodePathAnalyzer = require("./code-path-analysis/code-path-analyzer"),
34
+ applyDisableDirectives = require("./apply-disable-directives"),
35
+ ConfigCommentParser = require("./config-comment-parser"),
36
+ NodeEventGenerator = require("./node-event-generator"),
37
+ createReportTranslator = require("./report-translator"),
38
+ Rules = require("./rules"),
39
+ createEmitter = require("./safe-emitter"),
40
+ SourceCodeFixer = require("./source-code-fixer"),
41
+ timing = require("./timing"),
42
+ ruleReplacements = require("../../conf/replacements.json");
43
+ const { getRuleFromConfig } = require("../config/flat-config-helpers");
44
+ const { FlatConfigArray } = require("../config/flat-config-array");
45
+ const { RuleValidator } = require("../config/rule-validator");
46
+ const { assertIsRuleOptions, assertIsRuleSeverity } = require("../config/flat-config-schema");
47
+ const { normalizeSeverityToString } = require("../shared/severity");
48
+ const debug = require("debug")("eslint:linter");
49
+ const MAX_AUTOFIX_PASSES = 10;
50
+ const DEFAULT_PARSER_NAME = "espree";
51
+ const DEFAULT_ECMA_VERSION = 5;
52
+ const commentParser = new ConfigCommentParser();
53
+ const DEFAULT_ERROR_LOC = { start: { line: 1, column: 0 }, end: { line: 1, column: 1 } };
54
+ const parserSymbol = Symbol.for("eslint.RuleTester.parser");
55
+
56
+ //------------------------------------------------------------------------------
57
+ // Typedefs
58
+ //------------------------------------------------------------------------------
59
+
60
+ /** @typedef {InstanceType<import("../cli-engine/config-array").ConfigArray>} ConfigArray */
61
+ /** @typedef {InstanceType<import("../cli-engine/config-array").ExtractedConfig>} ExtractedConfig */
62
+ /** @typedef {import("../shared/types").ConfigData} ConfigData */
63
+ /** @typedef {import("../shared/types").Environment} Environment */
64
+ /** @typedef {import("../shared/types").GlobalConf} GlobalConf */
65
+ /** @typedef {import("../shared/types").LintMessage} LintMessage */
66
+ /** @typedef {import("../shared/types").SuppressedLintMessage} SuppressedLintMessage */
67
+ /** @typedef {import("../shared/types").ParserOptions} ParserOptions */
68
+ /** @typedef {import("../shared/types").LanguageOptions} LanguageOptions */
69
+ /** @typedef {import("../shared/types").Processor} Processor */
70
+ /** @typedef {import("../shared/types").Rule} Rule */
71
+
72
+ /* eslint-disable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/4#issuecomment-778805577 */
73
+ /**
74
+ * @template T
75
+ * @typedef {{ [P in keyof T]-?: T[P] }} Required
76
+ */
77
+ /* eslint-enable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/4#issuecomment-778805577 */
78
+
79
+ /**
80
+ * @typedef {Object} DisableDirective
81
+ * @property {("disable"|"enable"|"disable-line"|"disable-next-line")} type Type of directive
82
+ * @property {number} line The line number
83
+ * @property {number} column The column number
84
+ * @property {(string|null)} ruleId The rule ID
85
+ * @property {string} justification The justification of directive
86
+ */
87
+
88
+ /**
89
+ * The private data for `Linter` instance.
90
+ * @typedef {Object} LinterInternalSlots
91
+ * @property {ConfigArray|null} lastConfigArray The `ConfigArray` instance that the last `verify()` call used.
92
+ * @property {SourceCode|null} lastSourceCode The `SourceCode` instance that the last `verify()` call used.
93
+ * @property {SuppressedLintMessage[]} lastSuppressedMessages The `SuppressedLintMessage[]` instance that the last `verify()` call produced.
94
+ * @property {Map<string, Parser>} parserMap The loaded parsers.
95
+ * @property {Rules} ruleMap The loaded rules.
96
+ */
97
+
98
+ /**
99
+ * @typedef {Object} VerifyOptions
100
+ * @property {boolean} [allowInlineConfig] Allow/disallow inline comments' ability
101
+ * to change config once it is set. Defaults to true if not supplied.
102
+ * Useful if you want to validate JS without comments overriding rules.
103
+ * @property {boolean} [disableFixes] if `true` then the linter doesn't make `fix`
104
+ * properties into the lint result.
105
+ * @property {string} [filename] the filename of the source code.
106
+ * @property {boolean | "off" | "warn" | "error"} [reportUnusedDisableDirectives] Adds reported errors for
107
+ * unused `eslint-disable` directives.
108
+ */
109
+
110
+ /**
111
+ * @typedef {Object} ProcessorOptions
112
+ * @property {(filename:string, text:string) => boolean} [filterCodeBlock] the
113
+ * predicate function that selects adopt code blocks.
114
+ * @property {Processor.postprocess} [postprocess] postprocessor for report
115
+ * messages. If provided, this should accept an array of the message lists
116
+ * for each code block returned from the preprocessor, apply a mapping to
117
+ * the messages as appropriate, and return a one-dimensional array of
118
+ * messages.
119
+ * @property {Processor.preprocess} [preprocess] preprocessor for source text.
120
+ * If provided, this should accept a string of source text, and return an
121
+ * array of code blocks to lint.
122
+ */
123
+
124
+ /**
125
+ * @typedef {Object} FixOptions
126
+ * @property {boolean | ((message: LintMessage) => boolean)} [fix] Determines
127
+ * whether fixes should be applied.
128
+ */
129
+
130
+ /**
131
+ * @typedef {Object} InternalOptions
132
+ * @property {string | null} warnInlineConfig The config name what `noInlineConfig` setting came from. If `noInlineConfig` setting didn't exist, this is null. If this is a config name, then the linter warns directive comments.
133
+ * @property {"off" | "warn" | "error"} reportUnusedDisableDirectives (boolean values were normalized)
134
+ */
135
+
136
+ //------------------------------------------------------------------------------
137
+ // Helpers
138
+ //------------------------------------------------------------------------------
139
+
140
+ /**
141
+ * Determines if a given object is Espree.
142
+ * @param {Object} parser The parser to check.
143
+ * @returns {boolean} True if the parser is Espree or false if not.
144
+ */
145
+ function isEspree(parser) {
146
+ return !!(parser === espree || parser[parserSymbol] === espree);
147
+ }
148
+
149
+ /**
150
+ * Ensures that variables representing built-in properties of the Global Object,
151
+ * and any globals declared by special block comments, are present in the global
152
+ * scope.
153
+ * @param {Scope} globalScope The global scope.
154
+ * @param {Object} configGlobals The globals declared in configuration
155
+ * @param {{exportedVariables: Object, enabledGlobals: Object}} commentDirectives Directives from comment configuration
156
+ * @returns {void}
157
+ */
158
+ function addDeclaredGlobals(globalScope, configGlobals, { exportedVariables, enabledGlobals }) {
159
+
160
+ // Define configured global variables.
161
+ for (const id of new Set([...Object.keys(configGlobals), ...Object.keys(enabledGlobals)])) {
162
+
163
+ /*
164
+ * `ConfigOps.normalizeConfigGlobal` will throw an error if a configured global value is invalid. However, these errors would
165
+ * typically be caught when validating a config anyway (validity for inline global comments is checked separately).
166
+ */
167
+ const configValue = configGlobals[id] === void 0 ? void 0 : ConfigOps.normalizeConfigGlobal(configGlobals[id]);
168
+ const commentValue = enabledGlobals[id] && enabledGlobals[id].value;
169
+ const value = commentValue || configValue;
170
+ const sourceComments = enabledGlobals[id] && enabledGlobals[id].comments;
171
+
172
+ if (value === "off") {
173
+ continue;
174
+ }
175
+
176
+ let variable = globalScope.set.get(id);
177
+
178
+ if (!variable) {
179
+ variable = new eslintScope.Variable(id, globalScope);
180
+
181
+ globalScope.variables.push(variable);
182
+ globalScope.set.set(id, variable);
183
+ }
184
+
185
+ variable.eslintImplicitGlobalSetting = configValue;
186
+ variable.eslintExplicitGlobal = sourceComments !== void 0;
187
+ variable.eslintExplicitGlobalComments = sourceComments;
188
+ variable.writeable = (value === "writable");
189
+ }
190
+
191
+ // mark all exported variables as such
192
+ Object.keys(exportedVariables).forEach(name => {
193
+ const variable = globalScope.set.get(name);
194
+
195
+ if (variable) {
196
+ variable.eslintUsed = true;
197
+ variable.eslintExported = true;
198
+ }
199
+ });
200
+
201
+ /*
202
+ * "through" contains all references which definitions cannot be found.
203
+ * Since we augment the global scope using configuration, we need to update
204
+ * references and remove the ones that were added by configuration.
205
+ */
206
+ globalScope.through = globalScope.through.filter(reference => {
207
+ const name = reference.identifier.name;
208
+ const variable = globalScope.set.get(name);
209
+
210
+ if (variable) {
211
+
212
+ /*
213
+ * Links the variable and the reference.
214
+ * And this reference is removed from `Scope#through`.
215
+ */
216
+ reference.resolved = variable;
217
+ variable.references.push(reference);
218
+
219
+ return false;
220
+ }
221
+
222
+ return true;
223
+ });
224
+ }
225
+
226
+ /**
227
+ * creates a missing-rule message.
228
+ * @param {string} ruleId the ruleId to create
229
+ * @returns {string} created error message
230
+ * @private
231
+ */
232
+ function createMissingRuleMessage(ruleId) {
233
+ return Object.prototype.hasOwnProperty.call(ruleReplacements.rules, ruleId)
234
+ ? `Rule '${ruleId}' was removed and replaced by: ${ruleReplacements.rules[ruleId].join(", ")}`
235
+ : `Definition for rule '${ruleId}' was not found.`;
236
+ }
237
+
238
+ /**
239
+ * creates a linting problem
240
+ * @param {Object} options to create linting error
241
+ * @param {string} [options.ruleId] the ruleId to report
242
+ * @param {Object} [options.loc] the loc to report
243
+ * @param {string} [options.message] the error message to report
244
+ * @param {string} [options.severity] the error message to report
245
+ * @returns {LintMessage} created problem, returns a missing-rule problem if only provided ruleId.
246
+ * @private
247
+ */
248
+ function createLintingProblem(options) {
249
+ const {
250
+ ruleId = null,
251
+ loc = DEFAULT_ERROR_LOC,
252
+ message = createMissingRuleMessage(options.ruleId),
253
+ severity = 2
254
+ } = options;
255
+
256
+ return {
257
+ ruleId,
258
+ message,
259
+ line: loc.start.line,
260
+ column: loc.start.column + 1,
261
+ endLine: loc.end.line,
262
+ endColumn: loc.end.column + 1,
263
+ severity,
264
+ nodeType: null
265
+ };
266
+ }
267
+
268
+ /**
269
+ * Creates a collection of disable directives from a comment
270
+ * @param {Object} options to create disable directives
271
+ * @param {("disable"|"enable"|"disable-line"|"disable-next-line")} options.type The type of directive comment
272
+ * @param {token} options.commentToken The Comment token
273
+ * @param {string} options.value The value after the directive in the comment
274
+ * comment specified no specific rules, so it applies to all rules (e.g. `eslint-disable`)
275
+ * @param {string} options.justification The justification of the directive
276
+ * @param {function(string): {create: Function}} options.ruleMapper A map from rule IDs to defined rules
277
+ * @returns {Object} Directives and problems from the comment
278
+ */
279
+ function createDisableDirectives(options) {
280
+ const { commentToken, type, value, justification, ruleMapper } = options;
281
+ const ruleIds = Object.keys(commentParser.parseListConfig(value));
282
+ const directiveRules = ruleIds.length ? ruleIds : [null];
283
+ const result = {
284
+ directives: [], // valid disable directives
285
+ directiveProblems: [] // problems in directives
286
+ };
287
+
288
+ const parentComment = { commentToken, ruleIds };
289
+
290
+ for (const ruleId of directiveRules) {
291
+
292
+ // push to directives, if the rule is defined(including null, e.g. /*eslint enable*/)
293
+ if (ruleId === null || !!ruleMapper(ruleId)) {
294
+ if (type === "disable-next-line") {
295
+ result.directives.push({
296
+ parentComment,
297
+ type,
298
+ line: commentToken.loc.end.line,
299
+ column: commentToken.loc.end.column + 1,
300
+ ruleId,
301
+ justification
302
+ });
303
+ } else {
304
+ result.directives.push({
305
+ parentComment,
306
+ type,
307
+ line: commentToken.loc.start.line,
308
+ column: commentToken.loc.start.column + 1,
309
+ ruleId,
310
+ justification
311
+ });
312
+ }
313
+ } else {
314
+ result.directiveProblems.push(createLintingProblem({ ruleId, loc: commentToken.loc }));
315
+ }
316
+ }
317
+ return result;
318
+ }
319
+
320
+ /**
321
+ * Parses comments in file to extract file-specific config of rules, globals
322
+ * and environments and merges them with global config; also code blocks
323
+ * where reporting is disabled or enabled and merges them with reporting config.
324
+ * @param {SourceCode} sourceCode The SourceCode object to get comments from.
325
+ * @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules
326
+ * @param {string|null} warnInlineConfig If a string then it should warn directive comments as disabled. The string value is the config name what the setting came from.
327
+ * @returns {{configuredRules: Object, enabledGlobals: {value:string,comment:Token}[], exportedVariables: Object, problems: LintMessage[], disableDirectives: DisableDirective[]}}
328
+ * A collection of the directive comments that were found, along with any problems that occurred when parsing
329
+ */
330
+ function getDirectiveComments(sourceCode, ruleMapper, warnInlineConfig) {
331
+ const configuredRules = {};
332
+ const enabledGlobals = Object.create(null);
333
+ const exportedVariables = {};
334
+ const problems = [];
335
+ const disableDirectives = [];
336
+ const validator = new ConfigValidator({
337
+ builtInRules: Rules
338
+ });
339
+
340
+ sourceCode.getInlineConfigNodes().filter(token => token.type !== "Shebang").forEach(comment => {
341
+ const { directivePart, justificationPart } = commentParser.extractDirectiveComment(comment.value);
342
+
343
+ const match = directivesPattern.exec(directivePart);
344
+
345
+ if (!match) {
346
+ return;
347
+ }
348
+ const directiveText = match[1];
349
+ const lineCommentSupported = /^eslint-disable-(next-)?line$/u.test(directiveText);
350
+
351
+ if (comment.type === "Line" && !lineCommentSupported) {
352
+ return;
353
+ }
354
+
355
+ if (warnInlineConfig) {
356
+ const kind = comment.type === "Block" ? `/*${directiveText}*/` : `//${directiveText}`;
357
+
358
+ problems.push(createLintingProblem({
359
+ ruleId: null,
360
+ message: `'${kind}' has no effect because you have 'noInlineConfig' setting in ${warnInlineConfig}.`,
361
+ loc: comment.loc,
362
+ severity: 1
363
+ }));
364
+ return;
365
+ }
366
+
367
+ if (directiveText === "eslint-disable-line" && comment.loc.start.line !== comment.loc.end.line) {
368
+ const message = `${directiveText} comment should not span multiple lines.`;
369
+
370
+ problems.push(createLintingProblem({
371
+ ruleId: null,
372
+ message,
373
+ loc: comment.loc
374
+ }));
375
+ return;
376
+ }
377
+
378
+ const directiveValue = directivePart.slice(match.index + directiveText.length);
379
+
380
+ switch (directiveText) {
381
+ case "eslint-disable":
382
+ case "eslint-enable":
383
+ case "eslint-disable-next-line":
384
+ case "eslint-disable-line": {
385
+ const directiveType = directiveText.slice("eslint-".length);
386
+ const options = { commentToken: comment, type: directiveType, value: directiveValue, justification: justificationPart, ruleMapper };
387
+ const { directives, directiveProblems } = createDisableDirectives(options);
388
+
389
+ disableDirectives.push(...directives);
390
+ problems.push(...directiveProblems);
391
+ break;
392
+ }
393
+
394
+ case "exported":
395
+ Object.assign(exportedVariables, commentParser.parseStringConfig(directiveValue, comment));
396
+ break;
397
+
398
+ case "globals":
399
+ case "global":
400
+ for (const [id, { value }] of Object.entries(commentParser.parseStringConfig(directiveValue, comment))) {
401
+ let normalizedValue;
402
+
403
+ try {
404
+ normalizedValue = ConfigOps.normalizeConfigGlobal(value);
405
+ } catch (err) {
406
+ problems.push(createLintingProblem({
407
+ ruleId: null,
408
+ loc: comment.loc,
409
+ message: err.message
410
+ }));
411
+ continue;
412
+ }
413
+
414
+ if (enabledGlobals[id]) {
415
+ enabledGlobals[id].comments.push(comment);
416
+ enabledGlobals[id].value = normalizedValue;
417
+ } else {
418
+ enabledGlobals[id] = {
419
+ comments: [comment],
420
+ value: normalizedValue
421
+ };
422
+ }
423
+ }
424
+ break;
425
+
426
+ case "eslint": {
427
+ const parseResult = commentParser.parseJsonConfig(directiveValue, comment.loc);
428
+
429
+ if (parseResult.success) {
430
+ Object.keys(parseResult.config).forEach(name => {
431
+ const rule = ruleMapper(name);
432
+ const ruleValue = parseResult.config[name];
433
+
434
+ if (!rule) {
435
+ problems.push(createLintingProblem({ ruleId: name, loc: comment.loc }));
436
+ return;
437
+ }
438
+
439
+ try {
440
+ validator.validateRuleOptions(rule, name, ruleValue);
441
+ } catch (err) {
442
+ problems.push(createLintingProblem({
443
+ ruleId: name,
444
+ message: err.message,
445
+ loc: comment.loc
446
+ }));
447
+
448
+ // do not apply the config, if found invalid options.
449
+ return;
450
+ }
451
+
452
+ configuredRules[name] = ruleValue;
453
+ });
454
+ } else {
455
+ problems.push(parseResult.error);
456
+ }
457
+
458
+ break;
459
+ }
460
+
461
+ // no default
462
+ }
463
+ });
464
+
465
+ return {
466
+ configuredRules,
467
+ enabledGlobals,
468
+ exportedVariables,
469
+ problems,
470
+ disableDirectives
471
+ };
472
+ }
473
+
474
+ /**
475
+ * Parses comments in file to extract disable directives.
476
+ * @param {SourceCode} sourceCode The SourceCode object to get comments from.
477
+ * @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules
478
+ * @returns {{problems: LintMessage[], disableDirectives: DisableDirective[]}}
479
+ * A collection of the directive comments that were found, along with any problems that occurred when parsing
480
+ */
481
+ function getDirectiveCommentsForFlatConfig(sourceCode, ruleMapper) {
482
+ const problems = [];
483
+ const disableDirectives = [];
484
+
485
+ sourceCode.getInlineConfigNodes().filter(token => token.type !== "Shebang").forEach(comment => {
486
+ const { directivePart, justificationPart } = commentParser.extractDirectiveComment(comment.value);
487
+
488
+ const match = directivesPattern.exec(directivePart);
489
+
490
+ if (!match) {
491
+ return;
492
+ }
493
+ const directiveText = match[1];
494
+ const lineCommentSupported = /^eslint-disable-(next-)?line$/u.test(directiveText);
495
+
496
+ if (comment.type === "Line" && !lineCommentSupported) {
497
+ return;
498
+ }
499
+
500
+ if (directiveText === "eslint-disable-line" && comment.loc.start.line !== comment.loc.end.line) {
501
+ const message = `${directiveText} comment should not span multiple lines.`;
502
+
503
+ problems.push(createLintingProblem({
504
+ ruleId: null,
505
+ message,
506
+ loc: comment.loc
507
+ }));
508
+ return;
509
+ }
510
+
511
+ const directiveValue = directivePart.slice(match.index + directiveText.length);
512
+
513
+ switch (directiveText) {
514
+ case "eslint-disable":
515
+ case "eslint-enable":
516
+ case "eslint-disable-next-line":
517
+ case "eslint-disable-line": {
518
+ const directiveType = directiveText.slice("eslint-".length);
519
+ const options = { commentToken: comment, type: directiveType, value: directiveValue, justification: justificationPart, ruleMapper };
520
+ const { directives, directiveProblems } = createDisableDirectives(options);
521
+
522
+ disableDirectives.push(...directives);
523
+ problems.push(...directiveProblems);
524
+ break;
525
+ }
526
+
527
+ // no default
528
+ }
529
+ });
530
+
531
+ return {
532
+ problems,
533
+ disableDirectives
534
+ };
535
+ }
536
+
537
+ /**
538
+ * Normalize ECMAScript version from the initial config
539
+ * @param {Parser} parser The parser which uses this options.
540
+ * @param {number} ecmaVersion ECMAScript version from the initial config
541
+ * @returns {number} normalized ECMAScript version
542
+ */
543
+ function normalizeEcmaVersion(parser, ecmaVersion) {
544
+
545
+ if (isEspree(parser)) {
546
+ if (ecmaVersion === "latest") {
547
+ return espree.latestEcmaVersion;
548
+ }
549
+ }
550
+
551
+ /*
552
+ * Calculate ECMAScript edition number from official year version starting with
553
+ * ES2015, which corresponds with ES6 (or a difference of 2009).
554
+ */
555
+ return ecmaVersion >= 2015 ? ecmaVersion - 2009 : ecmaVersion;
556
+ }
557
+
558
+ /**
559
+ * Normalize ECMAScript version from the initial config into languageOptions (year)
560
+ * format.
561
+ * @param {any} [ecmaVersion] ECMAScript version from the initial config
562
+ * @returns {number} normalized ECMAScript version
563
+ */
564
+ function normalizeEcmaVersionForLanguageOptions(ecmaVersion) {
565
+
566
+ switch (ecmaVersion) {
567
+ case 3:
568
+ return 3;
569
+
570
+ // void 0 = no ecmaVersion specified so use the default
571
+ case 5:
572
+ case void 0:
573
+ return 5;
574
+
575
+ default:
576
+ if (typeof ecmaVersion === "number") {
577
+ return ecmaVersion >= 2015 ? ecmaVersion : ecmaVersion + 2009;
578
+ }
579
+ }
580
+
581
+ /*
582
+ * We default to the latest supported ecmaVersion for everything else.
583
+ * Remember, this is for languageOptions.ecmaVersion, which sets the version
584
+ * that is used for a number of processes inside of ESLint. It's normally
585
+ * safe to assume people want the latest unless otherwise specified.
586
+ */
587
+ return espree.latestEcmaVersion + 2009;
588
+ }
589
+
590
+ const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)(?:\*\/|$)/gsu;
591
+
592
+ /**
593
+ * Checks whether or not there is a comment which has "eslint-env *" in a given text.
594
+ * @param {string} text A source code text to check.
595
+ * @returns {Object|null} A result of parseListConfig() with "eslint-env *" comment.
596
+ */
597
+ function findEslintEnv(text) {
598
+ let match, retv;
599
+
600
+ eslintEnvPattern.lastIndex = 0;
601
+
602
+ while ((match = eslintEnvPattern.exec(text)) !== null) {
603
+ if (match[0].endsWith("*/")) {
604
+ retv = Object.assign(
605
+ retv || {},
606
+ commentParser.parseListConfig(commentParser.extractDirectiveComment(match[1]).directivePart)
607
+ );
608
+ }
609
+ }
610
+
611
+ return retv;
612
+ }
613
+
614
+ /**
615
+ * Convert "/path/to/<text>" to "<text>".
616
+ * `CLIEngine#executeOnText()` method gives "/path/to/<text>" if the filename
617
+ * was omitted because `configArray.extractConfig()` requires an absolute path.
618
+ * But the linter should pass `<text>` to `RuleContext#filename` in that
619
+ * case.
620
+ * Also, code blocks can have their virtual filename. If the parent filename was
621
+ * `<text>`, the virtual filename is `<text>/0_foo.js` or something like (i.e.,
622
+ * it's not an absolute path).
623
+ * @param {string} filename The filename to normalize.
624
+ * @returns {string} The normalized filename.
625
+ */
626
+ function normalizeFilename(filename) {
627
+ const parts = filename.split(path.sep);
628
+ const index = parts.lastIndexOf("<text>");
629
+
630
+ return index === -1 ? filename : parts.slice(index).join(path.sep);
631
+ }
632
+
633
+ /**
634
+ * Normalizes the possible options for `linter.verify` and `linter.verifyAndFix` to a
635
+ * consistent shape.
636
+ * @param {VerifyOptions} providedOptions Options
637
+ * @param {ConfigData} config Config.
638
+ * @returns {Required<VerifyOptions> & InternalOptions} Normalized options
639
+ */
640
+ function normalizeVerifyOptions(providedOptions, config) {
641
+
642
+ const linterOptions = config.linterOptions || config;
643
+
644
+ // .noInlineConfig for eslintrc, .linterOptions.noInlineConfig for flat
645
+ const disableInlineConfig = linterOptions.noInlineConfig === true;
646
+ const ignoreInlineConfig = providedOptions.allowInlineConfig === false;
647
+ const configNameOfNoInlineConfig = config.configNameOfNoInlineConfig
648
+ ? ` (${config.configNameOfNoInlineConfig})`
649
+ : "";
650
+
651
+ let reportUnusedDisableDirectives = providedOptions.reportUnusedDisableDirectives;
652
+
653
+ if (typeof reportUnusedDisableDirectives === "boolean") {
654
+ reportUnusedDisableDirectives = reportUnusedDisableDirectives ? "error" : "off";
655
+ }
656
+ if (typeof reportUnusedDisableDirectives !== "string") {
657
+ if (typeof linterOptions.reportUnusedDisableDirectives === "boolean") {
658
+ reportUnusedDisableDirectives = linterOptions.reportUnusedDisableDirectives ? "warn" : "off";
659
+ } else {
660
+ reportUnusedDisableDirectives = linterOptions.reportUnusedDisableDirectives === void 0 ? "off" : normalizeSeverityToString(linterOptions.reportUnusedDisableDirectives);
661
+ }
662
+ }
663
+
664
+ return {
665
+ filename: normalizeFilename(providedOptions.filename || "<input>"),
666
+ allowInlineConfig: !ignoreInlineConfig,
667
+ warnInlineConfig: disableInlineConfig && !ignoreInlineConfig
668
+ ? `your config${configNameOfNoInlineConfig}`
669
+ : null,
670
+ reportUnusedDisableDirectives,
671
+ disableFixes: Boolean(providedOptions.disableFixes)
672
+ };
673
+ }
674
+
675
+ /**
676
+ * Combines the provided parserOptions with the options from environments
677
+ * @param {Parser} parser The parser which uses this options.
678
+ * @param {ParserOptions} providedOptions The provided 'parserOptions' key in a config
679
+ * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments
680
+ * @returns {ParserOptions} Resulting parser options after merge
681
+ */
682
+ function resolveParserOptions(parser, providedOptions, enabledEnvironments) {
683
+
684
+ const parserOptionsFromEnv = enabledEnvironments
685
+ .filter(env => env.parserOptions)
686
+ .reduce((parserOptions, env) => merge(parserOptions, env.parserOptions), {});
687
+ const mergedParserOptions = merge(parserOptionsFromEnv, providedOptions || {});
688
+ const isModule = mergedParserOptions.sourceType === "module";
689
+
690
+ if (isModule) {
691
+
692
+ /*
693
+ * can't have global return inside of modules
694
+ * TODO: espree validate parserOptions.globalReturn when sourceType is setting to module.(@aladdin-add)
695
+ */
696
+ mergedParserOptions.ecmaFeatures = Object.assign({}, mergedParserOptions.ecmaFeatures, { globalReturn: false });
697
+ }
698
+
699
+ mergedParserOptions.ecmaVersion = normalizeEcmaVersion(parser, mergedParserOptions.ecmaVersion);
700
+
701
+ return mergedParserOptions;
702
+ }
703
+
704
+ /**
705
+ * Converts parserOptions to languageOptions for backwards compatibility with eslintrc.
706
+ * @param {ConfigData} config Config object.
707
+ * @param {Object} config.globals Global variable definitions.
708
+ * @param {Parser} config.parser The parser to use.
709
+ * @param {ParserOptions} config.parserOptions The parserOptions to use.
710
+ * @returns {LanguageOptions} The languageOptions equivalent.
711
+ */
712
+ function createLanguageOptions({ globals: configuredGlobals, parser, parserOptions }) {
713
+
714
+ const {
715
+ ecmaVersion,
716
+ sourceType
717
+ } = parserOptions;
718
+
719
+ return {
720
+ globals: configuredGlobals,
721
+ ecmaVersion: normalizeEcmaVersionForLanguageOptions(ecmaVersion),
722
+ sourceType,
723
+ parser,
724
+ parserOptions
725
+ };
726
+ }
727
+
728
+ /**
729
+ * Combines the provided globals object with the globals from environments
730
+ * @param {Record<string, GlobalConf>} providedGlobals The 'globals' key in a config
731
+ * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments
732
+ * @returns {Record<string, GlobalConf>} The resolved globals object
733
+ */
734
+ function resolveGlobals(providedGlobals, enabledEnvironments) {
735
+ return Object.assign(
736
+ Object.create(null),
737
+ ...enabledEnvironments.filter(env => env.globals).map(env => env.globals),
738
+ providedGlobals
739
+ );
740
+ }
741
+
742
+ /**
743
+ * Strips Unicode BOM from a given text.
744
+ * @param {string} text A text to strip.
745
+ * @returns {string} The stripped text.
746
+ */
747
+ function stripUnicodeBOM(text) {
748
+
749
+ /*
750
+ * Check Unicode BOM.
751
+ * In JavaScript, string data is stored as UTF-16, so BOM is 0xFEFF.
752
+ * http://www.ecma-international.org/ecma-262/6.0/#sec-unicode-format-control-characters
753
+ */
754
+ if (text.charCodeAt(0) === 0xFEFF) {
755
+ return text.slice(1);
756
+ }
757
+ return text;
758
+ }
759
+
760
+ /**
761
+ * Get the options for a rule (not including severity), if any
762
+ * @param {Array|number} ruleConfig rule configuration
763
+ * @returns {Array} of rule options, empty Array if none
764
+ */
765
+ function getRuleOptions(ruleConfig) {
766
+ if (Array.isArray(ruleConfig)) {
767
+ return ruleConfig.slice(1);
768
+ }
769
+ return [];
770
+
771
+ }
772
+
773
+ /**
774
+ * Analyze scope of the given AST.
775
+ * @param {ASTNode} ast The `Program` node to analyze.
776
+ * @param {LanguageOptions} languageOptions The parser options.
777
+ * @param {Record<string, string[]>} visitorKeys The visitor keys.
778
+ * @returns {ScopeManager} The analysis result.
779
+ */
780
+ function analyzeScope(ast, languageOptions, visitorKeys) {
781
+ const parserOptions = languageOptions.parserOptions;
782
+ const ecmaFeatures = parserOptions.ecmaFeatures || {};
783
+ const ecmaVersion = languageOptions.ecmaVersion || DEFAULT_ECMA_VERSION;
784
+
785
+ return eslintScope.analyze(ast, {
786
+ ignoreEval: true,
787
+ nodejsScope: ecmaFeatures.globalReturn,
788
+ impliedStrict: ecmaFeatures.impliedStrict,
789
+ ecmaVersion: typeof ecmaVersion === "number" ? ecmaVersion : 6,
790
+ sourceType: languageOptions.sourceType || "script",
791
+ childVisitorKeys: visitorKeys || evk.KEYS,
792
+ fallback: Traverser.getKeys
793
+ });
794
+ }
795
+
796
+ /**
797
+ * Parses text into an AST. Moved out here because the try-catch prevents
798
+ * optimization of functions, so it's best to keep the try-catch as isolated
799
+ * as possible
800
+ * @param {string} text The text to parse.
801
+ * @param {LanguageOptions} languageOptions Options to pass to the parser
802
+ * @param {string} filePath The path to the file being parsed.
803
+ * @returns {{success: false, error: LintMessage}|{success: true, sourceCode: SourceCode}}
804
+ * An object containing the AST and parser services if parsing was successful, or the error if parsing failed
805
+ * @private
806
+ */
807
+ function parse(text, languageOptions, filePath) {
808
+ const textToParse = stripUnicodeBOM(text).replace(astUtils.shebangPattern, (match, captured) => `//${captured}`);
809
+ const { ecmaVersion, sourceType, parser } = languageOptions;
810
+ const parserOptions = Object.assign(
811
+ { ecmaVersion, sourceType },
812
+ languageOptions.parserOptions,
813
+ {
814
+ loc: true,
815
+ range: true,
816
+ raw: true,
817
+ tokens: true,
818
+ comment: true,
819
+ eslintVisitorKeys: true,
820
+ eslintScopeManager: true,
821
+ filePath
822
+ }
823
+ );
824
+
825
+ /*
826
+ * Check for parsing errors first. If there's a parsing error, nothing
827
+ * else can happen. However, a parsing error does not throw an error
828
+ * from this method - it's just considered a fatal error message, a
829
+ * problem that ESLint identified just like any other.
830
+ */
831
+ try {
832
+ debug("Parsing:", filePath);
833
+ const parseResult = (typeof parser.parseForESLint === "function")
834
+ ? parser.parseForESLint(textToParse, parserOptions)
835
+ : { ast: parser.parse(textToParse, parserOptions) };
836
+
837
+ debug("Parsing successful:", filePath);
838
+ const ast = parseResult.ast;
839
+ const parserServices = parseResult.services || {};
840
+ const visitorKeys = parseResult.visitorKeys || evk.KEYS;
841
+
842
+ debug("Scope analysis:", filePath);
843
+ const scopeManager = parseResult.scopeManager || analyzeScope(ast, languageOptions, visitorKeys);
844
+
845
+ debug("Scope analysis successful:", filePath);
846
+
847
+ return {
848
+ success: true,
849
+
850
+ /*
851
+ * Save all values that `parseForESLint()` returned.
852
+ * If a `SourceCode` object is given as the first parameter instead of source code text,
853
+ * linter skips the parsing process and reuses the source code object.
854
+ * In that case, linter needs all the values that `parseForESLint()` returned.
855
+ */
856
+ sourceCode: new SourceCode({
857
+ text,
858
+ ast,
859
+ parserServices,
860
+ scopeManager,
861
+ visitorKeys
862
+ })
863
+ };
864
+ } catch (ex) {
865
+
866
+ // If the message includes a leading line number, strip it:
867
+ const message = `Parsing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`;
868
+
869
+ debug("%s\n%s", message, ex.stack);
870
+
871
+ return {
872
+ success: false,
873
+ error: {
874
+ ruleId: null,
875
+ fatal: true,
876
+ severity: 2,
877
+ message,
878
+ line: ex.lineNumber,
879
+ column: ex.column,
880
+ nodeType: null
881
+ }
882
+ };
883
+ }
884
+ }
885
+
886
+ /**
887
+ * Runs a rule, and gets its listeners
888
+ * @param {Rule} rule A normalized rule with a `create` method
889
+ * @param {Context} ruleContext The context that should be passed to the rule
890
+ * @throws {any} Any error during the rule's `create`
891
+ * @returns {Object} A map of selector listeners provided by the rule
892
+ */
893
+ function createRuleListeners(rule, ruleContext) {
894
+ try {
895
+ return rule.create(ruleContext);
896
+ } catch (ex) {
897
+ ex.message = `Error while loading rule '${ruleContext.id}': ${ex.message}`;
898
+ throw ex;
899
+ }
900
+ }
901
+
902
+ // methods that exist on SourceCode object
903
+ const DEPRECATED_SOURCECODE_PASSTHROUGHS = {
904
+ getSource: "getText",
905
+ getSourceLines: "getLines",
906
+ getAllComments: "getAllComments",
907
+ getNodeByRangeIndex: "getNodeByRangeIndex",
908
+ getComments: "getComments",
909
+ getCommentsBefore: "getCommentsBefore",
910
+ getCommentsAfter: "getCommentsAfter",
911
+ getCommentsInside: "getCommentsInside",
912
+ getJSDocComment: "getJSDocComment",
913
+ getFirstToken: "getFirstToken",
914
+ getFirstTokens: "getFirstTokens",
915
+ getLastToken: "getLastToken",
916
+ getLastTokens: "getLastTokens",
917
+ getTokenAfter: "getTokenAfter",
918
+ getTokenBefore: "getTokenBefore",
919
+ getTokenByRangeStart: "getTokenByRangeStart",
920
+ getTokens: "getTokens",
921
+ getTokensAfter: "getTokensAfter",
922
+ getTokensBefore: "getTokensBefore",
923
+ getTokensBetween: "getTokensBetween"
924
+ };
925
+
926
+
927
+ const BASE_TRAVERSAL_CONTEXT = Object.freeze(
928
+ Object.keys(DEPRECATED_SOURCECODE_PASSTHROUGHS).reduce(
929
+ (contextInfo, methodName) =>
930
+ Object.assign(contextInfo, {
931
+ [methodName](...args) {
932
+ return this.sourceCode[DEPRECATED_SOURCECODE_PASSTHROUGHS[methodName]](...args);
933
+ }
934
+ }),
935
+ {}
936
+ )
937
+ );
938
+
939
+ /**
940
+ * Runs the given rules on the given SourceCode object
941
+ * @param {SourceCode} sourceCode A SourceCode object for the given text
942
+ * @param {Object} configuredRules The rules configuration
943
+ * @param {function(string): Rule} ruleMapper A mapper function from rule names to rules
944
+ * @param {string | undefined} parserName The name of the parser in the config
945
+ * @param {LanguageOptions} languageOptions The options for parsing the code.
946
+ * @param {Object} settings The settings that were enabled in the config
947
+ * @param {string} filename The reported filename of the code
948
+ * @param {boolean} disableFixes If true, it doesn't make `fix` properties.
949
+ * @param {string | undefined} cwd cwd of the cli
950
+ * @param {string} physicalFilename The full path of the file on disk without any code block information
951
+ * @returns {LintMessage[]} An array of reported problems
952
+ */
953
+ function runRules(sourceCode, configuredRules, ruleMapper, parserName, languageOptions, settings, filename, disableFixes, cwd, physicalFilename) {
954
+ const emitter = createEmitter();
955
+ const nodeQueue = [];
956
+ let currentNode = sourceCode.ast;
957
+
958
+ Traverser.traverse(sourceCode.ast, {
959
+ enter(node, parent) {
960
+ node.parent = parent;
961
+ nodeQueue.push({ isEntering: true, node });
962
+ },
963
+ leave(node) {
964
+ nodeQueue.push({ isEntering: false, node });
965
+ },
966
+ visitorKeys: sourceCode.visitorKeys
967
+ });
968
+
969
+ /*
970
+ * Create a frozen object with the ruleContext properties and methods that are shared by all rules.
971
+ * All rule contexts will inherit from this object. This avoids the performance penalty of copying all the
972
+ * properties once for each rule.
973
+ */
974
+ const sharedTraversalContext = Object.freeze(
975
+ Object.assign(
976
+ Object.create(BASE_TRAVERSAL_CONTEXT),
977
+ {
978
+ getAncestors: () => sourceCode.getAncestors(currentNode),
979
+ getDeclaredVariables: node => sourceCode.getDeclaredVariables(node),
980
+ getCwd: () => cwd,
981
+ cwd,
982
+ getFilename: () => filename,
983
+ filename,
984
+ getPhysicalFilename: () => physicalFilename || filename,
985
+ physicalFilename: physicalFilename || filename,
986
+ getScope: () => sourceCode.getScope(currentNode),
987
+ getSourceCode: () => sourceCode,
988
+ sourceCode,
989
+ markVariableAsUsed: name => sourceCode.markVariableAsUsed(name, currentNode),
990
+ parserOptions: {
991
+ ...languageOptions.parserOptions
992
+ },
993
+ parserPath: parserName,
994
+ languageOptions,
995
+ parserServices: sourceCode.parserServices,
996
+ settings
997
+ }
998
+ )
999
+ );
1000
+
1001
+ const lintingProblems = [];
1002
+
1003
+ Object.keys(configuredRules).forEach(ruleId => {
1004
+ const severity = ConfigOps.getRuleSeverity(configuredRules[ruleId]);
1005
+
1006
+ // not load disabled rules
1007
+ if (severity === 0) {
1008
+ return;
1009
+ }
1010
+
1011
+ const rule = ruleMapper(ruleId);
1012
+
1013
+ if (!rule) {
1014
+ lintingProblems.push(createLintingProblem({ ruleId }));
1015
+ return;
1016
+ }
1017
+
1018
+ const messageIds = rule.meta && rule.meta.messages;
1019
+ let reportTranslator = null;
1020
+ const ruleContext = Object.freeze(
1021
+ Object.assign(
1022
+ Object.create(sharedTraversalContext),
1023
+ {
1024
+ id: ruleId,
1025
+ options: getRuleOptions(configuredRules[ruleId]),
1026
+ report(...args) {
1027
+
1028
+ /*
1029
+ * Create a report translator lazily.
1030
+ * In a vast majority of cases, any given rule reports zero errors on a given
1031
+ * piece of code. Creating a translator lazily avoids the performance cost of
1032
+ * creating a new translator function for each rule that usually doesn't get
1033
+ * called.
1034
+ *
1035
+ * Using lazy report translators improves end-to-end performance by about 3%
1036
+ * with Node 8.4.0.
1037
+ */
1038
+ if (reportTranslator === null) {
1039
+ reportTranslator = createReportTranslator({
1040
+ ruleId,
1041
+ severity,
1042
+ sourceCode,
1043
+ messageIds,
1044
+ disableFixes
1045
+ });
1046
+ }
1047
+ const problem = reportTranslator(...args);
1048
+
1049
+ if (problem.fix && !(rule.meta && rule.meta.fixable)) {
1050
+ throw new Error("Fixable rules must set the `meta.fixable` property to \"code\" or \"whitespace\".");
1051
+ }
1052
+ if (problem.suggestions && !(rule.meta && rule.meta.hasSuggestions === true)) {
1053
+ if (rule.meta && rule.meta.docs && typeof rule.meta.docs.suggestion !== "undefined") {
1054
+
1055
+ // Encourage migration from the former property name.
1056
+ throw new Error("Rules with suggestions must set the `meta.hasSuggestions` property to `true`. `meta.docs.suggestion` is ignored by ESLint.");
1057
+ }
1058
+ throw new Error("Rules with suggestions must set the `meta.hasSuggestions` property to `true`.");
1059
+ }
1060
+ lintingProblems.push(problem);
1061
+ }
1062
+ }
1063
+ )
1064
+ );
1065
+
1066
+ const ruleListeners = timing.enabled ? timing.time(ruleId, createRuleListeners)(rule, ruleContext) : createRuleListeners(rule, ruleContext);
1067
+
1068
+ /**
1069
+ * Include `ruleId` in error logs
1070
+ * @param {Function} ruleListener A rule method that listens for a node.
1071
+ * @returns {Function} ruleListener wrapped in error handler
1072
+ */
1073
+ function addRuleErrorHandler(ruleListener) {
1074
+ return function ruleErrorHandler(...listenerArgs) {
1075
+ try {
1076
+ return ruleListener(...listenerArgs);
1077
+ } catch (e) {
1078
+ e.ruleId = ruleId;
1079
+ throw e;
1080
+ }
1081
+ };
1082
+ }
1083
+
1084
+ if (typeof ruleListeners === "undefined" || ruleListeners === null) {
1085
+ throw new Error(`The create() function for rule '${ruleId}' did not return an object.`);
1086
+ }
1087
+
1088
+ // add all the selectors from the rule as listeners
1089
+ Object.keys(ruleListeners).forEach(selector => {
1090
+ const ruleListener = timing.enabled
1091
+ ? timing.time(ruleId, ruleListeners[selector])
1092
+ : ruleListeners[selector];
1093
+
1094
+ emitter.on(
1095
+ selector,
1096
+ addRuleErrorHandler(ruleListener)
1097
+ );
1098
+ });
1099
+ });
1100
+
1101
+ // only run code path analyzer if the top level node is "Program", skip otherwise
1102
+ const eventGenerator = nodeQueue[0].node.type === "Program"
1103
+ ? new CodePathAnalyzer(new NodeEventGenerator(emitter, { visitorKeys: sourceCode.visitorKeys, fallback: Traverser.getKeys }))
1104
+ : new NodeEventGenerator(emitter, { visitorKeys: sourceCode.visitorKeys, fallback: Traverser.getKeys });
1105
+
1106
+ nodeQueue.forEach(traversalInfo => {
1107
+ currentNode = traversalInfo.node;
1108
+
1109
+ try {
1110
+ if (traversalInfo.isEntering) {
1111
+ eventGenerator.enterNode(currentNode);
1112
+ } else {
1113
+ eventGenerator.leaveNode(currentNode);
1114
+ }
1115
+ } catch (err) {
1116
+ err.currentNode = currentNode;
1117
+ throw err;
1118
+ }
1119
+ });
1120
+
1121
+ return lintingProblems;
1122
+ }
1123
+
1124
+ /**
1125
+ * Ensure the source code to be a string.
1126
+ * @param {string|SourceCode} textOrSourceCode The text or source code object.
1127
+ * @returns {string} The source code text.
1128
+ */
1129
+ function ensureText(textOrSourceCode) {
1130
+ if (typeof textOrSourceCode === "object") {
1131
+ const { hasBOM, text } = textOrSourceCode;
1132
+ const bom = hasBOM ? "\uFEFF" : "";
1133
+
1134
+ return bom + text;
1135
+ }
1136
+
1137
+ return String(textOrSourceCode);
1138
+ }
1139
+
1140
+ /**
1141
+ * Get an environment.
1142
+ * @param {LinterInternalSlots} slots The internal slots of Linter.
1143
+ * @param {string} envId The environment ID to get.
1144
+ * @returns {Environment|null} The environment.
1145
+ */
1146
+ function getEnv(slots, envId) {
1147
+ return (
1148
+ (slots.lastConfigArray && slots.lastConfigArray.pluginEnvironments.get(envId)) ||
1149
+ BuiltInEnvironments.get(envId) ||
1150
+ null
1151
+ );
1152
+ }
1153
+
1154
+ /**
1155
+ * Get a rule.
1156
+ * @param {LinterInternalSlots} slots The internal slots of Linter.
1157
+ * @param {string} ruleId The rule ID to get.
1158
+ * @returns {Rule|null} The rule.
1159
+ */
1160
+ function getRule(slots, ruleId) {
1161
+ return (
1162
+ (slots.lastConfigArray && slots.lastConfigArray.pluginRules.get(ruleId)) ||
1163
+ slots.ruleMap.get(ruleId)
1164
+ );
1165
+ }
1166
+
1167
+ /**
1168
+ * Normalize the value of the cwd
1169
+ * @param {string | undefined} cwd raw value of the cwd, path to a directory that should be considered as the current working directory, can be undefined.
1170
+ * @returns {string | undefined} normalized cwd
1171
+ */
1172
+ function normalizeCwd(cwd) {
1173
+ if (cwd) {
1174
+ return cwd;
1175
+ }
1176
+ if (typeof process === "object") {
1177
+ return process.cwd();
1178
+ }
1179
+
1180
+ // It's more explicit to assign the undefined
1181
+ // eslint-disable-next-line no-undefined -- Consistently returning a value
1182
+ return undefined;
1183
+ }
1184
+
1185
+ /**
1186
+ * The map to store private data.
1187
+ * @type {WeakMap<Linter, LinterInternalSlots>}
1188
+ */
1189
+ const internalSlotsMap = new WeakMap();
1190
+
1191
+ /**
1192
+ * Throws an error when the given linter is in flat config mode.
1193
+ * @param {Linter} linter The linter to check.
1194
+ * @returns {void}
1195
+ * @throws {Error} If the linter is in flat config mode.
1196
+ */
1197
+ function assertEslintrcConfig(linter) {
1198
+ const { configType } = internalSlotsMap.get(linter);
1199
+
1200
+ if (configType === "flat") {
1201
+ throw new Error("This method cannot be used with flat config. Add your entries directly into the config array.");
1202
+ }
1203
+ }
1204
+
1205
+
1206
+ //------------------------------------------------------------------------------
1207
+ // Public Interface
1208
+ //------------------------------------------------------------------------------
1209
+
1210
+ /**
1211
+ * Object that is responsible for verifying JavaScript text
1212
+ * @name Linter
1213
+ */
1214
+ class Linter {
1215
+
1216
+ /**
1217
+ * Initialize the Linter.
1218
+ * @param {Object} [config] the config object
1219
+ * @param {string} [config.cwd] path to a directory that should be considered as the current working directory, can be undefined.
1220
+ * @param {"flat"|"eslintrc"} [config.configType="eslintrc"] the type of config used.
1221
+ */
1222
+ constructor({ cwd, configType } = {}) {
1223
+ internalSlotsMap.set(this, {
1224
+ cwd: normalizeCwd(cwd),
1225
+ lastConfigArray: null,
1226
+ lastSourceCode: null,
1227
+ lastSuppressedMessages: [],
1228
+ configType, // TODO: Remove after flat config conversion
1229
+ parserMap: new Map([["espree", espree]]),
1230
+ ruleMap: new Rules()
1231
+ });
1232
+
1233
+ this.version = pkg.version;
1234
+ }
1235
+
1236
+ /**
1237
+ * Getter for package version.
1238
+ * @static
1239
+ * @returns {string} The version from package.json.
1240
+ */
1241
+ static get version() {
1242
+ return pkg.version;
1243
+ }
1244
+
1245
+ /**
1246
+ * Same as linter.verify, except without support for processors.
1247
+ * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
1248
+ * @param {ConfigData} providedConfig An ESLintConfig instance to configure everything.
1249
+ * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked.
1250
+ * @throws {Error} If during rule execution.
1251
+ * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages.
1252
+ */
1253
+ _verifyWithoutProcessors(textOrSourceCode, providedConfig, providedOptions) {
1254
+ const slots = internalSlotsMap.get(this);
1255
+ const config = providedConfig || {};
1256
+ const options = normalizeVerifyOptions(providedOptions, config);
1257
+ let text;
1258
+
1259
+ // evaluate arguments
1260
+ if (typeof textOrSourceCode === "string") {
1261
+ slots.lastSourceCode = null;
1262
+ text = textOrSourceCode;
1263
+ } else {
1264
+ slots.lastSourceCode = textOrSourceCode;
1265
+ text = textOrSourceCode.text;
1266
+ }
1267
+
1268
+ // Resolve parser.
1269
+ let parserName = DEFAULT_PARSER_NAME;
1270
+ let parser = espree;
1271
+
1272
+ if (typeof config.parser === "object" && config.parser !== null) {
1273
+ parserName = config.parser.filePath;
1274
+ parser = config.parser.definition;
1275
+ } else if (typeof config.parser === "string") {
1276
+ if (!slots.parserMap.has(config.parser)) {
1277
+ return [{
1278
+ ruleId: null,
1279
+ fatal: true,
1280
+ severity: 2,
1281
+ message: `Configured parser '${config.parser}' was not found.`,
1282
+ line: 0,
1283
+ column: 0,
1284
+ nodeType: null
1285
+ }];
1286
+ }
1287
+ parserName = config.parser;
1288
+ parser = slots.parserMap.get(config.parser);
1289
+ }
1290
+
1291
+ // search and apply "eslint-env *".
1292
+ const envInFile = options.allowInlineConfig && !options.warnInlineConfig
1293
+ ? findEslintEnv(text)
1294
+ : {};
1295
+ const resolvedEnvConfig = Object.assign({ builtin: true }, config.env, envInFile);
1296
+ const enabledEnvs = Object.keys(resolvedEnvConfig)
1297
+ .filter(envName => resolvedEnvConfig[envName])
1298
+ .map(envName => getEnv(slots, envName))
1299
+ .filter(env => env);
1300
+
1301
+ const parserOptions = resolveParserOptions(parser, config.parserOptions || {}, enabledEnvs);
1302
+ const configuredGlobals = resolveGlobals(config.globals || {}, enabledEnvs);
1303
+ const settings = config.settings || {};
1304
+ const languageOptions = createLanguageOptions({
1305
+ globals: config.globals,
1306
+ parser,
1307
+ parserOptions
1308
+ });
1309
+
1310
+ if (!slots.lastSourceCode) {
1311
+ const parseResult = parse(
1312
+ text,
1313
+ languageOptions,
1314
+ options.filename
1315
+ );
1316
+
1317
+ if (!parseResult.success) {
1318
+ return [parseResult.error];
1319
+ }
1320
+
1321
+ slots.lastSourceCode = parseResult.sourceCode;
1322
+ } else {
1323
+
1324
+ /*
1325
+ * If the given source code object as the first argument does not have scopeManager, analyze the scope.
1326
+ * This is for backward compatibility (SourceCode is frozen so it cannot rebind).
1327
+ */
1328
+ if (!slots.lastSourceCode.scopeManager) {
1329
+ slots.lastSourceCode = new SourceCode({
1330
+ text: slots.lastSourceCode.text,
1331
+ ast: slots.lastSourceCode.ast,
1332
+ parserServices: slots.lastSourceCode.parserServices,
1333
+ visitorKeys: slots.lastSourceCode.visitorKeys,
1334
+ scopeManager: analyzeScope(slots.lastSourceCode.ast, languageOptions)
1335
+ });
1336
+ }
1337
+ }
1338
+
1339
+ const sourceCode = slots.lastSourceCode;
1340
+ const commentDirectives = options.allowInlineConfig
1341
+ ? getDirectiveComments(sourceCode, ruleId => getRule(slots, ruleId), options.warnInlineConfig)
1342
+ : { configuredRules: {}, enabledGlobals: {}, exportedVariables: {}, problems: [], disableDirectives: [] };
1343
+
1344
+ // augment global scope with declared global variables
1345
+ addDeclaredGlobals(
1346
+ sourceCode.scopeManager.scopes[0],
1347
+ configuredGlobals,
1348
+ { exportedVariables: commentDirectives.exportedVariables, enabledGlobals: commentDirectives.enabledGlobals }
1349
+ );
1350
+
1351
+ const configuredRules = Object.assign({}, config.rules, commentDirectives.configuredRules);
1352
+ let lintingProblems;
1353
+
1354
+ try {
1355
+ lintingProblems = runRules(
1356
+ sourceCode,
1357
+ configuredRules,
1358
+ ruleId => getRule(slots, ruleId),
1359
+ parserName,
1360
+ languageOptions,
1361
+ settings,
1362
+ options.filename,
1363
+ options.disableFixes,
1364
+ slots.cwd,
1365
+ providedOptions.physicalFilename
1366
+ );
1367
+ } catch (err) {
1368
+ err.message += `\nOccurred while linting ${options.filename}`;
1369
+ debug("An error occurred while traversing");
1370
+ debug("Filename:", options.filename);
1371
+ if (err.currentNode) {
1372
+ const { line } = err.currentNode.loc.start;
1373
+
1374
+ debug("Line:", line);
1375
+ err.message += `:${line}`;
1376
+ }
1377
+ debug("Parser Options:", parserOptions);
1378
+ debug("Parser Path:", parserName);
1379
+ debug("Settings:", settings);
1380
+
1381
+ if (err.ruleId) {
1382
+ err.message += `\nRule: "${err.ruleId}"`;
1383
+ }
1384
+
1385
+ throw err;
1386
+ }
1387
+
1388
+ return applyDisableDirectives({
1389
+ directives: commentDirectives.disableDirectives,
1390
+ disableFixes: options.disableFixes,
1391
+ problems: lintingProblems
1392
+ .concat(commentDirectives.problems)
1393
+ .sort((problemA, problemB) => problemA.line - problemB.line || problemA.column - problemB.column),
1394
+ reportUnusedDisableDirectives: options.reportUnusedDisableDirectives
1395
+ });
1396
+ }
1397
+
1398
+ /**
1399
+ * Verifies the text against the rules specified by the second argument.
1400
+ * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
1401
+ * @param {ConfigData|ConfigArray} config An ESLintConfig instance to configure everything.
1402
+ * @param {(string|(VerifyOptions&ProcessorOptions))} [filenameOrOptions] The optional filename of the file being checked.
1403
+ * If this is not set, the filename will default to '<input>' in the rule context. If
1404
+ * an object, then it has "filename", "allowInlineConfig", and some properties.
1405
+ * @returns {LintMessage[]} The results as an array of messages or an empty array if no messages.
1406
+ */
1407
+ verify(textOrSourceCode, config, filenameOrOptions) {
1408
+ debug("Verify");
1409
+
1410
+ const { configType, cwd } = internalSlotsMap.get(this);
1411
+
1412
+ const options = typeof filenameOrOptions === "string"
1413
+ ? { filename: filenameOrOptions }
1414
+ : filenameOrOptions || {};
1415
+
1416
+ if (config) {
1417
+ if (configType === "flat") {
1418
+
1419
+ /*
1420
+ * Because of how Webpack packages up the files, we can't
1421
+ * compare directly to `FlatConfigArray` using `instanceof`
1422
+ * because it's not the same `FlatConfigArray` as in the tests.
1423
+ * So, we work around it by assuming an array is, in fact, a
1424
+ * `FlatConfigArray` if it has a `getConfig()` method.
1425
+ */
1426
+ let configArray = config;
1427
+
1428
+ if (!Array.isArray(config) || typeof config.getConfig !== "function") {
1429
+ configArray = new FlatConfigArray(config, { basePath: cwd });
1430
+ configArray.normalizeSync();
1431
+ }
1432
+
1433
+ return this._distinguishSuppressedMessages(this._verifyWithFlatConfigArray(textOrSourceCode, configArray, options, true));
1434
+ }
1435
+
1436
+ if (typeof config.extractConfig === "function") {
1437
+ return this._distinguishSuppressedMessages(this._verifyWithConfigArray(textOrSourceCode, config, options));
1438
+ }
1439
+ }
1440
+
1441
+ /*
1442
+ * If we get to here, it means `config` is just an object rather
1443
+ * than a config array so we can go right into linting.
1444
+ */
1445
+
1446
+ /*
1447
+ * `Linter` doesn't support `overrides` property in configuration.
1448
+ * So we cannot apply multiple processors.
1449
+ */
1450
+ if (options.preprocess || options.postprocess) {
1451
+ return this._distinguishSuppressedMessages(this._verifyWithProcessor(textOrSourceCode, config, options));
1452
+ }
1453
+ return this._distinguishSuppressedMessages(this._verifyWithoutProcessors(textOrSourceCode, config, options));
1454
+ }
1455
+
1456
+ /**
1457
+ * Verify with a processor.
1458
+ * @param {string|SourceCode} textOrSourceCode The source code.
1459
+ * @param {FlatConfig} config The config array.
1460
+ * @param {VerifyOptions&ProcessorOptions} options The options.
1461
+ * @param {FlatConfigArray} [configForRecursive] The `ConfigArray` object to apply multiple processors recursively.
1462
+ * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems.
1463
+ */
1464
+ _verifyWithFlatConfigArrayAndProcessor(textOrSourceCode, config, options, configForRecursive) {
1465
+ const filename = options.filename || "<input>";
1466
+ const filenameToExpose = normalizeFilename(filename);
1467
+ const physicalFilename = options.physicalFilename || filenameToExpose;
1468
+ const text = ensureText(textOrSourceCode);
1469
+ const preprocess = options.preprocess || (rawText => [rawText]);
1470
+ const postprocess = options.postprocess || (messagesList => messagesList.flat());
1471
+ const filterCodeBlock =
1472
+ options.filterCodeBlock ||
1473
+ (blockFilename => blockFilename.endsWith(".js"));
1474
+ const originalExtname = path.extname(filename);
1475
+
1476
+ let blocks;
1477
+
1478
+ try {
1479
+ blocks = preprocess(text, filenameToExpose);
1480
+ } catch (ex) {
1481
+
1482
+ // If the message includes a leading line number, strip it:
1483
+ const message = `Preprocessing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`;
1484
+
1485
+ debug("%s\n%s", message, ex.stack);
1486
+
1487
+ return [
1488
+ {
1489
+ ruleId: null,
1490
+ fatal: true,
1491
+ severity: 2,
1492
+ message,
1493
+ line: ex.lineNumber,
1494
+ column: ex.column,
1495
+ nodeType: null
1496
+ }
1497
+ ];
1498
+ }
1499
+
1500
+ const messageLists = blocks.map((block, i) => {
1501
+ debug("A code block was found: %o", block.filename || "(unnamed)");
1502
+
1503
+ // Keep the legacy behavior.
1504
+ if (typeof block === "string") {
1505
+ return this._verifyWithFlatConfigArrayAndWithoutProcessors(block, config, options);
1506
+ }
1507
+
1508
+ const blockText = block.text;
1509
+ const blockName = path.join(filename, `${i}_${block.filename}`);
1510
+
1511
+ // Skip this block if filtered.
1512
+ if (!filterCodeBlock(blockName, blockText)) {
1513
+ debug("This code block was skipped.");
1514
+ return [];
1515
+ }
1516
+
1517
+ // Resolve configuration again if the file content or extension was changed.
1518
+ if (configForRecursive && (text !== blockText || path.extname(blockName) !== originalExtname)) {
1519
+ debug("Resolving configuration again because the file content or extension was changed.");
1520
+ return this._verifyWithFlatConfigArray(
1521
+ blockText,
1522
+ configForRecursive,
1523
+ { ...options, filename: blockName, physicalFilename }
1524
+ );
1525
+ }
1526
+
1527
+ // Does lint.
1528
+ return this._verifyWithFlatConfigArrayAndWithoutProcessors(
1529
+ blockText,
1530
+ config,
1531
+ { ...options, filename: blockName, physicalFilename }
1532
+ );
1533
+ });
1534
+
1535
+ return postprocess(messageLists, filenameToExpose);
1536
+ }
1537
+
1538
+ /**
1539
+ * Same as linter.verify, except without support for processors.
1540
+ * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
1541
+ * @param {FlatConfig} providedConfig An ESLintConfig instance to configure everything.
1542
+ * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked.
1543
+ * @throws {Error} If during rule execution.
1544
+ * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages.
1545
+ */
1546
+ _verifyWithFlatConfigArrayAndWithoutProcessors(textOrSourceCode, providedConfig, providedOptions) {
1547
+ const slots = internalSlotsMap.get(this);
1548
+ const config = providedConfig || {};
1549
+ const options = normalizeVerifyOptions(providedOptions, config);
1550
+ let text;
1551
+
1552
+ // evaluate arguments
1553
+ if (typeof textOrSourceCode === "string") {
1554
+ slots.lastSourceCode = null;
1555
+ text = textOrSourceCode;
1556
+ } else {
1557
+ slots.lastSourceCode = textOrSourceCode;
1558
+ text = textOrSourceCode.text;
1559
+ }
1560
+
1561
+ const languageOptions = config.languageOptions;
1562
+
1563
+ languageOptions.ecmaVersion = normalizeEcmaVersionForLanguageOptions(
1564
+ languageOptions.ecmaVersion
1565
+ );
1566
+
1567
+ // double check that there is a parser to avoid mysterious error messages
1568
+ if (!languageOptions.parser) {
1569
+ throw new TypeError(`No parser specified for ${options.filename}`);
1570
+ }
1571
+
1572
+ // Espree expects this information to be passed in
1573
+ if (isEspree(languageOptions.parser)) {
1574
+ const parserOptions = languageOptions.parserOptions;
1575
+
1576
+ if (languageOptions.sourceType) {
1577
+
1578
+ parserOptions.sourceType = languageOptions.sourceType;
1579
+
1580
+ if (
1581
+ parserOptions.sourceType === "module" &&
1582
+ parserOptions.ecmaFeatures &&
1583
+ parserOptions.ecmaFeatures.globalReturn
1584
+ ) {
1585
+ parserOptions.ecmaFeatures.globalReturn = false;
1586
+ }
1587
+ }
1588
+ }
1589
+
1590
+ const settings = config.settings || {};
1591
+
1592
+ if (!slots.lastSourceCode) {
1593
+ const parseResult = parse(
1594
+ text,
1595
+ languageOptions,
1596
+ options.filename
1597
+ );
1598
+
1599
+ if (!parseResult.success) {
1600
+ return [parseResult.error];
1601
+ }
1602
+
1603
+ slots.lastSourceCode = parseResult.sourceCode;
1604
+ } else {
1605
+
1606
+ /*
1607
+ * If the given source code object as the first argument does not have scopeManager, analyze the scope.
1608
+ * This is for backward compatibility (SourceCode is frozen so it cannot rebind).
1609
+ */
1610
+ if (!slots.lastSourceCode.scopeManager) {
1611
+ slots.lastSourceCode = new SourceCode({
1612
+ text: slots.lastSourceCode.text,
1613
+ ast: slots.lastSourceCode.ast,
1614
+ parserServices: slots.lastSourceCode.parserServices,
1615
+ visitorKeys: slots.lastSourceCode.visitorKeys,
1616
+ scopeManager: analyzeScope(slots.lastSourceCode.ast, languageOptions)
1617
+ });
1618
+ }
1619
+ }
1620
+
1621
+ const sourceCode = slots.lastSourceCode;
1622
+
1623
+ /*
1624
+ * Make adjustments based on the language options. For JavaScript,
1625
+ * this is primarily about adding variables into the global scope
1626
+ * to account for ecmaVersion and configured globals.
1627
+ */
1628
+ sourceCode.applyLanguageOptions(languageOptions);
1629
+
1630
+ const mergedInlineConfig = {
1631
+ rules: {}
1632
+ };
1633
+ const inlineConfigProblems = [];
1634
+
1635
+ /*
1636
+ * Inline config can be either enabled or disabled. If disabled, it's possible
1637
+ * to detect the inline config and emit a warning (though this is not required).
1638
+ * So we first check to see if inline config is allowed at all, and if so, we
1639
+ * need to check if it's a warning or not.
1640
+ */
1641
+ if (options.allowInlineConfig) {
1642
+
1643
+ // if inline config should warn then add the warnings
1644
+ if (options.warnInlineConfig) {
1645
+ sourceCode.getInlineConfigNodes().forEach(node => {
1646
+ inlineConfigProblems.push(createLintingProblem({
1647
+ ruleId: null,
1648
+ message: `'${sourceCode.text.slice(node.range[0], node.range[1])}' has no effect because you have 'noInlineConfig' setting in ${options.warnInlineConfig}.`,
1649
+ loc: node.loc,
1650
+ severity: 1
1651
+ }));
1652
+
1653
+ });
1654
+ } else {
1655
+ const inlineConfigResult = sourceCode.applyInlineConfig();
1656
+
1657
+ inlineConfigProblems.push(
1658
+ ...inlineConfigResult.problems
1659
+ .map(createLintingProblem)
1660
+ .map(problem => {
1661
+ problem.fatal = true;
1662
+ return problem;
1663
+ })
1664
+ );
1665
+
1666
+ // next we need to verify information about the specified rules
1667
+ const ruleValidator = new RuleValidator();
1668
+
1669
+ for (const { config: inlineConfig, node } of inlineConfigResult.configs) {
1670
+
1671
+ Object.keys(inlineConfig.rules).forEach(ruleId => {
1672
+ const rule = getRuleFromConfig(ruleId, config);
1673
+ const ruleValue = inlineConfig.rules[ruleId];
1674
+
1675
+ if (!rule) {
1676
+ inlineConfigProblems.push(createLintingProblem({ ruleId, loc: node.loc }));
1677
+ return;
1678
+ }
1679
+
1680
+ try {
1681
+
1682
+ const ruleOptions = Array.isArray(ruleValue) ? ruleValue : [ruleValue];
1683
+
1684
+ assertIsRuleOptions(ruleId, ruleValue);
1685
+ assertIsRuleSeverity(ruleId, ruleOptions[0]);
1686
+
1687
+ ruleValidator.validate({
1688
+ plugins: config.plugins,
1689
+ rules: {
1690
+ [ruleId]: ruleOptions
1691
+ }
1692
+ });
1693
+ mergedInlineConfig.rules[ruleId] = ruleValue;
1694
+ } catch (err) {
1695
+
1696
+ let baseMessage = err.message.slice(
1697
+ err.message.startsWith("Key \"rules\":")
1698
+ ? err.message.indexOf(":", 12) + 1
1699
+ : err.message.indexOf(":") + 1
1700
+ ).trim();
1701
+
1702
+ if (err.messageTemplate) {
1703
+ baseMessage += ` You passed "${ruleValue}".`;
1704
+ }
1705
+
1706
+ inlineConfigProblems.push(createLintingProblem({
1707
+ ruleId,
1708
+ message: `Inline configuration for rule "${ruleId}" is invalid:\n\t${baseMessage}\n`,
1709
+ loc: node.loc
1710
+ }));
1711
+ }
1712
+ });
1713
+ }
1714
+ }
1715
+ }
1716
+
1717
+ const commentDirectives = options.allowInlineConfig && !options.warnInlineConfig
1718
+ ? getDirectiveCommentsForFlatConfig(
1719
+ sourceCode,
1720
+ ruleId => getRuleFromConfig(ruleId, config)
1721
+ )
1722
+ : { problems: [], disableDirectives: [] };
1723
+
1724
+ const configuredRules = Object.assign({}, config.rules, mergedInlineConfig.rules);
1725
+ let lintingProblems;
1726
+
1727
+ sourceCode.finalize();
1728
+
1729
+ try {
1730
+ lintingProblems = runRules(
1731
+ sourceCode,
1732
+ configuredRules,
1733
+ ruleId => getRuleFromConfig(ruleId, config),
1734
+ void 0,
1735
+ languageOptions,
1736
+ settings,
1737
+ options.filename,
1738
+ options.disableFixes,
1739
+ slots.cwd,
1740
+ providedOptions.physicalFilename
1741
+ );
1742
+ } catch (err) {
1743
+ err.message += `\nOccurred while linting ${options.filename}`;
1744
+ debug("An error occurred while traversing");
1745
+ debug("Filename:", options.filename);
1746
+ if (err.currentNode) {
1747
+ const { line } = err.currentNode.loc.start;
1748
+
1749
+ debug("Line:", line);
1750
+ err.message += `:${line}`;
1751
+ }
1752
+ debug("Parser Options:", languageOptions.parserOptions);
1753
+
1754
+ // debug("Parser Path:", parserName);
1755
+ debug("Settings:", settings);
1756
+
1757
+ if (err.ruleId) {
1758
+ err.message += `\nRule: "${err.ruleId}"`;
1759
+ }
1760
+
1761
+ throw err;
1762
+ }
1763
+
1764
+ return applyDisableDirectives({
1765
+ directives: commentDirectives.disableDirectives,
1766
+ disableFixes: options.disableFixes,
1767
+ problems: lintingProblems
1768
+ .concat(commentDirectives.problems)
1769
+ .concat(inlineConfigProblems)
1770
+ .sort((problemA, problemB) => problemA.line - problemB.line || problemA.column - problemB.column),
1771
+ reportUnusedDisableDirectives: options.reportUnusedDisableDirectives
1772
+ });
1773
+ }
1774
+
1775
+ /**
1776
+ * Verify a given code with `ConfigArray`.
1777
+ * @param {string|SourceCode} textOrSourceCode The source code.
1778
+ * @param {ConfigArray} configArray The config array.
1779
+ * @param {VerifyOptions&ProcessorOptions} options The options.
1780
+ * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems.
1781
+ */
1782
+ _verifyWithConfigArray(textOrSourceCode, configArray, options) {
1783
+ debug("With ConfigArray: %s", options.filename);
1784
+
1785
+ // Store the config array in order to get plugin envs and rules later.
1786
+ internalSlotsMap.get(this).lastConfigArray = configArray;
1787
+
1788
+ // Extract the final config for this file.
1789
+ const config = configArray.extractConfig(options.filename);
1790
+ const processor =
1791
+ config.processor &&
1792
+ configArray.pluginProcessors.get(config.processor);
1793
+
1794
+ // Verify.
1795
+ if (processor) {
1796
+ debug("Apply the processor: %o", config.processor);
1797
+ const { preprocess, postprocess, supportsAutofix } = processor;
1798
+ const disableFixes = options.disableFixes || !supportsAutofix;
1799
+
1800
+ return this._verifyWithProcessor(
1801
+ textOrSourceCode,
1802
+ config,
1803
+ { ...options, disableFixes, postprocess, preprocess },
1804
+ configArray
1805
+ );
1806
+ }
1807
+ return this._verifyWithoutProcessors(textOrSourceCode, config, options);
1808
+ }
1809
+
1810
+ /**
1811
+ * Verify a given code with a flat config.
1812
+ * @param {string|SourceCode} textOrSourceCode The source code.
1813
+ * @param {FlatConfigArray} configArray The config array.
1814
+ * @param {VerifyOptions&ProcessorOptions} options The options.
1815
+ * @param {boolean} [firstCall=false] Indicates if this is being called directly
1816
+ * from verify(). (TODO: Remove once eslintrc is removed.)
1817
+ * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems.
1818
+ */
1819
+ _verifyWithFlatConfigArray(textOrSourceCode, configArray, options, firstCall = false) {
1820
+ debug("With flat config: %s", options.filename);
1821
+
1822
+ // we need a filename to match configs against
1823
+ const filename = options.filename || "__placeholder__.js";
1824
+
1825
+ // Store the config array in order to get plugin envs and rules later.
1826
+ internalSlotsMap.get(this).lastConfigArray = configArray;
1827
+ const config = configArray.getConfig(filename);
1828
+
1829
+ if (!config) {
1830
+ return [
1831
+ {
1832
+ ruleId: null,
1833
+ severity: 1,
1834
+ message: `No matching configuration found for ${filename}.`,
1835
+ line: 0,
1836
+ column: 0,
1837
+ nodeType: null
1838
+ }
1839
+ ];
1840
+ }
1841
+
1842
+ // Verify.
1843
+ if (config.processor) {
1844
+ debug("Apply the processor: %o", config.processor);
1845
+ const { preprocess, postprocess, supportsAutofix } = config.processor;
1846
+ const disableFixes = options.disableFixes || !supportsAutofix;
1847
+
1848
+ return this._verifyWithFlatConfigArrayAndProcessor(
1849
+ textOrSourceCode,
1850
+ config,
1851
+ { ...options, filename, disableFixes, postprocess, preprocess },
1852
+ configArray
1853
+ );
1854
+ }
1855
+
1856
+ // check for options-based processing
1857
+ if (firstCall && (options.preprocess || options.postprocess)) {
1858
+ return this._verifyWithFlatConfigArrayAndProcessor(textOrSourceCode, config, options);
1859
+ }
1860
+
1861
+ return this._verifyWithFlatConfigArrayAndWithoutProcessors(textOrSourceCode, config, options);
1862
+ }
1863
+
1864
+ /**
1865
+ * Verify with a processor.
1866
+ * @param {string|SourceCode} textOrSourceCode The source code.
1867
+ * @param {ConfigData|ExtractedConfig} config The config array.
1868
+ * @param {VerifyOptions&ProcessorOptions} options The options.
1869
+ * @param {ConfigArray} [configForRecursive] The `ConfigArray` object to apply multiple processors recursively.
1870
+ * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems.
1871
+ */
1872
+ _verifyWithProcessor(textOrSourceCode, config, options, configForRecursive) {
1873
+ const filename = options.filename || "<input>";
1874
+ const filenameToExpose = normalizeFilename(filename);
1875
+ const physicalFilename = options.physicalFilename || filenameToExpose;
1876
+ const text = ensureText(textOrSourceCode);
1877
+ const preprocess = options.preprocess || (rawText => [rawText]);
1878
+ const postprocess = options.postprocess || (messagesList => messagesList.flat());
1879
+ const filterCodeBlock =
1880
+ options.filterCodeBlock ||
1881
+ (blockFilename => blockFilename.endsWith(".js"));
1882
+ const originalExtname = path.extname(filename);
1883
+
1884
+ let blocks;
1885
+
1886
+ try {
1887
+ blocks = preprocess(text, filenameToExpose);
1888
+ } catch (ex) {
1889
+
1890
+ // If the message includes a leading line number, strip it:
1891
+ const message = `Preprocessing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`;
1892
+
1893
+ debug("%s\n%s", message, ex.stack);
1894
+
1895
+ return [
1896
+ {
1897
+ ruleId: null,
1898
+ fatal: true,
1899
+ severity: 2,
1900
+ message,
1901
+ line: ex.lineNumber,
1902
+ column: ex.column,
1903
+ nodeType: null
1904
+ }
1905
+ ];
1906
+ }
1907
+
1908
+ const messageLists = blocks.map((block, i) => {
1909
+ debug("A code block was found: %o", block.filename || "(unnamed)");
1910
+
1911
+ // Keep the legacy behavior.
1912
+ if (typeof block === "string") {
1913
+ return this._verifyWithoutProcessors(block, config, options);
1914
+ }
1915
+
1916
+ const blockText = block.text;
1917
+ const blockName = path.join(filename, `${i}_${block.filename}`);
1918
+
1919
+ // Skip this block if filtered.
1920
+ if (!filterCodeBlock(blockName, blockText)) {
1921
+ debug("This code block was skipped.");
1922
+ return [];
1923
+ }
1924
+
1925
+ // Resolve configuration again if the file content or extension was changed.
1926
+ if (configForRecursive && (text !== blockText || path.extname(blockName) !== originalExtname)) {
1927
+ debug("Resolving configuration again because the file content or extension was changed.");
1928
+ return this._verifyWithConfigArray(
1929
+ blockText,
1930
+ configForRecursive,
1931
+ { ...options, filename: blockName, physicalFilename }
1932
+ );
1933
+ }
1934
+
1935
+ // Does lint.
1936
+ return this._verifyWithoutProcessors(
1937
+ blockText,
1938
+ config,
1939
+ { ...options, filename: blockName, physicalFilename }
1940
+ );
1941
+ });
1942
+
1943
+ return postprocess(messageLists, filenameToExpose);
1944
+ }
1945
+
1946
+ /**
1947
+ * Given a list of reported problems, distinguish problems between normal messages and suppressed messages.
1948
+ * The normal messages will be returned and the suppressed messages will be stored as lastSuppressedMessages.
1949
+ * @param {Array<LintMessage|SuppressedLintMessage>} problems A list of reported problems.
1950
+ * @returns {LintMessage[]} A list of LintMessage.
1951
+ */
1952
+ _distinguishSuppressedMessages(problems) {
1953
+ const messages = [];
1954
+ const suppressedMessages = [];
1955
+ const slots = internalSlotsMap.get(this);
1956
+
1957
+ for (const problem of problems) {
1958
+ if (problem.suppressions) {
1959
+ suppressedMessages.push(problem);
1960
+ } else {
1961
+ messages.push(problem);
1962
+ }
1963
+ }
1964
+
1965
+ slots.lastSuppressedMessages = suppressedMessages;
1966
+
1967
+ return messages;
1968
+ }
1969
+
1970
+ /**
1971
+ * Gets the SourceCode object representing the parsed source.
1972
+ * @returns {SourceCode} The SourceCode object.
1973
+ */
1974
+ getSourceCode() {
1975
+ return internalSlotsMap.get(this).lastSourceCode;
1976
+ }
1977
+
1978
+ /**
1979
+ * Gets the list of SuppressedLintMessage produced in the last running.
1980
+ * @returns {SuppressedLintMessage[]} The list of SuppressedLintMessage
1981
+ */
1982
+ getSuppressedMessages() {
1983
+ return internalSlotsMap.get(this).lastSuppressedMessages;
1984
+ }
1985
+
1986
+ /**
1987
+ * Defines a new linting rule.
1988
+ * @param {string} ruleId A unique rule identifier
1989
+ * @param {Function | Rule} ruleModule Function from context to object mapping AST node types to event handlers
1990
+ * @returns {void}
1991
+ */
1992
+ defineRule(ruleId, ruleModule) {
1993
+ assertEslintrcConfig(this);
1994
+ internalSlotsMap.get(this).ruleMap.define(ruleId, ruleModule);
1995
+ }
1996
+
1997
+ /**
1998
+ * Defines many new linting rules.
1999
+ * @param {Record<string, Function | Rule>} rulesToDefine map from unique rule identifier to rule
2000
+ * @returns {void}
2001
+ */
2002
+ defineRules(rulesToDefine) {
2003
+ assertEslintrcConfig(this);
2004
+ Object.getOwnPropertyNames(rulesToDefine).forEach(ruleId => {
2005
+ this.defineRule(ruleId, rulesToDefine[ruleId]);
2006
+ });
2007
+ }
2008
+
2009
+ /**
2010
+ * Gets an object with all loaded rules.
2011
+ * @returns {Map<string, Rule>} All loaded rules
2012
+ */
2013
+ getRules() {
2014
+ assertEslintrcConfig(this);
2015
+ const { lastConfigArray, ruleMap } = internalSlotsMap.get(this);
2016
+
2017
+ return new Map(function *() {
2018
+ yield* ruleMap;
2019
+
2020
+ if (lastConfigArray) {
2021
+ yield* lastConfigArray.pluginRules;
2022
+ }
2023
+ }());
2024
+ }
2025
+
2026
+ /**
2027
+ * Define a new parser module
2028
+ * @param {string} parserId Name of the parser
2029
+ * @param {Parser} parserModule The parser object
2030
+ * @returns {void}
2031
+ */
2032
+ defineParser(parserId, parserModule) {
2033
+ assertEslintrcConfig(this);
2034
+ internalSlotsMap.get(this).parserMap.set(parserId, parserModule);
2035
+ }
2036
+
2037
+ /**
2038
+ * Performs multiple autofix passes over the text until as many fixes as possible
2039
+ * have been applied.
2040
+ * @param {string} text The source text to apply fixes to.
2041
+ * @param {ConfigData|ConfigArray|FlatConfigArray} config The ESLint config object to use.
2042
+ * @param {VerifyOptions&ProcessorOptions&FixOptions} options The ESLint options object to use.
2043
+ * @returns {{fixed:boolean,messages:LintMessage[],output:string}} The result of the fix operation as returned from the
2044
+ * SourceCodeFixer.
2045
+ */
2046
+ verifyAndFix(text, config, options) {
2047
+ let messages = [],
2048
+ fixedResult,
2049
+ fixed = false,
2050
+ passNumber = 0,
2051
+ currentText = text;
2052
+ const debugTextDescription = options && options.filename || `${text.slice(0, 10)}...`;
2053
+ const shouldFix = options && typeof options.fix !== "undefined" ? options.fix : true;
2054
+
2055
+ /**
2056
+ * This loop continues until one of the following is true:
2057
+ *
2058
+ * 1. No more fixes have been applied.
2059
+ * 2. Ten passes have been made.
2060
+ *
2061
+ * That means anytime a fix is successfully applied, there will be another pass.
2062
+ * Essentially, guaranteeing a minimum of two passes.
2063
+ */
2064
+ do {
2065
+ passNumber++;
2066
+
2067
+ debug(`Linting code for ${debugTextDescription} (pass ${passNumber})`);
2068
+ messages = this.verify(currentText, config, options);
2069
+
2070
+ debug(`Generating fixed text for ${debugTextDescription} (pass ${passNumber})`);
2071
+ fixedResult = SourceCodeFixer.applyFixes(currentText, messages, shouldFix);
2072
+
2073
+ /*
2074
+ * stop if there are any syntax errors.
2075
+ * 'fixedResult.output' is a empty string.
2076
+ */
2077
+ if (messages.length === 1 && messages[0].fatal) {
2078
+ break;
2079
+ }
2080
+
2081
+ // keep track if any fixes were ever applied - important for return value
2082
+ fixed = fixed || fixedResult.fixed;
2083
+
2084
+ // update to use the fixed output instead of the original text
2085
+ currentText = fixedResult.output;
2086
+
2087
+ } while (
2088
+ fixedResult.fixed &&
2089
+ passNumber < MAX_AUTOFIX_PASSES
2090
+ );
2091
+
2092
+ /*
2093
+ * If the last result had fixes, we need to lint again to be sure we have
2094
+ * the most up-to-date information.
2095
+ */
2096
+ if (fixedResult.fixed) {
2097
+ fixedResult.messages = this.verify(currentText, config, options);
2098
+ }
2099
+
2100
+ // ensure the last result properly reflects if fixes were done
2101
+ fixedResult.fixed = fixed;
2102
+ fixedResult.output = currentText;
2103
+
2104
+ return fixedResult;
2105
+ }
2106
+ }
2107
+
2108
+ module.exports = {
2109
+ Linter,
2110
+
2111
+ /**
2112
+ * Get the internal slots of a given Linter instance for tests.
2113
+ * @param {Linter} instance The Linter instance to get.
2114
+ * @returns {LinterInternalSlots} The internal slots.
2115
+ */
2116
+ getLinterInternalSlots(instance) {
2117
+ return internalSlotsMap.get(instance);
2118
+ }
2119
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/node-event-generator.js ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview The event generator for AST nodes.
3
+ * @author Toru Nagashima
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //------------------------------------------------------------------------------
9
+ // Requirements
10
+ //------------------------------------------------------------------------------
11
+
12
+ const esquery = require("esquery");
13
+
14
+ //------------------------------------------------------------------------------
15
+ // Typedefs
16
+ //------------------------------------------------------------------------------
17
+
18
+ /**
19
+ * An object describing an AST selector
20
+ * @typedef {Object} ASTSelector
21
+ * @property {string} rawSelector The string that was parsed into this selector
22
+ * @property {boolean} isExit `true` if this should be emitted when exiting the node rather than when entering
23
+ * @property {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector
24
+ * @property {string[]|null} listenerTypes A list of node types that could possibly cause the selector to match,
25
+ * or `null` if all node types could cause a match
26
+ * @property {number} attributeCount The total number of classes, pseudo-classes, and attribute queries in this selector
27
+ * @property {number} identifierCount The total number of identifier queries in this selector
28
+ */
29
+
30
+ //------------------------------------------------------------------------------
31
+ // Helpers
32
+ //------------------------------------------------------------------------------
33
+
34
+ /**
35
+ * Computes the union of one or more arrays
36
+ * @param {...any[]} arrays One or more arrays to union
37
+ * @returns {any[]} The union of the input arrays
38
+ */
39
+ function union(...arrays) {
40
+ return [...new Set(arrays.flat())];
41
+ }
42
+
43
+ /**
44
+ * Computes the intersection of one or more arrays
45
+ * @param {...any[]} arrays One or more arrays to intersect
46
+ * @returns {any[]} The intersection of the input arrays
47
+ */
48
+ function intersection(...arrays) {
49
+ if (arrays.length === 0) {
50
+ return [];
51
+ }
52
+
53
+ let result = [...new Set(arrays[0])];
54
+
55
+ for (const array of arrays.slice(1)) {
56
+ result = result.filter(x => array.includes(x));
57
+ }
58
+ return result;
59
+ }
60
+
61
+ /**
62
+ * Gets the possible types of a selector
63
+ * @param {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector
64
+ * @returns {string[]|null} The node types that could possibly trigger this selector, or `null` if all node types could trigger it
65
+ */
66
+ function getPossibleTypes(parsedSelector) {
67
+ switch (parsedSelector.type) {
68
+ case "identifier":
69
+ return [parsedSelector.value];
70
+
71
+ case "matches": {
72
+ const typesForComponents = parsedSelector.selectors.map(getPossibleTypes);
73
+
74
+ if (typesForComponents.every(Boolean)) {
75
+ return union(...typesForComponents);
76
+ }
77
+ return null;
78
+ }
79
+
80
+ case "compound": {
81
+ const typesForComponents = parsedSelector.selectors.map(getPossibleTypes).filter(typesForComponent => typesForComponent);
82
+
83
+ // If all of the components could match any type, then the compound could also match any type.
84
+ if (!typesForComponents.length) {
85
+ return null;
86
+ }
87
+
88
+ /*
89
+ * If at least one of the components could only match a particular type, the compound could only match
90
+ * the intersection of those types.
91
+ */
92
+ return intersection(...typesForComponents);
93
+ }
94
+
95
+ case "child":
96
+ case "descendant":
97
+ case "sibling":
98
+ case "adjacent":
99
+ return getPossibleTypes(parsedSelector.right);
100
+
101
+ case "class":
102
+ if (parsedSelector.name === "function") {
103
+ return ["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"];
104
+ }
105
+
106
+ return null;
107
+
108
+ default:
109
+ return null;
110
+
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Counts the number of class, pseudo-class, and attribute queries in this selector
116
+ * @param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior
117
+ * @returns {number} The number of class, pseudo-class, and attribute queries in this selector
118
+ */
119
+ function countClassAttributes(parsedSelector) {
120
+ switch (parsedSelector.type) {
121
+ case "child":
122
+ case "descendant":
123
+ case "sibling":
124
+ case "adjacent":
125
+ return countClassAttributes(parsedSelector.left) + countClassAttributes(parsedSelector.right);
126
+
127
+ case "compound":
128
+ case "not":
129
+ case "matches":
130
+ return parsedSelector.selectors.reduce((sum, childSelector) => sum + countClassAttributes(childSelector), 0);
131
+
132
+ case "attribute":
133
+ case "field":
134
+ case "nth-child":
135
+ case "nth-last-child":
136
+ return 1;
137
+
138
+ default:
139
+ return 0;
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Counts the number of identifier queries in this selector
145
+ * @param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior
146
+ * @returns {number} The number of identifier queries
147
+ */
148
+ function countIdentifiers(parsedSelector) {
149
+ switch (parsedSelector.type) {
150
+ case "child":
151
+ case "descendant":
152
+ case "sibling":
153
+ case "adjacent":
154
+ return countIdentifiers(parsedSelector.left) + countIdentifiers(parsedSelector.right);
155
+
156
+ case "compound":
157
+ case "not":
158
+ case "matches":
159
+ return parsedSelector.selectors.reduce((sum, childSelector) => sum + countIdentifiers(childSelector), 0);
160
+
161
+ case "identifier":
162
+ return 1;
163
+
164
+ default:
165
+ return 0;
166
+ }
167
+ }
168
+
169
+ /**
170
+ * Compares the specificity of two selector objects, with CSS-like rules.
171
+ * @param {ASTSelector} selectorA An AST selector descriptor
172
+ * @param {ASTSelector} selectorB Another AST selector descriptor
173
+ * @returns {number}
174
+ * a value less than 0 if selectorA is less specific than selectorB
175
+ * a value greater than 0 if selectorA is more specific than selectorB
176
+ * a value less than 0 if selectorA and selectorB have the same specificity, and selectorA <= selectorB alphabetically
177
+ * a value greater than 0 if selectorA and selectorB have the same specificity, and selectorA > selectorB alphabetically
178
+ */
179
+ function compareSpecificity(selectorA, selectorB) {
180
+ return selectorA.attributeCount - selectorB.attributeCount ||
181
+ selectorA.identifierCount - selectorB.identifierCount ||
182
+ (selectorA.rawSelector <= selectorB.rawSelector ? -1 : 1);
183
+ }
184
+
185
+ /**
186
+ * Parses a raw selector string, and throws a useful error if parsing fails.
187
+ * @param {string} rawSelector A raw AST selector
188
+ * @returns {Object} An object (from esquery) describing the matching behavior of this selector
189
+ * @throws {Error} An error if the selector is invalid
190
+ */
191
+ function tryParseSelector(rawSelector) {
192
+ try {
193
+ return esquery.parse(rawSelector.replace(/:exit$/u, ""));
194
+ } catch (err) {
195
+ if (err.location && err.location.start && typeof err.location.start.offset === "number") {
196
+ throw new SyntaxError(`Syntax error in selector "${rawSelector}" at position ${err.location.start.offset}: ${err.message}`);
197
+ }
198
+ throw err;
199
+ }
200
+ }
201
+
202
+ const selectorCache = new Map();
203
+
204
+ /**
205
+ * Parses a raw selector string, and returns the parsed selector along with specificity and type information.
206
+ * @param {string} rawSelector A raw AST selector
207
+ * @returns {ASTSelector} A selector descriptor
208
+ */
209
+ function parseSelector(rawSelector) {
210
+ if (selectorCache.has(rawSelector)) {
211
+ return selectorCache.get(rawSelector);
212
+ }
213
+
214
+ const parsedSelector = tryParseSelector(rawSelector);
215
+
216
+ const result = {
217
+ rawSelector,
218
+ isExit: rawSelector.endsWith(":exit"),
219
+ parsedSelector,
220
+ listenerTypes: getPossibleTypes(parsedSelector),
221
+ attributeCount: countClassAttributes(parsedSelector),
222
+ identifierCount: countIdentifiers(parsedSelector)
223
+ };
224
+
225
+ selectorCache.set(rawSelector, result);
226
+ return result;
227
+ }
228
+
229
+ //------------------------------------------------------------------------------
230
+ // Public Interface
231
+ //------------------------------------------------------------------------------
232
+
233
+ /**
234
+ * The event generator for AST nodes.
235
+ * This implements below interface.
236
+ *
237
+ * ```ts
238
+ * interface EventGenerator {
239
+ * emitter: SafeEmitter;
240
+ * enterNode(node: ASTNode): void;
241
+ * leaveNode(node: ASTNode): void;
242
+ * }
243
+ * ```
244
+ */
245
+ class NodeEventGenerator {
246
+
247
+ /**
248
+ * @param {SafeEmitter} emitter
249
+ * An SafeEmitter which is the destination of events. This emitter must already
250
+ * have registered listeners for all of the events that it needs to listen for.
251
+ * (See lib/linter/safe-emitter.js for more details on `SafeEmitter`.)
252
+ * @param {ESQueryOptions} esqueryOptions `esquery` options for traversing custom nodes.
253
+ * @returns {NodeEventGenerator} new instance
254
+ */
255
+ constructor(emitter, esqueryOptions) {
256
+ this.emitter = emitter;
257
+ this.esqueryOptions = esqueryOptions;
258
+ this.currentAncestry = [];
259
+ this.enterSelectorsByNodeType = new Map();
260
+ this.exitSelectorsByNodeType = new Map();
261
+ this.anyTypeEnterSelectors = [];
262
+ this.anyTypeExitSelectors = [];
263
+
264
+ emitter.eventNames().forEach(rawSelector => {
265
+ const selector = parseSelector(rawSelector);
266
+
267
+ if (selector.listenerTypes) {
268
+ const typeMap = selector.isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType;
269
+
270
+ selector.listenerTypes.forEach(nodeType => {
271
+ if (!typeMap.has(nodeType)) {
272
+ typeMap.set(nodeType, []);
273
+ }
274
+ typeMap.get(nodeType).push(selector);
275
+ });
276
+ return;
277
+ }
278
+ const selectors = selector.isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors;
279
+
280
+ selectors.push(selector);
281
+ });
282
+
283
+ this.anyTypeEnterSelectors.sort(compareSpecificity);
284
+ this.anyTypeExitSelectors.sort(compareSpecificity);
285
+ this.enterSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity));
286
+ this.exitSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity));
287
+ }
288
+
289
+ /**
290
+ * Checks a selector against a node, and emits it if it matches
291
+ * @param {ASTNode} node The node to check
292
+ * @param {ASTSelector} selector An AST selector descriptor
293
+ * @returns {void}
294
+ */
295
+ applySelector(node, selector) {
296
+ if (esquery.matches(node, selector.parsedSelector, this.currentAncestry, this.esqueryOptions)) {
297
+ this.emitter.emit(selector.rawSelector, node);
298
+ }
299
+ }
300
+
301
+ /**
302
+ * Applies all appropriate selectors to a node, in specificity order
303
+ * @param {ASTNode} node The node to check
304
+ * @param {boolean} isExit `false` if the node is currently being entered, `true` if it's currently being exited
305
+ * @returns {void}
306
+ */
307
+ applySelectors(node, isExit) {
308
+ const selectorsByNodeType = (isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType).get(node.type) || [];
309
+ const anyTypeSelectors = isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors;
310
+
311
+ /*
312
+ * selectorsByNodeType and anyTypeSelectors were already sorted by specificity in the constructor.
313
+ * Iterate through each of them, applying selectors in the right order.
314
+ */
315
+ let selectorsByTypeIndex = 0;
316
+ let anyTypeSelectorsIndex = 0;
317
+
318
+ while (selectorsByTypeIndex < selectorsByNodeType.length || anyTypeSelectorsIndex < anyTypeSelectors.length) {
319
+ if (
320
+ selectorsByTypeIndex >= selectorsByNodeType.length ||
321
+ anyTypeSelectorsIndex < anyTypeSelectors.length &&
322
+ compareSpecificity(anyTypeSelectors[anyTypeSelectorsIndex], selectorsByNodeType[selectorsByTypeIndex]) < 0
323
+ ) {
324
+ this.applySelector(node, anyTypeSelectors[anyTypeSelectorsIndex++]);
325
+ } else {
326
+ this.applySelector(node, selectorsByNodeType[selectorsByTypeIndex++]);
327
+ }
328
+ }
329
+ }
330
+
331
+ /**
332
+ * Emits an event of entering AST node.
333
+ * @param {ASTNode} node A node which was entered.
334
+ * @returns {void}
335
+ */
336
+ enterNode(node) {
337
+ if (node.parent) {
338
+ this.currentAncestry.unshift(node.parent);
339
+ }
340
+ this.applySelectors(node, false);
341
+ }
342
+
343
+ /**
344
+ * Emits an event of leaving AST node.
345
+ * @param {ASTNode} node A node which was left.
346
+ * @returns {void}
347
+ */
348
+ leaveNode(node) {
349
+ this.applySelectors(node, true);
350
+ this.currentAncestry.shift();
351
+ }
352
+ }
353
+
354
+ module.exports = NodeEventGenerator;
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/report-translator.js ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview A helper that translates context.report() calls from the rule API into generic problem objects
3
+ * @author Teddy Katz
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //------------------------------------------------------------------------------
9
+ // Requirements
10
+ //------------------------------------------------------------------------------
11
+
12
+ const assert = require("assert");
13
+ const ruleFixer = require("./rule-fixer");
14
+ const interpolate = require("./interpolate");
15
+
16
+ //------------------------------------------------------------------------------
17
+ // Typedefs
18
+ //------------------------------------------------------------------------------
19
+
20
+ /** @typedef {import("../shared/types").LintMessage} LintMessage */
21
+
22
+ /**
23
+ * An error message description
24
+ * @typedef {Object} MessageDescriptor
25
+ * @property {ASTNode} [node] The reported node
26
+ * @property {Location} loc The location of the problem.
27
+ * @property {string} message The problem message.
28
+ * @property {Object} [data] Optional data to use to fill in placeholders in the
29
+ * message.
30
+ * @property {Function} [fix] The function to call that creates a fix command.
31
+ * @property {Array<{desc?: string, messageId?: string, fix: Function}>} suggest Suggestion descriptions and functions to create a the associated fixes.
32
+ */
33
+
34
+ //------------------------------------------------------------------------------
35
+ // Module Definition
36
+ //------------------------------------------------------------------------------
37
+
38
+
39
+ /**
40
+ * Translates a multi-argument context.report() call into a single object argument call
41
+ * @param {...*} args A list of arguments passed to `context.report`
42
+ * @returns {MessageDescriptor} A normalized object containing report information
43
+ */
44
+ function normalizeMultiArgReportCall(...args) {
45
+
46
+ // If there is one argument, it is considered to be a new-style call already.
47
+ if (args.length === 1) {
48
+
49
+ // Shallow clone the object to avoid surprises if reusing the descriptor
50
+ return Object.assign({}, args[0]);
51
+ }
52
+
53
+ // If the second argument is a string, the arguments are interpreted as [node, message, data, fix].
54
+ if (typeof args[1] === "string") {
55
+ return {
56
+ node: args[0],
57
+ message: args[1],
58
+ data: args[2],
59
+ fix: args[3]
60
+ };
61
+ }
62
+
63
+ // Otherwise, the arguments are interpreted as [node, loc, message, data, fix].
64
+ return {
65
+ node: args[0],
66
+ loc: args[1],
67
+ message: args[2],
68
+ data: args[3],
69
+ fix: args[4]
70
+ };
71
+ }
72
+
73
+ /**
74
+ * Asserts that either a loc or a node was provided, and the node is valid if it was provided.
75
+ * @param {MessageDescriptor} descriptor A descriptor to validate
76
+ * @returns {void}
77
+ * @throws AssertionError if neither a node nor a loc was provided, or if the node is not an object
78
+ */
79
+ function assertValidNodeInfo(descriptor) {
80
+ if (descriptor.node) {
81
+ assert(typeof descriptor.node === "object", "Node must be an object");
82
+ } else {
83
+ assert(descriptor.loc, "Node must be provided when reporting error if location is not provided");
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Normalizes a MessageDescriptor to always have a `loc` with `start` and `end` properties
89
+ * @param {MessageDescriptor} descriptor A descriptor for the report from a rule.
90
+ * @returns {{start: Location, end: (Location|null)}} An updated location that infers the `start` and `end` properties
91
+ * from the `node` of the original descriptor, or infers the `start` from the `loc` of the original descriptor.
92
+ */
93
+ function normalizeReportLoc(descriptor) {
94
+ if (descriptor.loc) {
95
+ if (descriptor.loc.start) {
96
+ return descriptor.loc;
97
+ }
98
+ return { start: descriptor.loc, end: null };
99
+ }
100
+ return descriptor.node.loc;
101
+ }
102
+
103
+ /**
104
+ * Clones the given fix object.
105
+ * @param {Fix|null} fix The fix to clone.
106
+ * @returns {Fix|null} Deep cloned fix object or `null` if `null` or `undefined` was passed in.
107
+ */
108
+ function cloneFix(fix) {
109
+ if (!fix) {
110
+ return null;
111
+ }
112
+
113
+ return {
114
+ range: [fix.range[0], fix.range[1]],
115
+ text: fix.text
116
+ };
117
+ }
118
+
119
+ /**
120
+ * Check that a fix has a valid range.
121
+ * @param {Fix|null} fix The fix to validate.
122
+ * @returns {void}
123
+ */
124
+ function assertValidFix(fix) {
125
+ if (fix) {
126
+ assert(fix.range && typeof fix.range[0] === "number" && typeof fix.range[1] === "number", `Fix has invalid range: ${JSON.stringify(fix, null, 2)}`);
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Compares items in a fixes array by range.
132
+ * @param {Fix} a The first message.
133
+ * @param {Fix} b The second message.
134
+ * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal.
135
+ * @private
136
+ */
137
+ function compareFixesByRange(a, b) {
138
+ return a.range[0] - b.range[0] || a.range[1] - b.range[1];
139
+ }
140
+
141
+ /**
142
+ * Merges the given fixes array into one.
143
+ * @param {Fix[]} fixes The fixes to merge.
144
+ * @param {SourceCode} sourceCode The source code object to get the text between fixes.
145
+ * @returns {{text: string, range: number[]}} The merged fixes
146
+ */
147
+ function mergeFixes(fixes, sourceCode) {
148
+ for (const fix of fixes) {
149
+ assertValidFix(fix);
150
+ }
151
+
152
+ if (fixes.length === 0) {
153
+ return null;
154
+ }
155
+ if (fixes.length === 1) {
156
+ return cloneFix(fixes[0]);
157
+ }
158
+
159
+ fixes.sort(compareFixesByRange);
160
+
161
+ const originalText = sourceCode.text;
162
+ const start = fixes[0].range[0];
163
+ const end = fixes[fixes.length - 1].range[1];
164
+ let text = "";
165
+ let lastPos = Number.MIN_SAFE_INTEGER;
166
+
167
+ for (const fix of fixes) {
168
+ assert(fix.range[0] >= lastPos, "Fix objects must not be overlapped in a report.");
169
+
170
+ if (fix.range[0] >= 0) {
171
+ text += originalText.slice(Math.max(0, start, lastPos), fix.range[0]);
172
+ }
173
+ text += fix.text;
174
+ lastPos = fix.range[1];
175
+ }
176
+ text += originalText.slice(Math.max(0, start, lastPos), end);
177
+
178
+ return { range: [start, end], text };
179
+ }
180
+
181
+ /**
182
+ * Gets one fix object from the given descriptor.
183
+ * If the descriptor retrieves multiple fixes, this merges those to one.
184
+ * @param {MessageDescriptor} descriptor The report descriptor.
185
+ * @param {SourceCode} sourceCode The source code object to get text between fixes.
186
+ * @returns {({text: string, range: number[]}|null)} The fix for the descriptor
187
+ */
188
+ function normalizeFixes(descriptor, sourceCode) {
189
+ if (typeof descriptor.fix !== "function") {
190
+ return null;
191
+ }
192
+
193
+ // @type {null | Fix | Fix[] | IterableIterator<Fix>}
194
+ const fix = descriptor.fix(ruleFixer);
195
+
196
+ // Merge to one.
197
+ if (fix && Symbol.iterator in fix) {
198
+ return mergeFixes(Array.from(fix), sourceCode);
199
+ }
200
+
201
+ assertValidFix(fix);
202
+ return cloneFix(fix);
203
+ }
204
+
205
+ /**
206
+ * Gets an array of suggestion objects from the given descriptor.
207
+ * @param {MessageDescriptor} descriptor The report descriptor.
208
+ * @param {SourceCode} sourceCode The source code object to get text between fixes.
209
+ * @param {Object} messages Object of meta messages for the rule.
210
+ * @returns {Array<SuggestionResult>} The suggestions for the descriptor
211
+ */
212
+ function mapSuggestions(descriptor, sourceCode, messages) {
213
+ if (!descriptor.suggest || !Array.isArray(descriptor.suggest)) {
214
+ return [];
215
+ }
216
+
217
+ return descriptor.suggest
218
+ .map(suggestInfo => {
219
+ const computedDesc = suggestInfo.desc || messages[suggestInfo.messageId];
220
+
221
+ return {
222
+ ...suggestInfo,
223
+ desc: interpolate(computedDesc, suggestInfo.data),
224
+ fix: normalizeFixes(suggestInfo, sourceCode)
225
+ };
226
+ })
227
+
228
+ // Remove suggestions that didn't provide a fix
229
+ .filter(({ fix }) => fix);
230
+ }
231
+
232
+ /**
233
+ * Creates information about the report from a descriptor
234
+ * @param {Object} options Information about the problem
235
+ * @param {string} options.ruleId Rule ID
236
+ * @param {(0|1|2)} options.severity Rule severity
237
+ * @param {(ASTNode|null)} options.node Node
238
+ * @param {string} options.message Error message
239
+ * @param {string} [options.messageId] The error message ID.
240
+ * @param {{start: SourceLocation, end: (SourceLocation|null)}} options.loc Start and end location
241
+ * @param {{text: string, range: (number[]|null)}} options.fix The fix object
242
+ * @param {Array<{text: string, range: (number[]|null)}>} options.suggestions The array of suggestions objects
243
+ * @returns {LintMessage} Information about the report
244
+ */
245
+ function createProblem(options) {
246
+ const problem = {
247
+ ruleId: options.ruleId,
248
+ severity: options.severity,
249
+ message: options.message,
250
+ line: options.loc.start.line,
251
+ column: options.loc.start.column + 1,
252
+ nodeType: options.node && options.node.type || null
253
+ };
254
+
255
+ /*
256
+ * If this isn’t in the conditional, some of the tests fail
257
+ * because `messageId` is present in the problem object
258
+ */
259
+ if (options.messageId) {
260
+ problem.messageId = options.messageId;
261
+ }
262
+
263
+ if (options.loc.end) {
264
+ problem.endLine = options.loc.end.line;
265
+ problem.endColumn = options.loc.end.column + 1;
266
+ }
267
+
268
+ if (options.fix) {
269
+ problem.fix = options.fix;
270
+ }
271
+
272
+ if (options.suggestions && options.suggestions.length > 0) {
273
+ problem.suggestions = options.suggestions;
274
+ }
275
+
276
+ return problem;
277
+ }
278
+
279
+ /**
280
+ * Validates that suggestions are properly defined. Throws if an error is detected.
281
+ * @param {Array<{ desc?: string, messageId?: string }>} suggest The incoming suggest data.
282
+ * @param {Object} messages Object of meta messages for the rule.
283
+ * @returns {void}
284
+ */
285
+ function validateSuggestions(suggest, messages) {
286
+ if (suggest && Array.isArray(suggest)) {
287
+ suggest.forEach(suggestion => {
288
+ if (suggestion.messageId) {
289
+ const { messageId } = suggestion;
290
+
291
+ if (!messages) {
292
+ throw new TypeError(`context.report() called with a suggest option with a messageId '${messageId}', but no messages were present in the rule metadata.`);
293
+ }
294
+
295
+ if (!messages[messageId]) {
296
+ throw new TypeError(`context.report() called with a suggest option with a messageId '${messageId}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`);
297
+ }
298
+
299
+ if (suggestion.desc) {
300
+ throw new TypeError("context.report() called with a suggest option that defines both a 'messageId' and an 'desc'. Please only pass one.");
301
+ }
302
+ } else if (!suggestion.desc) {
303
+ throw new TypeError("context.report() called with a suggest option that doesn't have either a `desc` or `messageId`");
304
+ }
305
+
306
+ if (typeof suggestion.fix !== "function") {
307
+ throw new TypeError(`context.report() called with a suggest option without a fix function. See: ${suggestion}`);
308
+ }
309
+ });
310
+ }
311
+ }
312
+
313
+ /**
314
+ * Returns a function that converts the arguments of a `context.report` call from a rule into a reported
315
+ * problem for the Node.js API.
316
+ * @param {{ruleId: string, severity: number, sourceCode: SourceCode, messageIds: Object, disableFixes: boolean}} metadata Metadata for the reported problem
317
+ * @param {SourceCode} sourceCode The `SourceCode` instance for the text being linted
318
+ * @returns {function(...args): LintMessage} Function that returns information about the report
319
+ */
320
+
321
+ module.exports = function createReportTranslator(metadata) {
322
+
323
+ /*
324
+ * `createReportTranslator` gets called once per enabled rule per file. It needs to be very performant.
325
+ * The report translator itself (i.e. the function that `createReportTranslator` returns) gets
326
+ * called every time a rule reports a problem, which happens much less frequently (usually, the vast
327
+ * majority of rules don't report any problems for a given file).
328
+ */
329
+ return (...args) => {
330
+ const descriptor = normalizeMultiArgReportCall(...args);
331
+ const messages = metadata.messageIds;
332
+
333
+ assertValidNodeInfo(descriptor);
334
+
335
+ let computedMessage;
336
+
337
+ if (descriptor.messageId) {
338
+ if (!messages) {
339
+ throw new TypeError("context.report() called with a messageId, but no messages were present in the rule metadata.");
340
+ }
341
+ const id = descriptor.messageId;
342
+
343
+ if (descriptor.message) {
344
+ throw new TypeError("context.report() called with a message and a messageId. Please only pass one.");
345
+ }
346
+ if (!messages || !Object.prototype.hasOwnProperty.call(messages, id)) {
347
+ throw new TypeError(`context.report() called with a messageId of '${id}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`);
348
+ }
349
+ computedMessage = messages[id];
350
+ } else if (descriptor.message) {
351
+ computedMessage = descriptor.message;
352
+ } else {
353
+ throw new TypeError("Missing `message` property in report() call; add a message that describes the linting problem.");
354
+ }
355
+
356
+ validateSuggestions(descriptor.suggest, messages);
357
+
358
+ return createProblem({
359
+ ruleId: metadata.ruleId,
360
+ severity: metadata.severity,
361
+ node: descriptor.node,
362
+ message: interpolate(computedMessage, descriptor.data),
363
+ messageId: descriptor.messageId,
364
+ loc: normalizeReportLoc(descriptor),
365
+ fix: metadata.disableFixes ? null : normalizeFixes(descriptor, metadata.sourceCode),
366
+ suggestions: metadata.disableFixes ? [] : mapSuggestions(descriptor, metadata.sourceCode, messages)
367
+ });
368
+ };
369
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/rule-fixer.js ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview An object that creates fix commands for rules.
3
+ * @author Nicholas C. Zakas
4
+ */
5
+ "use strict";
6
+
7
+ //------------------------------------------------------------------------------
8
+ // Requirements
9
+ //------------------------------------------------------------------------------
10
+
11
+ // none!
12
+
13
+ //------------------------------------------------------------------------------
14
+ // Helpers
15
+ //------------------------------------------------------------------------------
16
+
17
+ /**
18
+ * Creates a fix command that inserts text at the specified index in the source text.
19
+ * @param {int} index The 0-based index at which to insert the new text.
20
+ * @param {string} text The text to insert.
21
+ * @returns {Object} The fix command.
22
+ * @private
23
+ */
24
+ function insertTextAt(index, text) {
25
+ return {
26
+ range: [index, index],
27
+ text
28
+ };
29
+ }
30
+
31
+ //------------------------------------------------------------------------------
32
+ // Public Interface
33
+ //------------------------------------------------------------------------------
34
+
35
+ /**
36
+ * Creates code fixing commands for rules.
37
+ */
38
+
39
+ const ruleFixer = Object.freeze({
40
+
41
+ /**
42
+ * Creates a fix command that inserts text after the given node or token.
43
+ * The fix is not applied until applyFixes() is called.
44
+ * @param {ASTNode|Token} nodeOrToken The node or token to insert after.
45
+ * @param {string} text The text to insert.
46
+ * @returns {Object} The fix command.
47
+ */
48
+ insertTextAfter(nodeOrToken, text) {
49
+ return this.insertTextAfterRange(nodeOrToken.range, text);
50
+ },
51
+
52
+ /**
53
+ * Creates a fix command that inserts text after the specified range in the source text.
54
+ * The fix is not applied until applyFixes() is called.
55
+ * @param {int[]} range The range to replace, first item is start of range, second
56
+ * is end of range.
57
+ * @param {string} text The text to insert.
58
+ * @returns {Object} The fix command.
59
+ */
60
+ insertTextAfterRange(range, text) {
61
+ return insertTextAt(range[1], text);
62
+ },
63
+
64
+ /**
65
+ * Creates a fix command that inserts text before the given node or token.
66
+ * The fix is not applied until applyFixes() is called.
67
+ * @param {ASTNode|Token} nodeOrToken The node or token to insert before.
68
+ * @param {string} text The text to insert.
69
+ * @returns {Object} The fix command.
70
+ */
71
+ insertTextBefore(nodeOrToken, text) {
72
+ return this.insertTextBeforeRange(nodeOrToken.range, text);
73
+ },
74
+
75
+ /**
76
+ * Creates a fix command that inserts text before the specified range in the source text.
77
+ * The fix is not applied until applyFixes() is called.
78
+ * @param {int[]} range The range to replace, first item is start of range, second
79
+ * is end of range.
80
+ * @param {string} text The text to insert.
81
+ * @returns {Object} The fix command.
82
+ */
83
+ insertTextBeforeRange(range, text) {
84
+ return insertTextAt(range[0], text);
85
+ },
86
+
87
+ /**
88
+ * Creates a fix command that replaces text at the node or token.
89
+ * The fix is not applied until applyFixes() is called.
90
+ * @param {ASTNode|Token} nodeOrToken The node or token to remove.
91
+ * @param {string} text The text to insert.
92
+ * @returns {Object} The fix command.
93
+ */
94
+ replaceText(nodeOrToken, text) {
95
+ return this.replaceTextRange(nodeOrToken.range, text);
96
+ },
97
+
98
+ /**
99
+ * Creates a fix command that replaces text at the specified range in the source text.
100
+ * The fix is not applied until applyFixes() is called.
101
+ * @param {int[]} range The range to replace, first item is start of range, second
102
+ * is end of range.
103
+ * @param {string} text The text to insert.
104
+ * @returns {Object} The fix command.
105
+ */
106
+ replaceTextRange(range, text) {
107
+ return {
108
+ range,
109
+ text
110
+ };
111
+ },
112
+
113
+ /**
114
+ * Creates a fix command that removes the node or token from the source.
115
+ * The fix is not applied until applyFixes() is called.
116
+ * @param {ASTNode|Token} nodeOrToken The node or token to remove.
117
+ * @returns {Object} The fix command.
118
+ */
119
+ remove(nodeOrToken) {
120
+ return this.removeRange(nodeOrToken.range);
121
+ },
122
+
123
+ /**
124
+ * Creates a fix command that removes the specified range of text from the source.
125
+ * The fix is not applied until applyFixes() is called.
126
+ * @param {int[]} range The range to remove, first item is start of range, second
127
+ * is end of range.
128
+ * @returns {Object} The fix command.
129
+ */
130
+ removeRange(range) {
131
+ return {
132
+ range,
133
+ text: ""
134
+ };
135
+ }
136
+
137
+ });
138
+
139
+
140
+ module.exports = ruleFixer;
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/rules.js ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Defines a storage for rules.
3
+ * @author Nicholas C. Zakas
4
+ * @author aladdin-add
5
+ */
6
+
7
+ "use strict";
8
+
9
+ //------------------------------------------------------------------------------
10
+ // Requirements
11
+ //------------------------------------------------------------------------------
12
+
13
+ const builtInRules = require("../rules");
14
+
15
+ //------------------------------------------------------------------------------
16
+ // Helpers
17
+ //------------------------------------------------------------------------------
18
+
19
+ /**
20
+ * Normalizes a rule module to the new-style API
21
+ * @param {(Function|{create: Function})} rule A rule object, which can either be a function
22
+ * ("old-style") or an object with a `create` method ("new-style")
23
+ * @returns {{create: Function}} A new-style rule.
24
+ */
25
+ function normalizeRule(rule) {
26
+ return typeof rule === "function" ? Object.assign({ create: rule }, rule) : rule;
27
+ }
28
+
29
+ //------------------------------------------------------------------------------
30
+ // Public Interface
31
+ //------------------------------------------------------------------------------
32
+
33
+ /**
34
+ * A storage for rules.
35
+ */
36
+ class Rules {
37
+ constructor() {
38
+ this._rules = Object.create(null);
39
+ }
40
+
41
+ /**
42
+ * Registers a rule module for rule id in storage.
43
+ * @param {string} ruleId Rule id (file name).
44
+ * @param {Function} ruleModule Rule handler.
45
+ * @returns {void}
46
+ */
47
+ define(ruleId, ruleModule) {
48
+ this._rules[ruleId] = normalizeRule(ruleModule);
49
+ }
50
+
51
+ /**
52
+ * Access rule handler by id (file name).
53
+ * @param {string} ruleId Rule id (file name).
54
+ * @returns {{create: Function, schema: JsonSchema[]}}
55
+ * A rule. This is normalized to always have the new-style shape with a `create` method.
56
+ */
57
+ get(ruleId) {
58
+ if (typeof this._rules[ruleId] === "string") {
59
+ this.define(ruleId, require(this._rules[ruleId]));
60
+ }
61
+ if (this._rules[ruleId]) {
62
+ return this._rules[ruleId];
63
+ }
64
+ if (builtInRules.has(ruleId)) {
65
+ return builtInRules.get(ruleId);
66
+ }
67
+
68
+ return null;
69
+ }
70
+
71
+ *[Symbol.iterator]() {
72
+ yield* builtInRules;
73
+
74
+ for (const ruleId of Object.keys(this._rules)) {
75
+ yield [ruleId, this.get(ruleId)];
76
+ }
77
+ }
78
+ }
79
+
80
+ module.exports = Rules;
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/safe-emitter.js ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview A variant of EventEmitter which does not give listeners information about each other
3
+ * @author Teddy Katz
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //------------------------------------------------------------------------------
9
+ // Typedefs
10
+ //------------------------------------------------------------------------------
11
+
12
+ /**
13
+ * An event emitter
14
+ * @typedef {Object} SafeEmitter
15
+ * @property {(eventName: string, listenerFunc: Function) => void} on Adds a listener for a given event name
16
+ * @property {(eventName: string, arg1?: any, arg2?: any, arg3?: any) => void} emit Emits an event with a given name.
17
+ * This calls all the listeners that were listening for that name, with `arg1`, `arg2`, and `arg3` as arguments.
18
+ * @property {function(): string[]} eventNames Gets the list of event names that have registered listeners.
19
+ */
20
+
21
+ /**
22
+ * Creates an object which can listen for and emit events.
23
+ * This is similar to the EventEmitter API in Node's standard library, but it has a few differences.
24
+ * The goal is to allow multiple modules to attach arbitrary listeners to the same emitter, without
25
+ * letting the modules know about each other at all.
26
+ * 1. It has no special keys like `error` and `newListener`, which would allow modules to detect when
27
+ * another module throws an error or registers a listener.
28
+ * 2. It calls listener functions without any `this` value. (`EventEmitter` calls listeners with a
29
+ * `this` value of the emitter instance, which would give listeners access to other listeners.)
30
+ * @returns {SafeEmitter} An emitter
31
+ */
32
+ module.exports = () => {
33
+ const listeners = Object.create(null);
34
+
35
+ return Object.freeze({
36
+ on(eventName, listener) {
37
+ if (eventName in listeners) {
38
+ listeners[eventName].push(listener);
39
+ } else {
40
+ listeners[eventName] = [listener];
41
+ }
42
+ },
43
+ emit(eventName, ...args) {
44
+ if (eventName in listeners) {
45
+ listeners[eventName].forEach(listener => listener(...args));
46
+ }
47
+ },
48
+ eventNames() {
49
+ return Object.keys(listeners);
50
+ }
51
+ });
52
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/source-code-fixer.js ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview An object that caches and applies source code fixes.
3
+ * @author Nicholas C. Zakas
4
+ */
5
+ "use strict";
6
+
7
+ //------------------------------------------------------------------------------
8
+ // Requirements
9
+ //------------------------------------------------------------------------------
10
+
11
+ const debug = require("debug")("eslint:source-code-fixer");
12
+
13
+ //------------------------------------------------------------------------------
14
+ // Helpers
15
+ //------------------------------------------------------------------------------
16
+
17
+ const BOM = "\uFEFF";
18
+
19
+ /**
20
+ * Compares items in a messages array by range.
21
+ * @param {Message} a The first message.
22
+ * @param {Message} b The second message.
23
+ * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal.
24
+ * @private
25
+ */
26
+ function compareMessagesByFixRange(a, b) {
27
+ return a.fix.range[0] - b.fix.range[0] || a.fix.range[1] - b.fix.range[1];
28
+ }
29
+
30
+ /**
31
+ * Compares items in a messages array by line and column.
32
+ * @param {Message} a The first message.
33
+ * @param {Message} b The second message.
34
+ * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal.
35
+ * @private
36
+ */
37
+ function compareMessagesByLocation(a, b) {
38
+ return a.line - b.line || a.column - b.column;
39
+ }
40
+
41
+ //------------------------------------------------------------------------------
42
+ // Public Interface
43
+ //------------------------------------------------------------------------------
44
+
45
+ /**
46
+ * Utility for apply fixes to source code.
47
+ * @constructor
48
+ */
49
+ function SourceCodeFixer() {
50
+ Object.freeze(this);
51
+ }
52
+
53
+ /**
54
+ * Applies the fixes specified by the messages to the given text. Tries to be
55
+ * smart about the fixes and won't apply fixes over the same area in the text.
56
+ * @param {string} sourceText The text to apply the changes to.
57
+ * @param {Message[]} messages The array of messages reported by ESLint.
58
+ * @param {boolean|Function} [shouldFix=true] Determines whether each message should be fixed
59
+ * @returns {Object} An object containing the fixed text and any unfixed messages.
60
+ */
61
+ SourceCodeFixer.applyFixes = function(sourceText, messages, shouldFix) {
62
+ debug("Applying fixes");
63
+
64
+ if (shouldFix === false) {
65
+ debug("shouldFix parameter was false, not attempting fixes");
66
+ return {
67
+ fixed: false,
68
+ messages,
69
+ output: sourceText
70
+ };
71
+ }
72
+
73
+ // clone the array
74
+ const remainingMessages = [],
75
+ fixes = [],
76
+ bom = sourceText.startsWith(BOM) ? BOM : "",
77
+ text = bom ? sourceText.slice(1) : sourceText;
78
+ let lastPos = Number.NEGATIVE_INFINITY,
79
+ output = bom;
80
+
81
+ /**
82
+ * Try to use the 'fix' from a problem.
83
+ * @param {Message} problem The message object to apply fixes from
84
+ * @returns {boolean} Whether fix was successfully applied
85
+ */
86
+ function attemptFix(problem) {
87
+ const fix = problem.fix;
88
+ const start = fix.range[0];
89
+ const end = fix.range[1];
90
+
91
+ // Remain it as a problem if it's overlapped or it's a negative range
92
+ if (lastPos >= start || start > end) {
93
+ remainingMessages.push(problem);
94
+ return false;
95
+ }
96
+
97
+ // Remove BOM.
98
+ if ((start < 0 && end >= 0) || (start === 0 && fix.text.startsWith(BOM))) {
99
+ output = "";
100
+ }
101
+
102
+ // Make output to this fix.
103
+ output += text.slice(Math.max(0, lastPos), Math.max(0, start));
104
+ output += fix.text;
105
+ lastPos = end;
106
+ return true;
107
+ }
108
+
109
+ messages.forEach(problem => {
110
+ if (Object.prototype.hasOwnProperty.call(problem, "fix")) {
111
+ fixes.push(problem);
112
+ } else {
113
+ remainingMessages.push(problem);
114
+ }
115
+ });
116
+
117
+ if (fixes.length) {
118
+ debug("Found fixes to apply");
119
+ let fixesWereApplied = false;
120
+
121
+ for (const problem of fixes.sort(compareMessagesByFixRange)) {
122
+ if (typeof shouldFix !== "function" || shouldFix(problem)) {
123
+ attemptFix(problem);
124
+
125
+ /*
126
+ * The only time attemptFix will fail is if a previous fix was
127
+ * applied which conflicts with it. So we can mark this as true.
128
+ */
129
+ fixesWereApplied = true;
130
+ } else {
131
+ remainingMessages.push(problem);
132
+ }
133
+ }
134
+ output += text.slice(Math.max(0, lastPos));
135
+
136
+ return {
137
+ fixed: fixesWereApplied,
138
+ messages: remainingMessages.sort(compareMessagesByLocation),
139
+ output
140
+ };
141
+ }
142
+
143
+ debug("No fixes to apply");
144
+ return {
145
+ fixed: false,
146
+ messages,
147
+ output: bom + text
148
+ };
149
+
150
+ };
151
+
152
+ module.exports = SourceCodeFixer;
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/linter/timing.js ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Tracks performance of individual rules.
3
+ * @author Brandon Mills
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //------------------------------------------------------------------------------
9
+ // Helpers
10
+ //------------------------------------------------------------------------------
11
+
12
+ /* c8 ignore next */
13
+ /**
14
+ * Align the string to left
15
+ * @param {string} str string to evaluate
16
+ * @param {int} len length of the string
17
+ * @param {string} ch delimiter character
18
+ * @returns {string} modified string
19
+ * @private
20
+ */
21
+ function alignLeft(str, len, ch) {
22
+ return str + new Array(len - str.length + 1).join(ch || " ");
23
+ }
24
+
25
+ /* c8 ignore next */
26
+ /**
27
+ * Align the string to right
28
+ * @param {string} str string to evaluate
29
+ * @param {int} len length of the string
30
+ * @param {string} ch delimiter character
31
+ * @returns {string} modified string
32
+ * @private
33
+ */
34
+ function alignRight(str, len, ch) {
35
+ return new Array(len - str.length + 1).join(ch || " ") + str;
36
+ }
37
+
38
+ //------------------------------------------------------------------------------
39
+ // Module definition
40
+ //------------------------------------------------------------------------------
41
+
42
+ const enabled = !!process.env.TIMING;
43
+
44
+ const HEADERS = ["Rule", "Time (ms)", "Relative"];
45
+ const ALIGN = [alignLeft, alignRight, alignRight];
46
+
47
+ /**
48
+ * Decide how many rules to show in the output list.
49
+ * @returns {number} the number of rules to show
50
+ */
51
+ function getListSize() {
52
+ const MINIMUM_SIZE = 10;
53
+
54
+ if (typeof process.env.TIMING !== "string") {
55
+ return MINIMUM_SIZE;
56
+ }
57
+
58
+ if (process.env.TIMING.toLowerCase() === "all") {
59
+ return Number.POSITIVE_INFINITY;
60
+ }
61
+
62
+ const TIMING_ENV_VAR_AS_INTEGER = Number.parseInt(process.env.TIMING, 10);
63
+
64
+ return TIMING_ENV_VAR_AS_INTEGER > 10 ? TIMING_ENV_VAR_AS_INTEGER : MINIMUM_SIZE;
65
+ }
66
+
67
+ /* c8 ignore next */
68
+ /**
69
+ * display the data
70
+ * @param {Object} data Data object to be displayed
71
+ * @returns {void} prints modified string with console.log
72
+ * @private
73
+ */
74
+ function display(data) {
75
+ let total = 0;
76
+ const rows = Object.keys(data)
77
+ .map(key => {
78
+ const time = data[key];
79
+
80
+ total += time;
81
+ return [key, time];
82
+ })
83
+ .sort((a, b) => b[1] - a[1])
84
+ .slice(0, getListSize());
85
+
86
+ rows.forEach(row => {
87
+ row.push(`${(row[1] * 100 / total).toFixed(1)}%`);
88
+ row[1] = row[1].toFixed(3);
89
+ });
90
+
91
+ rows.unshift(HEADERS);
92
+
93
+ const widths = [];
94
+
95
+ rows.forEach(row => {
96
+ const len = row.length;
97
+
98
+ for (let i = 0; i < len; i++) {
99
+ const n = row[i].length;
100
+
101
+ if (!widths[i] || n > widths[i]) {
102
+ widths[i] = n;
103
+ }
104
+ }
105
+ });
106
+
107
+ const table = rows.map(row => (
108
+ row
109
+ .map((cell, index) => ALIGN[index](cell, widths[index]))
110
+ .join(" | ")
111
+ ));
112
+
113
+ table.splice(1, 0, widths.map((width, index) => {
114
+ const extraAlignment = index !== 0 && index !== widths.length - 1 ? 2 : 1;
115
+
116
+ return ALIGN[index](":", width + extraAlignment, "-");
117
+ }).join("|"));
118
+
119
+ console.log(table.join("\n")); // eslint-disable-line no-console -- Debugging function
120
+ }
121
+
122
+ /* c8 ignore next */
123
+ module.exports = (function() {
124
+
125
+ const data = Object.create(null);
126
+
127
+ /**
128
+ * Time the run
129
+ * @param {any} key key from the data object
130
+ * @param {Function} fn function to be called
131
+ * @returns {Function} function to be executed
132
+ * @private
133
+ */
134
+ function time(key, fn) {
135
+ if (typeof data[key] === "undefined") {
136
+ data[key] = 0;
137
+ }
138
+
139
+ return function(...args) {
140
+ let t = process.hrtime();
141
+ const result = fn(...args);
142
+
143
+ t = process.hrtime(t);
144
+ data[key] += t[0] * 1e3 + t[1] / 1e6;
145
+ return result;
146
+ };
147
+ }
148
+
149
+ if (enabled) {
150
+ process.on("exit", () => {
151
+ display(data);
152
+ });
153
+ }
154
+
155
+ return {
156
+ time,
157
+ enabled,
158
+ getListSize
159
+ };
160
+
161
+ }());
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/rule-tester/flat-rule-tester.js ADDED
@@ -0,0 +1,1131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Mocha/Jest test wrapper
3
+ * @author Ilya Volodin
4
+ */
5
+ "use strict";
6
+
7
+ /* globals describe, it -- Mocha globals */
8
+
9
+ //------------------------------------------------------------------------------
10
+ // Requirements
11
+ //------------------------------------------------------------------------------
12
+
13
+ const
14
+ assert = require("assert"),
15
+ util = require("util"),
16
+ path = require("path"),
17
+ equal = require("fast-deep-equal"),
18
+ Traverser = require("../shared/traverser"),
19
+ { getRuleOptionsSchema } = require("../config/flat-config-helpers"),
20
+ { Linter, SourceCodeFixer, interpolate } = require("../linter"),
21
+ CodePath = require("../linter/code-path-analysis/code-path");
22
+
23
+ const { FlatConfigArray } = require("../config/flat-config-array");
24
+ const { defaultConfig } = require("../config/default-config");
25
+
26
+ const ajv = require("../shared/ajv")({ strictDefaults: true });
27
+
28
+ const parserSymbol = Symbol.for("eslint.RuleTester.parser");
29
+ const { SourceCode } = require("../source-code");
30
+ const { ConfigArraySymbol } = require("@humanwhocodes/config-array");
31
+
32
+ //------------------------------------------------------------------------------
33
+ // Typedefs
34
+ //------------------------------------------------------------------------------
35
+
36
+ /** @typedef {import("../shared/types").Parser} Parser */
37
+ /** @typedef {import("../shared/types").LanguageOptions} LanguageOptions */
38
+ /** @typedef {import("../shared/types").Rule} Rule */
39
+
40
+
41
+ /**
42
+ * A test case that is expected to pass lint.
43
+ * @typedef {Object} ValidTestCase
44
+ * @property {string} [name] Name for the test case.
45
+ * @property {string} code Code for the test case.
46
+ * @property {any[]} [options] Options for the test case.
47
+ * @property {LanguageOptions} [languageOptions] The language options to use in the test case.
48
+ * @property {{ [name: string]: any }} [settings] Settings for the test case.
49
+ * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames.
50
+ * @property {boolean} [only] Run only this test case or the subset of test cases with this property.
51
+ */
52
+
53
+ /**
54
+ * A test case that is expected to fail lint.
55
+ * @typedef {Object} InvalidTestCase
56
+ * @property {string} [name] Name for the test case.
57
+ * @property {string} code Code for the test case.
58
+ * @property {number | Array<TestCaseError | string | RegExp>} errors Expected errors.
59
+ * @property {string | null} [output] The expected code after autofixes are applied. If set to `null`, the test runner will assert that no autofix is suggested.
60
+ * @property {any[]} [options] Options for the test case.
61
+ * @property {{ [name: string]: any }} [settings] Settings for the test case.
62
+ * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames.
63
+ * @property {LanguageOptions} [languageOptions] The language options to use in the test case.
64
+ * @property {boolean} [only] Run only this test case or the subset of test cases with this property.
65
+ */
66
+
67
+ /**
68
+ * A description of a reported error used in a rule tester test.
69
+ * @typedef {Object} TestCaseError
70
+ * @property {string | RegExp} [message] Message.
71
+ * @property {string} [messageId] Message ID.
72
+ * @property {string} [type] The type of the reported AST node.
73
+ * @property {{ [name: string]: string }} [data] The data used to fill the message template.
74
+ * @property {number} [line] The 1-based line number of the reported start location.
75
+ * @property {number} [column] The 1-based column number of the reported start location.
76
+ * @property {number} [endLine] The 1-based line number of the reported end location.
77
+ * @property {number} [endColumn] The 1-based column number of the reported end location.
78
+ */
79
+
80
+ //------------------------------------------------------------------------------
81
+ // Private Members
82
+ //------------------------------------------------------------------------------
83
+
84
+ /*
85
+ * testerDefaultConfig must not be modified as it allows to reset the tester to
86
+ * the initial default configuration
87
+ */
88
+ const testerDefaultConfig = { rules: {} };
89
+
90
+ /*
91
+ * RuleTester uses this config as its default. This can be overwritten via
92
+ * setDefaultConfig().
93
+ */
94
+ let sharedDefaultConfig = { rules: {} };
95
+
96
+ /*
97
+ * List every parameters possible on a test case that are not related to eslint
98
+ * configuration
99
+ */
100
+ const RuleTesterParameters = [
101
+ "name",
102
+ "code",
103
+ "filename",
104
+ "options",
105
+ "errors",
106
+ "output",
107
+ "only"
108
+ ];
109
+
110
+ /*
111
+ * All allowed property names in error objects.
112
+ */
113
+ const errorObjectParameters = new Set([
114
+ "message",
115
+ "messageId",
116
+ "data",
117
+ "type",
118
+ "line",
119
+ "column",
120
+ "endLine",
121
+ "endColumn",
122
+ "suggestions"
123
+ ]);
124
+ const friendlyErrorObjectParameterList = `[${[...errorObjectParameters].map(key => `'${key}'`).join(", ")}]`;
125
+
126
+ /*
127
+ * All allowed property names in suggestion objects.
128
+ */
129
+ const suggestionObjectParameters = new Set([
130
+ "desc",
131
+ "messageId",
132
+ "data",
133
+ "output"
134
+ ]);
135
+ const friendlySuggestionObjectParameterList = `[${[...suggestionObjectParameters].map(key => `'${key}'`).join(", ")}]`;
136
+
137
+ const forbiddenMethods = [
138
+ "applyInlineConfig",
139
+ "applyLanguageOptions",
140
+ "finalize"
141
+ ];
142
+
143
+ /** @type {Map<string,WeakSet>} */
144
+ const forbiddenMethodCalls = new Map(forbiddenMethods.map(methodName => ([methodName, new WeakSet()])));
145
+
146
+ const hasOwnProperty = Function.call.bind(Object.hasOwnProperty);
147
+
148
+ /**
149
+ * Clones a given value deeply.
150
+ * Note: This ignores `parent` property.
151
+ * @param {any} x A value to clone.
152
+ * @returns {any} A cloned value.
153
+ */
154
+ function cloneDeeplyExcludesParent(x) {
155
+ if (typeof x === "object" && x !== null) {
156
+ if (Array.isArray(x)) {
157
+ return x.map(cloneDeeplyExcludesParent);
158
+ }
159
+
160
+ const retv = {};
161
+
162
+ for (const key in x) {
163
+ if (key !== "parent" && hasOwnProperty(x, key)) {
164
+ retv[key] = cloneDeeplyExcludesParent(x[key]);
165
+ }
166
+ }
167
+
168
+ return retv;
169
+ }
170
+
171
+ return x;
172
+ }
173
+
174
+ /**
175
+ * Freezes a given value deeply.
176
+ * @param {any} x A value to freeze.
177
+ * @returns {void}
178
+ */
179
+ function freezeDeeply(x) {
180
+ if (typeof x === "object" && x !== null) {
181
+ if (Array.isArray(x)) {
182
+ x.forEach(freezeDeeply);
183
+ } else {
184
+ for (const key in x) {
185
+ if (key !== "parent" && hasOwnProperty(x, key)) {
186
+ freezeDeeply(x[key]);
187
+ }
188
+ }
189
+ }
190
+ Object.freeze(x);
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Replace control characters by `\u00xx` form.
196
+ * @param {string} text The text to sanitize.
197
+ * @returns {string} The sanitized text.
198
+ */
199
+ function sanitize(text) {
200
+ if (typeof text !== "string") {
201
+ return "";
202
+ }
203
+ return text.replace(
204
+ /[\u0000-\u0009\u000b-\u001a]/gu, // eslint-disable-line no-control-regex -- Escaping controls
205
+ c => `\\u${c.codePointAt(0).toString(16).padStart(4, "0")}`
206
+ );
207
+ }
208
+
209
+ /**
210
+ * Define `start`/`end` properties as throwing error.
211
+ * @param {string} objName Object name used for error messages.
212
+ * @param {ASTNode} node The node to define.
213
+ * @returns {void}
214
+ */
215
+ function defineStartEndAsError(objName, node) {
216
+ Object.defineProperties(node, {
217
+ start: {
218
+ get() {
219
+ throw new Error(`Use ${objName}.range[0] instead of ${objName}.start`);
220
+ },
221
+ configurable: true,
222
+ enumerable: false
223
+ },
224
+ end: {
225
+ get() {
226
+ throw new Error(`Use ${objName}.range[1] instead of ${objName}.end`);
227
+ },
228
+ configurable: true,
229
+ enumerable: false
230
+ }
231
+ });
232
+ }
233
+
234
+
235
+ /**
236
+ * Define `start`/`end` properties of all nodes of the given AST as throwing error.
237
+ * @param {ASTNode} ast The root node to errorize `start`/`end` properties.
238
+ * @param {Object} [visitorKeys] Visitor keys to be used for traversing the given ast.
239
+ * @returns {void}
240
+ */
241
+ function defineStartEndAsErrorInTree(ast, visitorKeys) {
242
+ Traverser.traverse(ast, { visitorKeys, enter: defineStartEndAsError.bind(null, "node") });
243
+ ast.tokens.forEach(defineStartEndAsError.bind(null, "token"));
244
+ ast.comments.forEach(defineStartEndAsError.bind(null, "token"));
245
+ }
246
+
247
+ /**
248
+ * Wraps the given parser in order to intercept and modify return values from the `parse` and `parseForESLint` methods, for test purposes.
249
+ * In particular, to modify ast nodes, tokens and comments to throw on access to their `start` and `end` properties.
250
+ * @param {Parser} parser Parser object.
251
+ * @returns {Parser} Wrapped parser object.
252
+ */
253
+ function wrapParser(parser) {
254
+
255
+ if (typeof parser.parseForESLint === "function") {
256
+ return {
257
+ [parserSymbol]: parser,
258
+ parseForESLint(...args) {
259
+ const ret = parser.parseForESLint(...args);
260
+
261
+ defineStartEndAsErrorInTree(ret.ast, ret.visitorKeys);
262
+ return ret;
263
+ }
264
+ };
265
+ }
266
+
267
+ return {
268
+ [parserSymbol]: parser,
269
+ parse(...args) {
270
+ const ast = parser.parse(...args);
271
+
272
+ defineStartEndAsErrorInTree(ast);
273
+ return ast;
274
+ }
275
+ };
276
+ }
277
+
278
+ /**
279
+ * Function to replace `SourceCode.prototype.getComments`.
280
+ * @returns {void}
281
+ * @throws {Error} Deprecation message.
282
+ */
283
+ function getCommentsDeprecation() {
284
+ throw new Error(
285
+ "`SourceCode#getComments()` is deprecated and will be removed in a future major version. Use `getCommentsBefore()`, `getCommentsAfter()`, and `getCommentsInside()` instead."
286
+ );
287
+ }
288
+
289
+ /**
290
+ * Emit a deprecation warning if rule uses CodePath#currentSegments.
291
+ * @param {string} ruleName Name of the rule.
292
+ * @returns {void}
293
+ */
294
+ function emitCodePathCurrentSegmentsWarning(ruleName) {
295
+ if (!emitCodePathCurrentSegmentsWarning[`warned-${ruleName}`]) {
296
+ emitCodePathCurrentSegmentsWarning[`warned-${ruleName}`] = true;
297
+ process.emitWarning(
298
+ `"${ruleName}" rule uses CodePath#currentSegments and will stop working in ESLint v9. Please read the documentation for how to update your code: https://eslint.org/docs/latest/extend/code-path-analysis#usage-examples`,
299
+ "DeprecationWarning"
300
+ );
301
+ }
302
+ }
303
+
304
+ /**
305
+ * Function to replace forbidden `SourceCode` methods. Allows just one call per method.
306
+ * @param {string} methodName The name of the method to forbid.
307
+ * @param {Function} prototype The prototype with the original method to call.
308
+ * @returns {Function} The function that throws the error.
309
+ */
310
+ function throwForbiddenMethodError(methodName, prototype) {
311
+
312
+ const original = prototype[methodName];
313
+
314
+ return function(...args) {
315
+
316
+ const called = forbiddenMethodCalls.get(methodName);
317
+
318
+ /* eslint-disable no-invalid-this -- needed to operate as a method. */
319
+ if (!called.has(this)) {
320
+ called.add(this);
321
+
322
+ return original.apply(this, args);
323
+ }
324
+ /* eslint-enable no-invalid-this -- not needed past this point */
325
+
326
+ throw new Error(
327
+ `\`SourceCode#${methodName}()\` cannot be called inside a rule.`
328
+ );
329
+ };
330
+ }
331
+
332
+ //------------------------------------------------------------------------------
333
+ // Public Interface
334
+ //------------------------------------------------------------------------------
335
+
336
+ // default separators for testing
337
+ const DESCRIBE = Symbol("describe");
338
+ const IT = Symbol("it");
339
+ const IT_ONLY = Symbol("itOnly");
340
+
341
+ /**
342
+ * This is `it` default handler if `it` don't exist.
343
+ * @this {Mocha}
344
+ * @param {string} text The description of the test case.
345
+ * @param {Function} method The logic of the test case.
346
+ * @throws {Error} Any error upon execution of `method`.
347
+ * @returns {any} Returned value of `method`.
348
+ */
349
+ function itDefaultHandler(text, method) {
350
+ try {
351
+ return method.call(this);
352
+ } catch (err) {
353
+ if (err instanceof assert.AssertionError) {
354
+ err.message += ` (${util.inspect(err.actual)} ${err.operator} ${util.inspect(err.expected)})`;
355
+ }
356
+ throw err;
357
+ }
358
+ }
359
+
360
+ /**
361
+ * This is `describe` default handler if `describe` don't exist.
362
+ * @this {Mocha}
363
+ * @param {string} text The description of the test case.
364
+ * @param {Function} method The logic of the test case.
365
+ * @returns {any} Returned value of `method`.
366
+ */
367
+ function describeDefaultHandler(text, method) {
368
+ return method.call(this);
369
+ }
370
+
371
+ /**
372
+ * Mocha test wrapper.
373
+ */
374
+ class FlatRuleTester {
375
+
376
+ /**
377
+ * Creates a new instance of RuleTester.
378
+ * @param {Object} [testerConfig] Optional, extra configuration for the tester
379
+ */
380
+ constructor(testerConfig = {}) {
381
+
382
+ /**
383
+ * The configuration to use for this tester. Combination of the tester
384
+ * configuration and the default configuration.
385
+ * @type {Object}
386
+ */
387
+ this.testerConfig = [
388
+ sharedDefaultConfig,
389
+ testerConfig,
390
+ { rules: { "rule-tester/validate-ast": "error" } }
391
+ ];
392
+
393
+ this.linter = new Linter({ configType: "flat" });
394
+ }
395
+
396
+ /**
397
+ * Set the configuration to use for all future tests
398
+ * @param {Object} config the configuration to use.
399
+ * @throws {TypeError} If non-object config.
400
+ * @returns {void}
401
+ */
402
+ static setDefaultConfig(config) {
403
+ if (typeof config !== "object" || config === null) {
404
+ throw new TypeError("FlatRuleTester.setDefaultConfig: config must be an object");
405
+ }
406
+ sharedDefaultConfig = config;
407
+
408
+ // Make sure the rules object exists since it is assumed to exist later
409
+ sharedDefaultConfig.rules = sharedDefaultConfig.rules || {};
410
+ }
411
+
412
+ /**
413
+ * Get the current configuration used for all tests
414
+ * @returns {Object} the current configuration
415
+ */
416
+ static getDefaultConfig() {
417
+ return sharedDefaultConfig;
418
+ }
419
+
420
+ /**
421
+ * Reset the configuration to the initial configuration of the tester removing
422
+ * any changes made until now.
423
+ * @returns {void}
424
+ */
425
+ static resetDefaultConfig() {
426
+ sharedDefaultConfig = {
427
+ rules: {
428
+ ...testerDefaultConfig.rules
429
+ }
430
+ };
431
+ }
432
+
433
+
434
+ /*
435
+ * If people use `mocha test.js --watch` command, `describe` and `it` function
436
+ * instances are different for each execution. So `describe` and `it` should get fresh instance
437
+ * always.
438
+ */
439
+ static get describe() {
440
+ return (
441
+ this[DESCRIBE] ||
442
+ (typeof describe === "function" ? describe : describeDefaultHandler)
443
+ );
444
+ }
445
+
446
+ static set describe(value) {
447
+ this[DESCRIBE] = value;
448
+ }
449
+
450
+ static get it() {
451
+ return (
452
+ this[IT] ||
453
+ (typeof it === "function" ? it : itDefaultHandler)
454
+ );
455
+ }
456
+
457
+ static set it(value) {
458
+ this[IT] = value;
459
+ }
460
+
461
+ /**
462
+ * Adds the `only` property to a test to run it in isolation.
463
+ * @param {string | ValidTestCase | InvalidTestCase} item A single test to run by itself.
464
+ * @returns {ValidTestCase | InvalidTestCase} The test with `only` set.
465
+ */
466
+ static only(item) {
467
+ if (typeof item === "string") {
468
+ return { code: item, only: true };
469
+ }
470
+
471
+ return { ...item, only: true };
472
+ }
473
+
474
+ static get itOnly() {
475
+ if (typeof this[IT_ONLY] === "function") {
476
+ return this[IT_ONLY];
477
+ }
478
+ if (typeof this[IT] === "function" && typeof this[IT].only === "function") {
479
+ return Function.bind.call(this[IT].only, this[IT]);
480
+ }
481
+ if (typeof it === "function" && typeof it.only === "function") {
482
+ return Function.bind.call(it.only, it);
483
+ }
484
+
485
+ if (typeof this[DESCRIBE] === "function" || typeof this[IT] === "function") {
486
+ throw new Error(
487
+ "Set `RuleTester.itOnly` to use `only` with a custom test framework.\n" +
488
+ "See https://eslint.org/docs/latest/integrate/nodejs-api#customizing-ruletester for more."
489
+ );
490
+ }
491
+ if (typeof it === "function") {
492
+ throw new Error("The current test framework does not support exclusive tests with `only`.");
493
+ }
494
+ throw new Error("To use `only`, use RuleTester with a test framework that provides `it.only()` like Mocha.");
495
+ }
496
+
497
+ static set itOnly(value) {
498
+ this[IT_ONLY] = value;
499
+ }
500
+
501
+
502
+ /**
503
+ * Adds a new rule test to execute.
504
+ * @param {string} ruleName The name of the rule to run.
505
+ * @param {Function | Rule} rule The rule to test.
506
+ * @param {{
507
+ * valid: (ValidTestCase | string)[],
508
+ * invalid: InvalidTestCase[]
509
+ * }} test The collection of tests to run.
510
+ * @throws {TypeError|Error} If non-object `test`, or if a required
511
+ * scenario of the given type is missing.
512
+ * @returns {void}
513
+ */
514
+ run(ruleName, rule, test) {
515
+
516
+ const testerConfig = this.testerConfig,
517
+ requiredScenarios = ["valid", "invalid"],
518
+ scenarioErrors = [],
519
+ linter = this.linter,
520
+ ruleId = `rule-to-test/${ruleName}`;
521
+
522
+ if (!test || typeof test !== "object") {
523
+ throw new TypeError(`Test Scenarios for rule ${ruleName} : Could not find test scenario object`);
524
+ }
525
+
526
+ requiredScenarios.forEach(scenarioType => {
527
+ if (!test[scenarioType]) {
528
+ scenarioErrors.push(`Could not find any ${scenarioType} test scenarios`);
529
+ }
530
+ });
531
+
532
+ if (scenarioErrors.length > 0) {
533
+ throw new Error([
534
+ `Test Scenarios for rule ${ruleName} is invalid:`
535
+ ].concat(scenarioErrors).join("\n"));
536
+ }
537
+
538
+ const baseConfig = [
539
+ { files: ["**"] }, // Make sure the default config matches for all files
540
+ {
541
+ plugins: {
542
+
543
+ // copy root plugin over
544
+ "@": {
545
+
546
+ /*
547
+ * Parsers are wrapped to detect more errors, so this needs
548
+ * to be a new object for each call to run(), otherwise the
549
+ * parsers will be wrapped multiple times.
550
+ */
551
+ parsers: {
552
+ ...defaultConfig[0].plugins["@"].parsers
553
+ },
554
+
555
+ /*
556
+ * The rules key on the default plugin is a proxy to lazy-load
557
+ * just the rules that are needed. So, don't create a new object
558
+ * here, just use the default one to keep that performance
559
+ * enhancement.
560
+ */
561
+ rules: defaultConfig[0].plugins["@"].rules
562
+ },
563
+ "rule-to-test": {
564
+ rules: {
565
+ [ruleName]: Object.assign({}, rule, {
566
+
567
+ // Create a wrapper rule that freezes the `context` properties.
568
+ create(context) {
569
+ freezeDeeply(context.options);
570
+ freezeDeeply(context.settings);
571
+ freezeDeeply(context.parserOptions);
572
+
573
+ // freezeDeeply(context.languageOptions);
574
+
575
+ return (typeof rule === "function" ? rule : rule.create)(context);
576
+ }
577
+ })
578
+ }
579
+ }
580
+ },
581
+ languageOptions: {
582
+ ...defaultConfig[0].languageOptions
583
+ }
584
+ },
585
+ ...defaultConfig.slice(1)
586
+ ];
587
+
588
+ /**
589
+ * Run the rule for the given item
590
+ * @param {string|Object} item Item to run the rule against
591
+ * @throws {Error} If an invalid schema.
592
+ * @returns {Object} Eslint run result
593
+ * @private
594
+ */
595
+ function runRuleForItem(item) {
596
+ const flatConfigArrayOptions = {
597
+ baseConfig
598
+ };
599
+
600
+ if (item.filename) {
601
+ flatConfigArrayOptions.basePath = path.parse(item.filename).root;
602
+ }
603
+
604
+ const configs = new FlatConfigArray(testerConfig, flatConfigArrayOptions);
605
+
606
+ /*
607
+ * Modify the returned config so that the parser is wrapped to catch
608
+ * access of the start/end properties. This method is called just
609
+ * once per code snippet being tested, so each test case gets a clean
610
+ * parser.
611
+ */
612
+ configs[ConfigArraySymbol.finalizeConfig] = function(...args) {
613
+
614
+ // can't do super here :(
615
+ const proto = Object.getPrototypeOf(this);
616
+ const calculatedConfig = proto[ConfigArraySymbol.finalizeConfig].apply(this, args);
617
+
618
+ // wrap the parser to catch start/end property access
619
+ calculatedConfig.languageOptions.parser = wrapParser(calculatedConfig.languageOptions.parser);
620
+ return calculatedConfig;
621
+ };
622
+
623
+ let code, filename, output, beforeAST, afterAST;
624
+
625
+ if (typeof item === "string") {
626
+ code = item;
627
+ } else {
628
+ code = item.code;
629
+
630
+ /*
631
+ * Assumes everything on the item is a config except for the
632
+ * parameters used by this tester
633
+ */
634
+ const itemConfig = { ...item };
635
+
636
+ for (const parameter of RuleTesterParameters) {
637
+ delete itemConfig[parameter];
638
+ }
639
+
640
+ // wrap any parsers
641
+ if (itemConfig.languageOptions && itemConfig.languageOptions.parser) {
642
+
643
+ const parser = itemConfig.languageOptions.parser;
644
+
645
+ if (parser && typeof parser !== "object") {
646
+ throw new Error("Parser must be an object with a parse() or parseForESLint() method.");
647
+ }
648
+
649
+ }
650
+
651
+ /*
652
+ * Create the config object from the tester config and this item
653
+ * specific configurations.
654
+ */
655
+ configs.push(itemConfig);
656
+ }
657
+
658
+ if (item.filename) {
659
+ filename = item.filename;
660
+ }
661
+
662
+ let ruleConfig = 1;
663
+
664
+ if (hasOwnProperty(item, "options")) {
665
+ assert(Array.isArray(item.options), "options must be an array");
666
+ ruleConfig = [1, ...item.options];
667
+ }
668
+
669
+ configs.push({
670
+ rules: {
671
+ [ruleId]: ruleConfig
672
+ }
673
+ });
674
+
675
+ const schema = getRuleOptionsSchema(rule);
676
+
677
+ /*
678
+ * Setup AST getters.
679
+ * The goal is to check whether or not AST was modified when
680
+ * running the rule under test.
681
+ */
682
+ configs.push({
683
+ plugins: {
684
+ "rule-tester": {
685
+ rules: {
686
+ "validate-ast": {
687
+ create() {
688
+ return {
689
+ Program(node) {
690
+ beforeAST = cloneDeeplyExcludesParent(node);
691
+ },
692
+ "Program:exit"(node) {
693
+ afterAST = node;
694
+ }
695
+ };
696
+ }
697
+ }
698
+ }
699
+ }
700
+ }
701
+ });
702
+
703
+ if (schema) {
704
+ ajv.validateSchema(schema);
705
+
706
+ if (ajv.errors) {
707
+ const errors = ajv.errors.map(error => {
708
+ const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
709
+
710
+ return `\t${field}: ${error.message}`;
711
+ }).join("\n");
712
+
713
+ throw new Error([`Schema for rule ${ruleName} is invalid:`, errors]);
714
+ }
715
+
716
+ /*
717
+ * `ajv.validateSchema` checks for errors in the structure of the schema (by comparing the schema against a "meta-schema"),
718
+ * and it reports those errors individually. However, there are other types of schema errors that only occur when compiling
719
+ * the schema (e.g. using invalid defaults in a schema), and only one of these errors can be reported at a time. As a result,
720
+ * the schema is compiled here separately from checking for `validateSchema` errors.
721
+ */
722
+ try {
723
+ ajv.compile(schema);
724
+ } catch (err) {
725
+ throw new Error(`Schema for rule ${ruleName} is invalid: ${err.message}`);
726
+ }
727
+ }
728
+
729
+ // check for validation errors
730
+ try {
731
+ configs.normalizeSync();
732
+ configs.getConfig("test.js");
733
+ } catch (error) {
734
+ error.message = `ESLint configuration in rule-tester is invalid: ${error.message}`;
735
+ throw error;
736
+ }
737
+
738
+ // Verify the code.
739
+ const { getComments, applyLanguageOptions, applyInlineConfig, finalize } = SourceCode.prototype;
740
+ const originalCurrentSegments = Object.getOwnPropertyDescriptor(CodePath.prototype, "currentSegments");
741
+ let messages;
742
+
743
+ try {
744
+ SourceCode.prototype.getComments = getCommentsDeprecation;
745
+ Object.defineProperty(CodePath.prototype, "currentSegments", {
746
+ get() {
747
+ emitCodePathCurrentSegmentsWarning(ruleName);
748
+ return originalCurrentSegments.get.call(this);
749
+ }
750
+ });
751
+
752
+ forbiddenMethods.forEach(methodName => {
753
+ SourceCode.prototype[methodName] = throwForbiddenMethodError(methodName, SourceCode.prototype);
754
+ });
755
+
756
+ messages = linter.verify(code, configs, filename);
757
+ } finally {
758
+ SourceCode.prototype.getComments = getComments;
759
+ Object.defineProperty(CodePath.prototype, "currentSegments", originalCurrentSegments);
760
+ SourceCode.prototype.applyInlineConfig = applyInlineConfig;
761
+ SourceCode.prototype.applyLanguageOptions = applyLanguageOptions;
762
+ SourceCode.prototype.finalize = finalize;
763
+ }
764
+
765
+
766
+ const fatalErrorMessage = messages.find(m => m.fatal);
767
+
768
+ assert(!fatalErrorMessage, `A fatal parsing error occurred: ${fatalErrorMessage && fatalErrorMessage.message}`);
769
+
770
+ // Verify if autofix makes a syntax error or not.
771
+ if (messages.some(m => m.fix)) {
772
+ output = SourceCodeFixer.applyFixes(code, messages).output;
773
+ const errorMessageInFix = linter.verify(output, configs, filename).find(m => m.fatal);
774
+
775
+ assert(!errorMessageInFix, [
776
+ "A fatal parsing error occurred in autofix.",
777
+ `Error: ${errorMessageInFix && errorMessageInFix.message}`,
778
+ "Autofix output:",
779
+ output
780
+ ].join("\n"));
781
+ } else {
782
+ output = code;
783
+ }
784
+
785
+ return {
786
+ messages,
787
+ output,
788
+ beforeAST,
789
+ afterAST: cloneDeeplyExcludesParent(afterAST)
790
+ };
791
+ }
792
+
793
+ /**
794
+ * Check if the AST was changed
795
+ * @param {ASTNode} beforeAST AST node before running
796
+ * @param {ASTNode} afterAST AST node after running
797
+ * @returns {void}
798
+ * @private
799
+ */
800
+ function assertASTDidntChange(beforeAST, afterAST) {
801
+ if (!equal(beforeAST, afterAST)) {
802
+ assert.fail("Rule should not modify AST.");
803
+ }
804
+ }
805
+
806
+ /**
807
+ * Check if the template is valid or not
808
+ * all valid cases go through this
809
+ * @param {string|Object} item Item to run the rule against
810
+ * @returns {void}
811
+ * @private
812
+ */
813
+ function testValidTemplate(item) {
814
+ const code = typeof item === "object" ? item.code : item;
815
+
816
+ assert.ok(typeof code === "string", "Test case must specify a string value for 'code'");
817
+ if (item.name) {
818
+ assert.ok(typeof item.name === "string", "Optional test case property 'name' must be a string");
819
+ }
820
+
821
+ const result = runRuleForItem(item);
822
+ const messages = result.messages;
823
+
824
+ assert.strictEqual(messages.length, 0, util.format("Should have no errors but had %d: %s",
825
+ messages.length,
826
+ util.inspect(messages)));
827
+
828
+ assertASTDidntChange(result.beforeAST, result.afterAST);
829
+ }
830
+
831
+ /**
832
+ * Asserts that the message matches its expected value. If the expected
833
+ * value is a regular expression, it is checked against the actual
834
+ * value.
835
+ * @param {string} actual Actual value
836
+ * @param {string|RegExp} expected Expected value
837
+ * @returns {void}
838
+ * @private
839
+ */
840
+ function assertMessageMatches(actual, expected) {
841
+ if (expected instanceof RegExp) {
842
+
843
+ // assert.js doesn't have a built-in RegExp match function
844
+ assert.ok(
845
+ expected.test(actual),
846
+ `Expected '${actual}' to match ${expected}`
847
+ );
848
+ } else {
849
+ assert.strictEqual(actual, expected);
850
+ }
851
+ }
852
+
853
+ /**
854
+ * Check if the template is invalid or not
855
+ * all invalid cases go through this.
856
+ * @param {string|Object} item Item to run the rule against
857
+ * @returns {void}
858
+ * @private
859
+ */
860
+ function testInvalidTemplate(item) {
861
+ assert.ok(typeof item.code === "string", "Test case must specify a string value for 'code'");
862
+ if (item.name) {
863
+ assert.ok(typeof item.name === "string", "Optional test case property 'name' must be a string");
864
+ }
865
+ assert.ok(item.errors || item.errors === 0,
866
+ `Did not specify errors for an invalid test of ${ruleName}`);
867
+
868
+ if (Array.isArray(item.errors) && item.errors.length === 0) {
869
+ assert.fail("Invalid cases must have at least one error");
870
+ }
871
+
872
+ const ruleHasMetaMessages = hasOwnProperty(rule, "meta") && hasOwnProperty(rule.meta, "messages");
873
+ const friendlyIDList = ruleHasMetaMessages ? `[${Object.keys(rule.meta.messages).map(key => `'${key}'`).join(", ")}]` : null;
874
+
875
+ const result = runRuleForItem(item);
876
+ const messages = result.messages;
877
+
878
+ if (typeof item.errors === "number") {
879
+
880
+ if (item.errors === 0) {
881
+ assert.fail("Invalid cases must have 'error' value greater than 0");
882
+ }
883
+
884
+ assert.strictEqual(messages.length, item.errors, util.format("Should have %d error%s but had %d: %s",
885
+ item.errors,
886
+ item.errors === 1 ? "" : "s",
887
+ messages.length,
888
+ util.inspect(messages)));
889
+ } else {
890
+ assert.strictEqual(
891
+ messages.length, item.errors.length, util.format(
892
+ "Should have %d error%s but had %d: %s",
893
+ item.errors.length,
894
+ item.errors.length === 1 ? "" : "s",
895
+ messages.length,
896
+ util.inspect(messages)
897
+ )
898
+ );
899
+
900
+ const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleId);
901
+
902
+ for (let i = 0, l = item.errors.length; i < l; i++) {
903
+ const error = item.errors[i];
904
+ const message = messages[i];
905
+
906
+ assert(hasMessageOfThisRule, "Error rule name should be the same as the name of the rule being tested");
907
+
908
+ if (typeof error === "string" || error instanceof RegExp) {
909
+
910
+ // Just an error message.
911
+ assertMessageMatches(message.message, error);
912
+ } else if (typeof error === "object" && error !== null) {
913
+
914
+ /*
915
+ * Error object.
916
+ * This may have a message, messageId, data, node type, line, and/or
917
+ * column.
918
+ */
919
+
920
+ Object.keys(error).forEach(propertyName => {
921
+ assert.ok(
922
+ errorObjectParameters.has(propertyName),
923
+ `Invalid error property name '${propertyName}'. Expected one of ${friendlyErrorObjectParameterList}.`
924
+ );
925
+ });
926
+
927
+ if (hasOwnProperty(error, "message")) {
928
+ assert.ok(!hasOwnProperty(error, "messageId"), "Error should not specify both 'message' and a 'messageId'.");
929
+ assert.ok(!hasOwnProperty(error, "data"), "Error should not specify both 'data' and 'message'.");
930
+ assertMessageMatches(message.message, error.message);
931
+ } else if (hasOwnProperty(error, "messageId")) {
932
+ assert.ok(
933
+ ruleHasMetaMessages,
934
+ "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'."
935
+ );
936
+ if (!hasOwnProperty(rule.meta.messages, error.messageId)) {
937
+ assert(false, `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`);
938
+ }
939
+ assert.strictEqual(
940
+ message.messageId,
941
+ error.messageId,
942
+ `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.`
943
+ );
944
+ if (hasOwnProperty(error, "data")) {
945
+
946
+ /*
947
+ * if data was provided, then directly compare the returned message to a synthetic
948
+ * interpolated message using the same message ID and data provided in the test.
949
+ * See https://github.com/eslint/eslint/issues/9890 for context.
950
+ */
951
+ const unformattedOriginalMessage = rule.meta.messages[error.messageId];
952
+ const rehydratedMessage = interpolate(unformattedOriginalMessage, error.data);
953
+
954
+ assert.strictEqual(
955
+ message.message,
956
+ rehydratedMessage,
957
+ `Hydrated message "${rehydratedMessage}" does not match "${message.message}"`
958
+ );
959
+ }
960
+ }
961
+
962
+ assert.ok(
963
+ hasOwnProperty(error, "data") ? hasOwnProperty(error, "messageId") : true,
964
+ "Error must specify 'messageId' if 'data' is used."
965
+ );
966
+
967
+ if (error.type) {
968
+ assert.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`);
969
+ }
970
+
971
+ if (hasOwnProperty(error, "line")) {
972
+ assert.strictEqual(message.line, error.line, `Error line should be ${error.line}`);
973
+ }
974
+
975
+ if (hasOwnProperty(error, "column")) {
976
+ assert.strictEqual(message.column, error.column, `Error column should be ${error.column}`);
977
+ }
978
+
979
+ if (hasOwnProperty(error, "endLine")) {
980
+ assert.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`);
981
+ }
982
+
983
+ if (hasOwnProperty(error, "endColumn")) {
984
+ assert.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`);
985
+ }
986
+
987
+ if (hasOwnProperty(error, "suggestions")) {
988
+
989
+ // Support asserting there are no suggestions
990
+ if (!error.suggestions || (Array.isArray(error.suggestions) && error.suggestions.length === 0)) {
991
+ if (Array.isArray(message.suggestions) && message.suggestions.length > 0) {
992
+ assert.fail(`Error should have no suggestions on error with message: "${message.message}"`);
993
+ }
994
+ } else {
995
+ assert.strictEqual(Array.isArray(message.suggestions), true, `Error should have an array of suggestions. Instead received "${message.suggestions}" on error with message: "${message.message}"`);
996
+ assert.strictEqual(message.suggestions.length, error.suggestions.length, `Error should have ${error.suggestions.length} suggestions. Instead found ${message.suggestions.length} suggestions`);
997
+
998
+ error.suggestions.forEach((expectedSuggestion, index) => {
999
+ assert.ok(
1000
+ typeof expectedSuggestion === "object" && expectedSuggestion !== null,
1001
+ "Test suggestion in 'suggestions' array must be an object."
1002
+ );
1003
+ Object.keys(expectedSuggestion).forEach(propertyName => {
1004
+ assert.ok(
1005
+ suggestionObjectParameters.has(propertyName),
1006
+ `Invalid suggestion property name '${propertyName}'. Expected one of ${friendlySuggestionObjectParameterList}.`
1007
+ );
1008
+ });
1009
+
1010
+ const actualSuggestion = message.suggestions[index];
1011
+ const suggestionPrefix = `Error Suggestion at index ${index} :`;
1012
+
1013
+ if (hasOwnProperty(expectedSuggestion, "desc")) {
1014
+ assert.ok(
1015
+ !hasOwnProperty(expectedSuggestion, "data"),
1016
+ `${suggestionPrefix} Test should not specify both 'desc' and 'data'.`
1017
+ );
1018
+ assert.strictEqual(
1019
+ actualSuggestion.desc,
1020
+ expectedSuggestion.desc,
1021
+ `${suggestionPrefix} desc should be "${expectedSuggestion.desc}" but got "${actualSuggestion.desc}" instead.`
1022
+ );
1023
+ }
1024
+
1025
+ if (hasOwnProperty(expectedSuggestion, "messageId")) {
1026
+ assert.ok(
1027
+ ruleHasMetaMessages,
1028
+ `${suggestionPrefix} Test can not use 'messageId' if rule under test doesn't define 'meta.messages'.`
1029
+ );
1030
+ assert.ok(
1031
+ hasOwnProperty(rule.meta.messages, expectedSuggestion.messageId),
1032
+ `${suggestionPrefix} Test has invalid messageId '${expectedSuggestion.messageId}', the rule under test allows only one of ${friendlyIDList}.`
1033
+ );
1034
+ assert.strictEqual(
1035
+ actualSuggestion.messageId,
1036
+ expectedSuggestion.messageId,
1037
+ `${suggestionPrefix} messageId should be '${expectedSuggestion.messageId}' but got '${actualSuggestion.messageId}' instead.`
1038
+ );
1039
+ if (hasOwnProperty(expectedSuggestion, "data")) {
1040
+ const unformattedMetaMessage = rule.meta.messages[expectedSuggestion.messageId];
1041
+ const rehydratedDesc = interpolate(unformattedMetaMessage, expectedSuggestion.data);
1042
+
1043
+ assert.strictEqual(
1044
+ actualSuggestion.desc,
1045
+ rehydratedDesc,
1046
+ `${suggestionPrefix} Hydrated test desc "${rehydratedDesc}" does not match received desc "${actualSuggestion.desc}".`
1047
+ );
1048
+ }
1049
+ } else {
1050
+ assert.ok(
1051
+ !hasOwnProperty(expectedSuggestion, "data"),
1052
+ `${suggestionPrefix} Test must specify 'messageId' if 'data' is used.`
1053
+ );
1054
+ }
1055
+
1056
+ if (hasOwnProperty(expectedSuggestion, "output")) {
1057
+ const codeWithAppliedSuggestion = SourceCodeFixer.applyFixes(item.code, [actualSuggestion]).output;
1058
+
1059
+ assert.strictEqual(codeWithAppliedSuggestion, expectedSuggestion.output, `Expected the applied suggestion fix to match the test suggestion output for suggestion at index: ${index} on error with message: "${message.message}"`);
1060
+ }
1061
+ });
1062
+ }
1063
+ }
1064
+ } else {
1065
+
1066
+ // Message was an unexpected type
1067
+ assert.fail(`Error should be a string, object, or RegExp, but found (${util.inspect(message)})`);
1068
+ }
1069
+ }
1070
+ }
1071
+
1072
+ if (hasOwnProperty(item, "output")) {
1073
+ if (item.output === null) {
1074
+ assert.strictEqual(
1075
+ result.output,
1076
+ item.code,
1077
+ "Expected no autofixes to be suggested"
1078
+ );
1079
+ } else {
1080
+ assert.strictEqual(result.output, item.output, "Output is incorrect.");
1081
+ }
1082
+ } else {
1083
+ assert.strictEqual(
1084
+ result.output,
1085
+ item.code,
1086
+ "The rule fixed the code. Please add 'output' property."
1087
+ );
1088
+ }
1089
+
1090
+ assertASTDidntChange(result.beforeAST, result.afterAST);
1091
+ }
1092
+
1093
+ /*
1094
+ * This creates a mocha test suite and pipes all supplied info through
1095
+ * one of the templates above.
1096
+ * The test suites for valid/invalid are created conditionally as
1097
+ * test runners (eg. vitest) fail for empty test suites.
1098
+ */
1099
+ this.constructor.describe(ruleName, () => {
1100
+ if (test.valid.length > 0) {
1101
+ this.constructor.describe("valid", () => {
1102
+ test.valid.forEach(valid => {
1103
+ this.constructor[valid.only ? "itOnly" : "it"](
1104
+ sanitize(typeof valid === "object" ? valid.name || valid.code : valid),
1105
+ () => {
1106
+ testValidTemplate(valid);
1107
+ }
1108
+ );
1109
+ });
1110
+ });
1111
+ }
1112
+
1113
+ if (test.invalid.length > 0) {
1114
+ this.constructor.describe("invalid", () => {
1115
+ test.invalid.forEach(invalid => {
1116
+ this.constructor[invalid.only ? "itOnly" : "it"](
1117
+ sanitize(invalid.name || invalid.code),
1118
+ () => {
1119
+ testInvalidTemplate(invalid);
1120
+ }
1121
+ );
1122
+ });
1123
+ });
1124
+ }
1125
+ });
1126
+ }
1127
+ }
1128
+
1129
+ FlatRuleTester[DESCRIBE] = FlatRuleTester[IT] = FlatRuleTester[IT_ONLY] = null;
1130
+
1131
+ module.exports = FlatRuleTester;
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/rule-tester/index.js ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ "use strict";
2
+
3
+ module.exports = {
4
+ RuleTester: require("./rule-tester")
5
+ };
novas/novacore-zephyr/groq-code-cli/node_modules/eslint/lib/rule-tester/rule-tester.js ADDED
@@ -0,0 +1,1206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @fileoverview Mocha test wrapper
3
+ * @author Ilya Volodin
4
+ */
5
+ "use strict";
6
+
7
+ /* globals describe, it -- Mocha globals */
8
+
9
+ /*
10
+ * This is a wrapper around mocha to allow for DRY unittests for eslint
11
+ * Format:
12
+ * RuleTester.run("{ruleName}", {
13
+ * valid: [
14
+ * "{code}",
15
+ * { code: "{code}", options: {options}, globals: {globals}, parser: "{parser}", settings: {settings} }
16
+ * ],
17
+ * invalid: [
18
+ * { code: "{code}", errors: {numErrors} },
19
+ * { code: "{code}", errors: ["{errorMessage}"] },
20
+ * { code: "{code}", options: {options}, globals: {globals}, parser: "{parser}", settings: {settings}, errors: [{ message: "{errorMessage}", type: "{errorNodeType}"}] }
21
+ * ]
22
+ * });
23
+ *
24
+ * Variables:
25
+ * {code} - String that represents the code to be tested
26
+ * {options} - Arguments that are passed to the configurable rules.
27
+ * {globals} - An object representing a list of variables that are
28
+ * registered as globals
29
+ * {parser} - String representing the parser to use
30
+ * {settings} - An object representing global settings for all rules
31
+ * {numErrors} - If failing case doesn't need to check error message,
32
+ * this integer will specify how many errors should be
33
+ * received
34
+ * {errorMessage} - Message that is returned by the rule on failure
35
+ * {errorNodeType} - AST node type that is returned by they rule as
36
+ * a cause of the failure.
37
+ */
38
+
39
+ //------------------------------------------------------------------------------
40
+ // Requirements
41
+ //------------------------------------------------------------------------------
42
+
43
+ const
44
+ assert = require("assert"),
45
+ path = require("path"),
46
+ util = require("util"),
47
+ merge = require("lodash.merge"),
48
+ equal = require("fast-deep-equal"),
49
+ Traverser = require("../../lib/shared/traverser"),
50
+ { getRuleOptionsSchema, validate } = require("../shared/config-validator"),
51
+ { Linter, SourceCodeFixer, interpolate } = require("../linter"),
52
+ CodePath = require("../linter/code-path-analysis/code-path");
53
+
54
+ const ajv = require("../shared/ajv")({ strictDefaults: true });
55
+
56
+ const espreePath = require.resolve("espree");
57
+ const parserSymbol = Symbol.for("eslint.RuleTester.parser");
58
+
59
+ const { SourceCode } = require("../source-code");
60
+
61
+ //------------------------------------------------------------------------------
62
+ // Typedefs
63
+ //------------------------------------------------------------------------------
64
+
65
+ /** @typedef {import("../shared/types").Parser} Parser */
66
+ /** @typedef {import("../shared/types").Rule} Rule */
67
+
68
+
69
+ /**
70
+ * A test case that is expected to pass lint.
71
+ * @typedef {Object} ValidTestCase
72
+ * @property {string} [name] Name for the test case.
73
+ * @property {string} code Code for the test case.
74
+ * @property {any[]} [options] Options for the test case.
75
+ * @property {{ [name: string]: any }} [settings] Settings for the test case.
76
+ * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames.
77
+ * @property {string} [parser] The absolute path for the parser.
78
+ * @property {{ [name: string]: any }} [parserOptions] Options for the parser.
79
+ * @property {{ [name: string]: "readonly" | "writable" | "off" }} [globals] The additional global variables.
80
+ * @property {{ [name: string]: boolean }} [env] Environments for the test case.
81
+ * @property {boolean} [only] Run only this test case or the subset of test cases with this property.
82
+ */
83
+
84
+ /**
85
+ * A test case that is expected to fail lint.
86
+ * @typedef {Object} InvalidTestCase
87
+ * @property {string} [name] Name for the test case.
88
+ * @property {string} code Code for the test case.
89
+ * @property {number | Array<TestCaseError | string | RegExp>} errors Expected errors.
90
+ * @property {string | null} [output] The expected code after autofixes are applied. If set to `null`, the test runner will assert that no autofix is suggested.
91
+ * @property {any[]} [options] Options for the test case.
92
+ * @property {{ [name: string]: any }} [settings] Settings for the test case.
93
+ * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames.
94
+ * @property {string} [parser] The absolute path for the parser.
95
+ * @property {{ [name: string]: any }} [parserOptions] Options for the parser.
96
+ * @property {{ [name: string]: "readonly" | "writable" | "off" }} [globals] The additional global variables.
97
+ * @property {{ [name: string]: boolean }} [env] Environments for the test case.
98
+ * @property {boolean} [only] Run only this test case or the subset of test cases with this property.
99
+ */
100
+
101
+ /**
102
+ * A description of a reported error used in a rule tester test.
103
+ * @typedef {Object} TestCaseError
104
+ * @property {string | RegExp} [message] Message.
105
+ * @property {string} [messageId] Message ID.
106
+ * @property {string} [type] The type of the reported AST node.
107
+ * @property {{ [name: string]: string }} [data] The data used to fill the message template.
108
+ * @property {number} [line] The 1-based line number of the reported start location.
109
+ * @property {number} [column] The 1-based column number of the reported start location.
110
+ * @property {number} [endLine] The 1-based line number of the reported end location.
111
+ * @property {number} [endColumn] The 1-based column number of the reported end location.
112
+ */
113
+
114
+ //------------------------------------------------------------------------------
115
+ // Private Members
116
+ //------------------------------------------------------------------------------
117
+
118
+ /*
119
+ * testerDefaultConfig must not be modified as it allows to reset the tester to
120
+ * the initial default configuration
121
+ */
122
+ const testerDefaultConfig = { rules: {} };
123
+ let defaultConfig = { rules: {} };
124
+
125
+ /*
126
+ * List every parameters possible on a test case that are not related to eslint
127
+ * configuration
128
+ */
129
+ const RuleTesterParameters = [
130
+ "name",
131
+ "code",
132
+ "filename",
133
+ "options",
134
+ "errors",
135
+ "output",
136
+ "only"
137
+ ];
138
+
139
+ /*
140
+ * All allowed property names in error objects.
141
+ */
142
+ const errorObjectParameters = new Set([
143
+ "message",
144
+ "messageId",
145
+ "data",
146
+ "type",
147
+ "line",
148
+ "column",
149
+ "endLine",
150
+ "endColumn",
151
+ "suggestions"
152
+ ]);
153
+ const friendlyErrorObjectParameterList = `[${[...errorObjectParameters].map(key => `'${key}'`).join(", ")}]`;
154
+
155
+ /*
156
+ * All allowed property names in suggestion objects.
157
+ */
158
+ const suggestionObjectParameters = new Set([
159
+ "desc",
160
+ "messageId",
161
+ "data",
162
+ "output"
163
+ ]);
164
+ const friendlySuggestionObjectParameterList = `[${[...suggestionObjectParameters].map(key => `'${key}'`).join(", ")}]`;
165
+
166
+ const forbiddenMethods = [
167
+ "applyInlineConfig",
168
+ "applyLanguageOptions",
169
+ "finalize"
170
+ ];
171
+
172
+ const hasOwnProperty = Function.call.bind(Object.hasOwnProperty);
173
+
174
+ const DEPRECATED_SOURCECODE_PASSTHROUGHS = {
175
+ getSource: "getText",
176
+ getSourceLines: "getLines",
177
+ getAllComments: "getAllComments",
178
+ getNodeByRangeIndex: "getNodeByRangeIndex",
179
+
180
+ // getComments: "getComments", -- already handled by a separate error
181
+ getCommentsBefore: "getCommentsBefore",
182
+ getCommentsAfter: "getCommentsAfter",
183
+ getCommentsInside: "getCommentsInside",
184
+ getJSDocComment: "getJSDocComment",
185
+ getFirstToken: "getFirstToken",
186
+ getFirstTokens: "getFirstTokens",
187
+ getLastToken: "getLastToken",
188
+ getLastTokens: "getLastTokens",
189
+ getTokenAfter: "getTokenAfter",
190
+ getTokenBefore: "getTokenBefore",
191
+ getTokenByRangeStart: "getTokenByRangeStart",
192
+ getTokens: "getTokens",
193
+ getTokensAfter: "getTokensAfter",
194
+ getTokensBefore: "getTokensBefore",
195
+ getTokensBetween: "getTokensBetween",
196
+
197
+ getScope: "getScope",
198
+ getAncestors: "getAncestors",
199
+ getDeclaredVariables: "getDeclaredVariables",
200
+ markVariableAsUsed: "markVariableAsUsed"
201
+ };
202
+
203
+ /**
204
+ * Clones a given value deeply.
205
+ * Note: This ignores `parent` property.
206
+ * @param {any} x A value to clone.
207
+ * @returns {any} A cloned value.
208
+ */
209
+ function cloneDeeplyExcludesParent(x) {
210
+ if (typeof x === "object" && x !== null) {
211
+ if (Array.isArray(x)) {
212
+ return x.map(cloneDeeplyExcludesParent);
213
+ }
214
+
215
+ const retv = {};
216
+
217
+ for (const key in x) {
218
+ if (key !== "parent" && hasOwnProperty(x, key)) {
219
+ retv[key] = cloneDeeplyExcludesParent(x[key]);
220
+ }
221
+ }
222
+
223
+ return retv;
224
+ }
225
+
226
+ return x;
227
+ }
228
+
229
+ /**
230
+ * Freezes a given value deeply.
231
+ * @param {any} x A value to freeze.
232
+ * @returns {void}
233
+ */
234
+ function freezeDeeply(x) {
235
+ if (typeof x === "object" && x !== null) {
236
+ if (Array.isArray(x)) {
237
+ x.forEach(freezeDeeply);
238
+ } else {
239
+ for (const key in x) {
240
+ if (key !== "parent" && hasOwnProperty(x, key)) {
241
+ freezeDeeply(x[key]);
242
+ }
243
+ }
244
+ }
245
+ Object.freeze(x);
246
+ }
247
+ }
248
+
249
+ /**
250
+ * Replace control characters by `\u00xx` form.
251
+ * @param {string} text The text to sanitize.
252
+ * @returns {string} The sanitized text.
253
+ */
254
+ function sanitize(text) {
255
+ if (typeof text !== "string") {
256
+ return "";
257
+ }
258
+ return text.replace(
259
+ /[\u0000-\u0009\u000b-\u001a]/gu, // eslint-disable-line no-control-regex -- Escaping controls
260
+ c => `\\u${c.codePointAt(0).toString(16).padStart(4, "0")}`
261
+ );
262
+ }
263
+
264
+ /**
265
+ * Define `start`/`end` properties as throwing error.
266
+ * @param {string} objName Object name used for error messages.
267
+ * @param {ASTNode} node The node to define.
268
+ * @returns {void}
269
+ */
270
+ function defineStartEndAsError(objName, node) {
271
+ Object.defineProperties(node, {
272
+ start: {
273
+ get() {
274
+ throw new Error(`Use ${objName}.range[0] instead of ${objName}.start`);
275
+ },
276
+ configurable: true,
277
+ enumerable: false
278
+ },
279
+ end: {
280
+ get() {
281
+ throw new Error(`Use ${objName}.range[1] instead of ${objName}.end`);
282
+ },
283
+ configurable: true,
284
+ enumerable: false
285
+ }
286
+ });
287
+ }
288
+
289
+
290
+ /**
291
+ * Define `start`/`end` properties of all nodes of the given AST as throwing error.
292
+ * @param {ASTNode} ast The root node to errorize `start`/`end` properties.
293
+ * @param {Object} [visitorKeys] Visitor keys to be used for traversing the given ast.
294
+ * @returns {void}
295
+ */
296
+ function defineStartEndAsErrorInTree(ast, visitorKeys) {
297
+ Traverser.traverse(ast, { visitorKeys, enter: defineStartEndAsError.bind(null, "node") });
298
+ ast.tokens.forEach(defineStartEndAsError.bind(null, "token"));
299
+ ast.comments.forEach(defineStartEndAsError.bind(null, "token"));
300
+ }
301
+
302
+ /**
303
+ * Wraps the given parser in order to intercept and modify return values from the `parse` and `parseForESLint` methods, for test purposes.
304
+ * In particular, to modify ast nodes, tokens and comments to throw on access to their `start` and `end` properties.
305
+ * @param {Parser} parser Parser object.
306
+ * @returns {Parser} Wrapped parser object.
307
+ */
308
+ function wrapParser(parser) {
309
+
310
+ if (typeof parser.parseForESLint === "function") {
311
+ return {
312
+ [parserSymbol]: parser,
313
+ parseForESLint(...args) {
314
+ const ret = parser.parseForESLint(...args);
315
+
316
+ defineStartEndAsErrorInTree(ret.ast, ret.visitorKeys);
317
+ return ret;
318
+ }
319
+ };
320
+ }
321
+
322
+ return {
323
+ [parserSymbol]: parser,
324
+ parse(...args) {
325
+ const ast = parser.parse(...args);
326
+
327
+ defineStartEndAsErrorInTree(ast);
328
+ return ast;
329
+ }
330
+ };
331
+ }
332
+
333
+ /**
334
+ * Function to replace `SourceCode.prototype.getComments`.
335
+ * @returns {void}
336
+ * @throws {Error} Deprecation message.
337
+ */
338
+ function getCommentsDeprecation() {
339
+ throw new Error(
340
+ "`SourceCode#getComments()` is deprecated and will be removed in a future major version. Use `getCommentsBefore()`, `getCommentsAfter()`, and `getCommentsInside()` instead."
341
+ );
342
+ }
343
+
344
+ /**
345
+ * Function to replace forbidden `SourceCode` methods.
346
+ * @param {string} methodName The name of the method to forbid.
347
+ * @returns {Function} The function that throws the error.
348
+ */
349
+ function throwForbiddenMethodError(methodName) {
350
+ return () => {
351
+ throw new Error(
352
+ `\`SourceCode#${methodName}()\` cannot be called inside a rule.`
353
+ );
354
+ };
355
+ }
356
+
357
+ /**
358
+ * Emit a deprecation warning if function-style format is being used.
359
+ * @param {string} ruleName Name of the rule.
360
+ * @returns {void}
361
+ */
362
+ function emitLegacyRuleAPIWarning(ruleName) {
363
+ if (!emitLegacyRuleAPIWarning[`warned-${ruleName}`]) {
364
+ emitLegacyRuleAPIWarning[`warned-${ruleName}`] = true;
365
+ process.emitWarning(
366
+ `"${ruleName}" rule is using the deprecated function-style format and will stop working in ESLint v9. Please use object-style format: https://eslint.org/docs/latest/extend/custom-rules`,
367
+ "DeprecationWarning"
368
+ );
369
+ }
370
+ }
371
+
372
+ /**
373
+ * Emit a deprecation warning if rule has options but is missing the "meta.schema" property
374
+ * @param {string} ruleName Name of the rule.
375
+ * @returns {void}
376
+ */
377
+ function emitMissingSchemaWarning(ruleName) {
378
+ if (!emitMissingSchemaWarning[`warned-${ruleName}`]) {
379
+ emitMissingSchemaWarning[`warned-${ruleName}`] = true;
380
+ process.emitWarning(
381
+ `"${ruleName}" rule has options but is missing the "meta.schema" property and will stop working in ESLint v9. Please add a schema: https://eslint.org/docs/latest/extend/custom-rules#options-schemas`,
382
+ "DeprecationWarning"
383
+ );
384
+ }
385
+ }
386
+
387
+ /**
388
+ * Emit a deprecation warning if a rule uses a deprecated `context` method.
389
+ * @param {string} ruleName Name of the rule.
390
+ * @param {string} methodName The name of the method on `context` that was used.
391
+ * @returns {void}
392
+ */
393
+ function emitDeprecatedContextMethodWarning(ruleName, methodName) {
394
+ if (!emitDeprecatedContextMethodWarning[`warned-${ruleName}-${methodName}`]) {
395
+ emitDeprecatedContextMethodWarning[`warned-${ruleName}-${methodName}`] = true;
396
+ process.emitWarning(
397
+ `"${ruleName}" rule is using \`context.${methodName}()\`, which is deprecated and will be removed in ESLint v9. Please use \`sourceCode.${DEPRECATED_SOURCECODE_PASSTHROUGHS[methodName]}()\` instead.`,
398
+ "DeprecationWarning"
399
+ );
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Emit a deprecation warning if rule uses CodePath#currentSegments.
405
+ * @param {string} ruleName Name of the rule.
406
+ * @returns {void}
407
+ */
408
+ function emitCodePathCurrentSegmentsWarning(ruleName) {
409
+ if (!emitCodePathCurrentSegmentsWarning[`warned-${ruleName}`]) {
410
+ emitCodePathCurrentSegmentsWarning[`warned-${ruleName}`] = true;
411
+ process.emitWarning(
412
+ `"${ruleName}" rule uses CodePath#currentSegments and will stop working in ESLint v9. Please read the documentation for how to update your code: https://eslint.org/docs/latest/extend/code-path-analysis#usage-examples`,
413
+ "DeprecationWarning"
414
+ );
415
+ }
416
+ }
417
+
418
+ /**
419
+ * Emit a deprecation warning if `context.parserServices` is used.
420
+ * @param {string} ruleName Name of the rule.
421
+ * @returns {void}
422
+ */
423
+ function emitParserServicesWarning(ruleName) {
424
+ if (!emitParserServicesWarning[`warned-${ruleName}`]) {
425
+ emitParserServicesWarning[`warned-${ruleName}`] = true;
426
+ process.emitWarning(
427
+ `"${ruleName}" rule is using \`context.parserServices\`, which is deprecated and will be removed in ESLint v9. Please use \`sourceCode.parserServices\` instead.`,
428
+ "DeprecationWarning"
429
+ );
430
+ }
431
+ }
432
+
433
+
434
+ //------------------------------------------------------------------------------
435
+ // Public Interface
436
+ //------------------------------------------------------------------------------
437
+
438
+ // default separators for testing
439
+ const DESCRIBE = Symbol("describe");
440
+ const IT = Symbol("it");
441
+ const IT_ONLY = Symbol("itOnly");
442
+
443
+ /**
444
+ * This is `it` default handler if `it` don't exist.
445
+ * @this {Mocha}
446
+ * @param {string} text The description of the test case.
447
+ * @param {Function} method The logic of the test case.
448
+ * @throws {Error} Any error upon execution of `method`.
449
+ * @returns {any} Returned value of `method`.
450
+ */
451
+ function itDefaultHandler(text, method) {
452
+ try {
453
+ return method.call(this);
454
+ } catch (err) {
455
+ if (err instanceof assert.AssertionError) {
456
+ err.message += ` (${util.inspect(err.actual)} ${err.operator} ${util.inspect(err.expected)})`;
457
+ }
458
+ throw err;
459
+ }
460
+ }
461
+
462
+ /**
463
+ * This is `describe` default handler if `describe` don't exist.
464
+ * @this {Mocha}
465
+ * @param {string} text The description of the test case.
466
+ * @param {Function} method The logic of the test case.
467
+ * @returns {any} Returned value of `method`.
468
+ */
469
+ function describeDefaultHandler(text, method) {
470
+ return method.call(this);
471
+ }
472
+
473
+ /**
474
+ * Mocha test wrapper.
475
+ */
476
+ class RuleTester {
477
+
478
+ /**
479
+ * Creates a new instance of RuleTester.
480
+ * @param {Object} [testerConfig] Optional, extra configuration for the tester
481
+ */
482
+ constructor(testerConfig) {
483
+
484
+ /**
485
+ * The configuration to use for this tester. Combination of the tester
486
+ * configuration and the default configuration.
487
+ * @type {Object}
488
+ */
489
+ this.testerConfig = merge(
490
+ {},
491
+ defaultConfig,
492
+ testerConfig,
493
+ { rules: { "rule-tester/validate-ast": "error" } }
494
+ );
495
+
496
+ /**
497
+ * Rule definitions to define before tests.
498
+ * @type {Object}
499
+ */
500
+ this.rules = {};
501
+ this.linter = new Linter();
502
+ }
503
+
504
+ /**
505
+ * Set the configuration to use for all future tests
506
+ * @param {Object} config the configuration to use.
507
+ * @throws {TypeError} If non-object config.
508
+ * @returns {void}
509
+ */
510
+ static setDefaultConfig(config) {
511
+ if (typeof config !== "object" || config === null) {
512
+ throw new TypeError("RuleTester.setDefaultConfig: config must be an object");
513
+ }
514
+ defaultConfig = config;
515
+
516
+ // Make sure the rules object exists since it is assumed to exist later
517
+ defaultConfig.rules = defaultConfig.rules || {};
518
+ }
519
+
520
+ /**
521
+ * Get the current configuration used for all tests
522
+ * @returns {Object} the current configuration
523
+ */
524
+ static getDefaultConfig() {
525
+ return defaultConfig;
526
+ }
527
+
528
+ /**
529
+ * Reset the configuration to the initial configuration of the tester removing
530
+ * any changes made until now.
531
+ * @returns {void}
532
+ */
533
+ static resetDefaultConfig() {
534
+ defaultConfig = merge({}, testerDefaultConfig);
535
+ }
536
+
537
+
538
+ /*
539
+ * If people use `mocha test.js --watch` command, `describe` and `it` function
540
+ * instances are different for each execution. So `describe` and `it` should get fresh instance
541
+ * always.
542
+ */
543
+ static get describe() {
544
+ return (
545
+ this[DESCRIBE] ||
546
+ (typeof describe === "function" ? describe : describeDefaultHandler)
547
+ );
548
+ }
549
+
550
+ static set describe(value) {
551
+ this[DESCRIBE] = value;
552
+ }
553
+
554
+ static get it() {
555
+ return (
556
+ this[IT] ||
557
+ (typeof it === "function" ? it : itDefaultHandler)
558
+ );
559
+ }
560
+
561
+ static set it(value) {
562
+ this[IT] = value;
563
+ }
564
+
565
+ /**
566
+ * Adds the `only` property to a test to run it in isolation.
567
+ * @param {string | ValidTestCase | InvalidTestCase} item A single test to run by itself.
568
+ * @returns {ValidTestCase | InvalidTestCase} The test with `only` set.
569
+ */
570
+ static only(item) {
571
+ if (typeof item === "string") {
572
+ return { code: item, only: true };
573
+ }
574
+
575
+ return { ...item, only: true };
576
+ }
577
+
578
+ static get itOnly() {
579
+ if (typeof this[IT_ONLY] === "function") {
580
+ return this[IT_ONLY];
581
+ }
582
+ if (typeof this[IT] === "function" && typeof this[IT].only === "function") {
583
+ return Function.bind.call(this[IT].only, this[IT]);
584
+ }
585
+ if (typeof it === "function" && typeof it.only === "function") {
586
+ return Function.bind.call(it.only, it);
587
+ }
588
+
589
+ if (typeof this[DESCRIBE] === "function" || typeof this[IT] === "function") {
590
+ throw new Error(
591
+ "Set `RuleTester.itOnly` to use `only` with a custom test framework.\n" +
592
+ "See https://eslint.org/docs/latest/integrate/nodejs-api#customizing-ruletester for more."
593
+ );
594
+ }
595
+ if (typeof it === "function") {
596
+ throw new Error("The current test framework does not support exclusive tests with `only`.");
597
+ }
598
+ throw new Error("To use `only`, use RuleTester with a test framework that provides `it.only()` like Mocha.");
599
+ }
600
+
601
+ static set itOnly(value) {
602
+ this[IT_ONLY] = value;
603
+ }
604
+
605
+ /**
606
+ * Define a rule for one particular run of tests.
607
+ * @param {string} name The name of the rule to define.
608
+ * @param {Function | Rule} rule The rule definition.
609
+ * @returns {void}
610
+ */
611
+ defineRule(name, rule) {
612
+ if (typeof rule === "function") {
613
+ emitLegacyRuleAPIWarning(name);
614
+ }
615
+ this.rules[name] = rule;
616
+ }
617
+
618
+ /**
619
+ * Adds a new rule test to execute.
620
+ * @param {string} ruleName The name of the rule to run.
621
+ * @param {Function | Rule} rule The rule to test.
622
+ * @param {{
623
+ * valid: (ValidTestCase | string)[],
624
+ * invalid: InvalidTestCase[]
625
+ * }} test The collection of tests to run.
626
+ * @throws {TypeError|Error} If non-object `test`, or if a required
627
+ * scenario of the given type is missing.
628
+ * @returns {void}
629
+ */
630
+ run(ruleName, rule, test) {
631
+
632
+ const testerConfig = this.testerConfig,
633
+ requiredScenarios = ["valid", "invalid"],
634
+ scenarioErrors = [],
635
+ linter = this.linter;
636
+
637
+ if (!test || typeof test !== "object") {
638
+ throw new TypeError(`Test Scenarios for rule ${ruleName} : Could not find test scenario object`);
639
+ }
640
+
641
+ requiredScenarios.forEach(scenarioType => {
642
+ if (!test[scenarioType]) {
643
+ scenarioErrors.push(`Could not find any ${scenarioType} test scenarios`);
644
+ }
645
+ });
646
+
647
+ if (scenarioErrors.length > 0) {
648
+ throw new Error([
649
+ `Test Scenarios for rule ${ruleName} is invalid:`
650
+ ].concat(scenarioErrors).join("\n"));
651
+ }
652
+
653
+ if (typeof rule === "function") {
654
+ emitLegacyRuleAPIWarning(ruleName);
655
+ }
656
+
657
+ linter.defineRule(ruleName, Object.assign({}, rule, {
658
+
659
+ // Create a wrapper rule that freezes the `context` properties.
660
+ create(context) {
661
+ freezeDeeply(context.options);
662
+ freezeDeeply(context.settings);
663
+ freezeDeeply(context.parserOptions);
664
+
665
+ // wrap all deprecated methods
666
+ const newContext = Object.create(
667
+ context,
668
+ Object.fromEntries(Object.keys(DEPRECATED_SOURCECODE_PASSTHROUGHS).map(methodName => [
669
+ methodName,
670
+ {
671
+ value(...args) {
672
+
673
+ // emit deprecation warning
674
+ emitDeprecatedContextMethodWarning(ruleName, methodName);
675
+
676
+ // call the original method
677
+ return context[methodName].call(this, ...args);
678
+ },
679
+ enumerable: true
680
+ }
681
+ ]))
682
+ );
683
+
684
+ // emit warning about context.parserServices
685
+ const parserServices = context.parserServices;
686
+
687
+ Object.defineProperty(newContext, "parserServices", {
688
+ get() {
689
+ emitParserServicesWarning(ruleName);
690
+ return parserServices;
691
+ }
692
+ });
693
+
694
+ Object.freeze(newContext);
695
+
696
+ return (typeof rule === "function" ? rule : rule.create)(newContext);
697
+ }
698
+ }));
699
+
700
+ linter.defineRules(this.rules);
701
+
702
+ /**
703
+ * Run the rule for the given item
704
+ * @param {string|Object} item Item to run the rule against
705
+ * @throws {Error} If an invalid schema.
706
+ * @returns {Object} Eslint run result
707
+ * @private
708
+ */
709
+ function runRuleForItem(item) {
710
+ let config = merge({}, testerConfig),
711
+ code, filename, output, beforeAST, afterAST;
712
+
713
+ if (typeof item === "string") {
714
+ code = item;
715
+ } else {
716
+ code = item.code;
717
+
718
+ /*
719
+ * Assumes everything on the item is a config except for the
720
+ * parameters used by this tester
721
+ */
722
+ const itemConfig = { ...item };
723
+
724
+ for (const parameter of RuleTesterParameters) {
725
+ delete itemConfig[parameter];
726
+ }
727
+
728
+ /*
729
+ * Create the config object from the tester config and this item
730
+ * specific configurations.
731
+ */
732
+ config = merge(
733
+ config,
734
+ itemConfig
735
+ );
736
+ }
737
+
738
+ if (item.filename) {
739
+ filename = item.filename;
740
+ }
741
+
742
+ if (hasOwnProperty(item, "options")) {
743
+ assert(Array.isArray(item.options), "options must be an array");
744
+ if (
745
+ item.options.length > 0 &&
746
+ typeof rule === "object" &&
747
+ (
748
+ !rule.meta || (rule.meta && (typeof rule.meta.schema === "undefined" || rule.meta.schema === null))
749
+ )
750
+ ) {
751
+ emitMissingSchemaWarning(ruleName);
752
+ }
753
+ config.rules[ruleName] = [1].concat(item.options);
754
+ } else {
755
+ config.rules[ruleName] = 1;
756
+ }
757
+
758
+ const schema = getRuleOptionsSchema(rule);
759
+
760
+ /*
761
+ * Setup AST getters.
762
+ * The goal is to check whether or not AST was modified when
763
+ * running the rule under test.
764
+ */
765
+ linter.defineRule("rule-tester/validate-ast", {
766
+ create() {
767
+ return {
768
+ Program(node) {
769
+ beforeAST = cloneDeeplyExcludesParent(node);
770
+ },
771
+ "Program:exit"(node) {
772
+ afterAST = node;
773
+ }
774
+ };
775
+ }
776
+ });
777
+
778
+ if (typeof config.parser === "string") {
779
+ assert(path.isAbsolute(config.parser), "Parsers provided as strings to RuleTester must be absolute paths");
780
+ } else {
781
+ config.parser = espreePath;
782
+ }
783
+
784
+ linter.defineParser(config.parser, wrapParser(require(config.parser)));
785
+
786
+ if (schema) {
787
+ ajv.validateSchema(schema);
788
+
789
+ if (ajv.errors) {
790
+ const errors = ajv.errors.map(error => {
791
+ const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
792
+
793
+ return `\t${field}: ${error.message}`;
794
+ }).join("\n");
795
+
796
+ throw new Error([`Schema for rule ${ruleName} is invalid:`, errors]);
797
+ }
798
+
799
+ /*
800
+ * `ajv.validateSchema` checks for errors in the structure of the schema (by comparing the schema against a "meta-schema"),
801
+ * and it reports those errors individually. However, there are other types of schema errors that only occur when compiling
802
+ * the schema (e.g. using invalid defaults in a schema), and only one of these errors can be reported at a time. As a result,
803
+ * the schema is compiled here separately from checking for `validateSchema` errors.
804
+ */
805
+ try {
806
+ ajv.compile(schema);
807
+ } catch (err) {
808
+ throw new Error(`Schema for rule ${ruleName} is invalid: ${err.message}`);
809
+ }
810
+ }
811
+
812
+ validate(config, "rule-tester", id => (id === ruleName ? rule : null));
813
+
814
+ // Verify the code.
815
+ const { getComments, applyLanguageOptions, applyInlineConfig, finalize } = SourceCode.prototype;
816
+ const originalCurrentSegments = Object.getOwnPropertyDescriptor(CodePath.prototype, "currentSegments");
817
+ let messages;
818
+
819
+ try {
820
+ SourceCode.prototype.getComments = getCommentsDeprecation;
821
+ Object.defineProperty(CodePath.prototype, "currentSegments", {
822
+ get() {
823
+ emitCodePathCurrentSegmentsWarning(ruleName);
824
+ return originalCurrentSegments.get.call(this);
825
+ }
826
+ });
827
+
828
+ forbiddenMethods.forEach(methodName => {
829
+ SourceCode.prototype[methodName] = throwForbiddenMethodError(methodName);
830
+ });
831
+
832
+ messages = linter.verify(code, config, filename);
833
+ } finally {
834
+ SourceCode.prototype.getComments = getComments;
835
+ Object.defineProperty(CodePath.prototype, "currentSegments", originalCurrentSegments);
836
+ SourceCode.prototype.applyInlineConfig = applyInlineConfig;
837
+ SourceCode.prototype.applyLanguageOptions = applyLanguageOptions;
838
+ SourceCode.prototype.finalize = finalize;
839
+ }
840
+
841
+ const fatalErrorMessage = messages.find(m => m.fatal);
842
+
843
+ assert(!fatalErrorMessage, `A fatal parsing error occurred: ${fatalErrorMessage && fatalErrorMessage.message}`);
844
+
845
+ // Verify if autofix makes a syntax error or not.
846
+ if (messages.some(m => m.fix)) {
847
+ output = SourceCodeFixer.applyFixes(code, messages).output;
848
+ const errorMessageInFix = linter.verify(output, config, filename).find(m => m.fatal);
849
+
850
+ assert(!errorMessageInFix, [
851
+ "A fatal parsing error occurred in autofix.",
852
+ `Error: ${errorMessageInFix && errorMessageInFix.message}`,
853
+ "Autofix output:",
854
+ output
855
+ ].join("\n"));
856
+ } else {
857
+ output = code;
858
+ }
859
+
860
+ return {
861
+ messages,
862
+ output,
863
+ beforeAST,
864
+ afterAST: cloneDeeplyExcludesParent(afterAST)
865
+ };
866
+ }
867
+
868
+ /**
869
+ * Check if the AST was changed
870
+ * @param {ASTNode} beforeAST AST node before running
871
+ * @param {ASTNode} afterAST AST node after running
872
+ * @returns {void}
873
+ * @private
874
+ */
875
+ function assertASTDidntChange(beforeAST, afterAST) {
876
+ if (!equal(beforeAST, afterAST)) {
877
+ assert.fail("Rule should not modify AST.");
878
+ }
879
+ }
880
+
881
+ /**
882
+ * Check if the template is valid or not
883
+ * all valid cases go through this
884
+ * @param {string|Object} item Item to run the rule against
885
+ * @returns {void}
886
+ * @private
887
+ */
888
+ function testValidTemplate(item) {
889
+ const code = typeof item === "object" ? item.code : item;
890
+
891
+ assert.ok(typeof code === "string", "Test case must specify a string value for 'code'");
892
+ if (item.name) {
893
+ assert.ok(typeof item.name === "string", "Optional test case property 'name' must be a string");
894
+ }
895
+
896
+ const result = runRuleForItem(item);
897
+ const messages = result.messages;
898
+
899
+ assert.strictEqual(messages.length, 0, util.format("Should have no errors but had %d: %s",
900
+ messages.length,
901
+ util.inspect(messages)));
902
+
903
+ assertASTDidntChange(result.beforeAST, result.afterAST);
904
+ }
905
+
906
+ /**
907
+ * Asserts that the message matches its expected value. If the expected
908
+ * value is a regular expression, it is checked against the actual
909
+ * value.
910
+ * @param {string} actual Actual value
911
+ * @param {string|RegExp} expected Expected value
912
+ * @returns {void}
913
+ * @private
914
+ */
915
+ function assertMessageMatches(actual, expected) {
916
+ if (expected instanceof RegExp) {
917
+
918
+ // assert.js doesn't have a built-in RegExp match function
919
+ assert.ok(
920
+ expected.test(actual),
921
+ `Expected '${actual}' to match ${expected}`
922
+ );
923
+ } else {
924
+ assert.strictEqual(actual, expected);
925
+ }
926
+ }
927
+
928
+ /**
929
+ * Check if the template is invalid or not
930
+ * all invalid cases go through this.
931
+ * @param {string|Object} item Item to run the rule against
932
+ * @returns {void}
933
+ * @private
934
+ */
935
+ function testInvalidTemplate(item) {
936
+ assert.ok(typeof item.code === "string", "Test case must specify a string value for 'code'");
937
+ if (item.name) {
938
+ assert.ok(typeof item.name === "string", "Optional test case property 'name' must be a string");
939
+ }
940
+ assert.ok(item.errors || item.errors === 0,
941
+ `Did not specify errors for an invalid test of ${ruleName}`);
942
+
943
+ if (Array.isArray(item.errors) && item.errors.length === 0) {
944
+ assert.fail("Invalid cases must have at least one error");
945
+ }
946
+
947
+ const ruleHasMetaMessages = hasOwnProperty(rule, "meta") && hasOwnProperty(rule.meta, "messages");
948
+ const friendlyIDList = ruleHasMetaMessages ? `[${Object.keys(rule.meta.messages).map(key => `'${key}'`).join(", ")}]` : null;
949
+
950
+ const result = runRuleForItem(item);
951
+ const messages = result.messages;
952
+
953
+ if (typeof item.errors === "number") {
954
+
955
+ if (item.errors === 0) {
956
+ assert.fail("Invalid cases must have 'error' value greater than 0");
957
+ }
958
+
959
+ assert.strictEqual(messages.length, item.errors, util.format("Should have %d error%s but had %d: %s",
960
+ item.errors,
961
+ item.errors === 1 ? "" : "s",
962
+ messages.length,
963
+ util.inspect(messages)));
964
+ } else {
965
+ assert.strictEqual(
966
+ messages.length, item.errors.length, util.format(
967
+ "Should have %d error%s but had %d: %s",
968
+ item.errors.length,
969
+ item.errors.length === 1 ? "" : "s",
970
+ messages.length,
971
+ util.inspect(messages)
972
+ )
973
+ );
974
+
975
+ const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleName);
976
+
977
+ for (let i = 0, l = item.errors.length; i < l; i++) {
978
+ const error = item.errors[i];
979
+ const message = messages[i];
980
+
981
+ assert(hasMessageOfThisRule, "Error rule name should be the same as the name of the rule being tested");
982
+
983
+ if (typeof error === "string" || error instanceof RegExp) {
984
+
985
+ // Just an error message.
986
+ assertMessageMatches(message.message, error);
987
+ } else if (typeof error === "object" && error !== null) {
988
+
989
+ /*
990
+ * Error object.
991
+ * This may have a message, messageId, data, node type, line, and/or
992
+ * column.
993
+ */
994
+
995
+ Object.keys(error).forEach(propertyName => {
996
+ assert.ok(
997
+ errorObjectParameters.has(propertyName),
998
+ `Invalid error property name '${propertyName}'. Expected one of ${friendlyErrorObjectParameterList}.`
999
+ );
1000
+ });
1001
+
1002
+ if (hasOwnProperty(error, "message")) {
1003
+ assert.ok(!hasOwnProperty(error, "messageId"), "Error should not specify both 'message' and a 'messageId'.");
1004
+ assert.ok(!hasOwnProperty(error, "data"), "Error should not specify both 'data' and 'message'.");
1005
+ assertMessageMatches(message.message, error.message);
1006
+ } else if (hasOwnProperty(error, "messageId")) {
1007
+ assert.ok(
1008
+ ruleHasMetaMessages,
1009
+ "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'."
1010
+ );
1011
+ if (!hasOwnProperty(rule.meta.messages, error.messageId)) {
1012
+ assert(false, `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`);
1013
+ }
1014
+ assert.strictEqual(
1015
+ message.messageId,
1016
+ error.messageId,
1017
+ `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.`
1018
+ );
1019
+ if (hasOwnProperty(error, "data")) {
1020
+
1021
+ /*
1022
+ * if data was provided, then directly compare the returned message to a synthetic
1023
+ * interpolated message using the same message ID and data provided in the test.
1024
+ * See https://github.com/eslint/eslint/issues/9890 for context.
1025
+ */
1026
+ const unformattedOriginalMessage = rule.meta.messages[error.messageId];
1027
+ const rehydratedMessage = interpolate(unformattedOriginalMessage, error.data);
1028
+
1029
+ assert.strictEqual(
1030
+ message.message,
1031
+ rehydratedMessage,
1032
+ `Hydrated message "${rehydratedMessage}" does not match "${message.message}"`
1033
+ );
1034
+ }
1035
+ }
1036
+
1037
+ assert.ok(
1038
+ hasOwnProperty(error, "data") ? hasOwnProperty(error, "messageId") : true,
1039
+ "Error must specify 'messageId' if 'data' is used."
1040
+ );
1041
+
1042
+ if (error.type) {
1043
+ assert.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`);
1044
+ }
1045
+
1046
+ if (hasOwnProperty(error, "line")) {
1047
+ assert.strictEqual(message.line, error.line, `Error line should be ${error.line}`);
1048
+ }
1049
+
1050
+ if (hasOwnProperty(error, "column")) {
1051
+ assert.strictEqual(message.column, error.column, `Error column should be ${error.column}`);
1052
+ }
1053
+
1054
+ if (hasOwnProperty(error, "endLine")) {
1055
+ assert.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`);
1056
+ }
1057
+
1058
+ if (hasOwnProperty(error, "endColumn")) {
1059
+ assert.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`);
1060
+ }
1061
+
1062
+ if (hasOwnProperty(error, "suggestions")) {
1063
+
1064
+ // Support asserting there are no suggestions
1065
+ if (!error.suggestions || (Array.isArray(error.suggestions) && error.suggestions.length === 0)) {
1066
+ if (Array.isArray(message.suggestions) && message.suggestions.length > 0) {
1067
+ assert.fail(`Error should have no suggestions on error with message: "${message.message}"`);
1068
+ }
1069
+ } else {
1070
+ assert.strictEqual(Array.isArray(message.suggestions), true, `Error should have an array of suggestions. Instead received "${message.suggestions}" on error with message: "${message.message}"`);
1071
+ assert.strictEqual(message.suggestions.length, error.suggestions.length, `Error should have ${error.suggestions.length} suggestions. Instead found ${message.suggestions.length} suggestions`);
1072
+
1073
+ error.suggestions.forEach((expectedSuggestion, index) => {
1074
+ assert.ok(
1075
+ typeof expectedSuggestion === "object" && expectedSuggestion !== null,
1076
+ "Test suggestion in 'suggestions' array must be an object."
1077
+ );
1078
+ Object.keys(expectedSuggestion).forEach(propertyName => {
1079
+ assert.ok(
1080
+ suggestionObjectParameters.has(propertyName),
1081
+ `Invalid suggestion property name '${propertyName}'. Expected one of ${friendlySuggestionObjectParameterList}.`
1082
+ );
1083
+ });
1084
+
1085
+ const actualSuggestion = message.suggestions[index];
1086
+ const suggestionPrefix = `Error Suggestion at index ${index} :`;
1087
+
1088
+ if (hasOwnProperty(expectedSuggestion, "desc")) {
1089
+ assert.ok(
1090
+ !hasOwnProperty(expectedSuggestion, "data"),
1091
+ `${suggestionPrefix} Test should not specify both 'desc' and 'data'.`
1092
+ );
1093
+ assert.strictEqual(
1094
+ actualSuggestion.desc,
1095
+ expectedSuggestion.desc,
1096
+ `${suggestionPrefix} desc should be "${expectedSuggestion.desc}" but got "${actualSuggestion.desc}" instead.`
1097
+ );
1098
+ }
1099
+
1100
+ if (hasOwnProperty(expectedSuggestion, "messageId")) {
1101
+ assert.ok(
1102
+ ruleHasMetaMessages,
1103
+ `${suggestionPrefix} Test can not use 'messageId' if rule under test doesn't define 'meta.messages'.`
1104
+ );
1105
+ assert.ok(
1106
+ hasOwnProperty(rule.meta.messages, expectedSuggestion.messageId),
1107
+ `${suggestionPrefix} Test has invalid messageId '${expectedSuggestion.messageId}', the rule under test allows only one of ${friendlyIDList}.`
1108
+ );
1109
+ assert.strictEqual(
1110
+ actualSuggestion.messageId,
1111
+ expectedSuggestion.messageId,
1112
+ `${suggestionPrefix} messageId should be '${expectedSuggestion.messageId}' but got '${actualSuggestion.messageId}' instead.`
1113
+ );
1114
+ if (hasOwnProperty(expectedSuggestion, "data")) {
1115
+ const unformattedMetaMessage = rule.meta.messages[expectedSuggestion.messageId];
1116
+ const rehydratedDesc = interpolate(unformattedMetaMessage, expectedSuggestion.data);
1117
+
1118
+ assert.strictEqual(
1119
+ actualSuggestion.desc,
1120
+ rehydratedDesc,
1121
+ `${suggestionPrefix} Hydrated test desc "${rehydratedDesc}" does not match received desc "${actualSuggestion.desc}".`
1122
+ );
1123
+ }
1124
+ } else {
1125
+ assert.ok(
1126
+ !hasOwnProperty(expectedSuggestion, "data"),
1127
+ `${suggestionPrefix} Test must specify 'messageId' if 'data' is used.`
1128
+ );
1129
+ }
1130
+
1131
+ if (hasOwnProperty(expectedSuggestion, "output")) {
1132
+ const codeWithAppliedSuggestion = SourceCodeFixer.applyFixes(item.code, [actualSuggestion]).output;
1133
+
1134
+ assert.strictEqual(codeWithAppliedSuggestion, expectedSuggestion.output, `Expected the applied suggestion fix to match the test suggestion output for suggestion at index: ${index} on error with message: "${message.message}"`);
1135
+ }
1136
+ });
1137
+ }
1138
+ }
1139
+ } else {
1140
+
1141
+ // Message was an unexpected type
1142
+ assert.fail(`Error should be a string, object, or RegExp, but found (${util.inspect(message)})`);
1143
+ }
1144
+ }
1145
+ }
1146
+
1147
+ if (hasOwnProperty(item, "output")) {
1148
+ if (item.output === null) {
1149
+ assert.strictEqual(
1150
+ result.output,
1151
+ item.code,
1152
+ "Expected no autofixes to be suggested"
1153
+ );
1154
+ } else {
1155
+ assert.strictEqual(result.output, item.output, "Output is incorrect.");
1156
+ }
1157
+ } else {
1158
+ assert.strictEqual(
1159
+ result.output,
1160
+ item.code,
1161
+ "The rule fixed the code. Please add 'output' property."
1162
+ );
1163
+ }
1164
+
1165
+ assertASTDidntChange(result.beforeAST, result.afterAST);
1166
+ }
1167
+
1168
+ /*
1169
+ * This creates a mocha test suite and pipes all supplied info through
1170
+ * one of the templates above.
1171
+ * The test suites for valid/invalid are created conditionally as
1172
+ * test runners (eg. vitest) fail for empty test suites.
1173
+ */
1174
+ this.constructor.describe(ruleName, () => {
1175
+ if (test.valid.length > 0) {
1176
+ this.constructor.describe("valid", () => {
1177
+ test.valid.forEach(valid => {
1178
+ this.constructor[valid.only ? "itOnly" : "it"](
1179
+ sanitize(typeof valid === "object" ? valid.name || valid.code : valid),
1180
+ () => {
1181
+ testValidTemplate(valid);
1182
+ }
1183
+ );
1184
+ });
1185
+ });
1186
+ }
1187
+
1188
+ if (test.invalid.length > 0) {
1189
+ this.constructor.describe("invalid", () => {
1190
+ test.invalid.forEach(invalid => {
1191
+ this.constructor[invalid.only ? "itOnly" : "it"](
1192
+ sanitize(invalid.name || invalid.code),
1193
+ () => {
1194
+ testInvalidTemplate(invalid);
1195
+ }
1196
+ );
1197
+ });
1198
+ });
1199
+ }
1200
+ });
1201
+ }
1202
+ }
1203
+
1204
+ RuleTester[DESCRIBE] = RuleTester[IT] = RuleTester[IT_ONLY] = null;
1205
+
1206
+ module.exports = RuleTester;