@alexlit/lint-kit 117.3.0 → 117.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/package.json +1 -1
  2. package/packages/config-eslint/package.json +5 -9
  3. package/packages/config-eslint/plugins/no-await-in-promise.js +1 -1
  4. package/packages/config-eslint/utils/create-config.js +3 -3
  5. package/scripts/.config.sh +1 -1
  6. package/packages/config-eslint/node_modules/@eslint/eslintrc/LICENSE +0 -19
  7. package/packages/config-eslint/node_modules/@eslint/eslintrc/README.md +0 -126
  8. package/packages/config-eslint/node_modules/@eslint/eslintrc/conf/config-schema.js +0 -79
  9. package/packages/config-eslint/node_modules/@eslint/eslintrc/conf/environments.js +0 -215
  10. package/packages/config-eslint/node_modules/@eslint/eslintrc/dist/eslintrc-universal.cjs +0 -1143
  11. package/packages/config-eslint/node_modules/@eslint/eslintrc/dist/eslintrc-universal.cjs.map +0 -1
  12. package/packages/config-eslint/node_modules/@eslint/eslintrc/dist/eslintrc.cjs +0 -4371
  13. package/packages/config-eslint/node_modules/@eslint/eslintrc/dist/eslintrc.cjs.map +0 -1
  14. package/packages/config-eslint/node_modules/@eslint/eslintrc/lib/cascading-config-array-factory.js +0 -532
  15. package/packages/config-eslint/node_modules/@eslint/eslintrc/lib/config-array/config-array.js +0 -510
  16. package/packages/config-eslint/node_modules/@eslint/eslintrc/lib/config-array/config-dependency.js +0 -124
  17. package/packages/config-eslint/node_modules/@eslint/eslintrc/lib/config-array/extracted-config.js +0 -145
  18. package/packages/config-eslint/node_modules/@eslint/eslintrc/lib/config-array/ignore-pattern.js +0 -238
  19. package/packages/config-eslint/node_modules/@eslint/eslintrc/lib/config-array/index.js +0 -19
  20. package/packages/config-eslint/node_modules/@eslint/eslintrc/lib/config-array/override-tester.js +0 -225
  21. package/packages/config-eslint/node_modules/@eslint/eslintrc/lib/config-array-factory.js +0 -1155
  22. package/packages/config-eslint/node_modules/@eslint/eslintrc/lib/flat-compat.js +0 -318
  23. package/packages/config-eslint/node_modules/@eslint/eslintrc/lib/index-universal.js +0 -29
  24. package/packages/config-eslint/node_modules/@eslint/eslintrc/lib/index.js +0 -58
  25. package/packages/config-eslint/node_modules/@eslint/eslintrc/lib/shared/ajv.js +0 -191
  26. package/packages/config-eslint/node_modules/@eslint/eslintrc/lib/shared/config-ops.js +0 -135
  27. package/packages/config-eslint/node_modules/@eslint/eslintrc/lib/shared/config-validator.js +0 -370
  28. package/packages/config-eslint/node_modules/@eslint/eslintrc/lib/shared/deprecation-warnings.js +0 -63
  29. package/packages/config-eslint/node_modules/@eslint/eslintrc/lib/shared/naming.js +0 -96
  30. package/packages/config-eslint/node_modules/@eslint/eslintrc/lib/shared/relative-module-resolver.js +0 -42
  31. package/packages/config-eslint/node_modules/@eslint/eslintrc/lib/shared/types.js +0 -149
  32. package/packages/config-eslint/node_modules/@eslint/eslintrc/package.json +0 -82
  33. package/packages/config-eslint/node_modules/@eslint/eslintrc/universal.js +0 -9
  34. package/packages/config-eslint/node_modules/ajv/.tonic_example.js +0 -20
  35. package/packages/config-eslint/node_modules/ajv/LICENSE +0 -22
  36. package/packages/config-eslint/node_modules/ajv/README.md +0 -1497
  37. package/packages/config-eslint/node_modules/ajv/dist/ajv.bundle.js +0 -7189
  38. package/packages/config-eslint/node_modules/ajv/dist/ajv.min.js +0 -3
  39. package/packages/config-eslint/node_modules/ajv/dist/ajv.min.js.map +0 -1
  40. package/packages/config-eslint/node_modules/ajv/lib/ajv.d.ts +0 -397
  41. package/packages/config-eslint/node_modules/ajv/lib/ajv.js +0 -506
  42. package/packages/config-eslint/node_modules/ajv/lib/cache.js +0 -26
  43. package/packages/config-eslint/node_modules/ajv/lib/compile/async.js +0 -90
  44. package/packages/config-eslint/node_modules/ajv/lib/compile/equal.js +0 -5
  45. package/packages/config-eslint/node_modules/ajv/lib/compile/error_classes.js +0 -34
  46. package/packages/config-eslint/node_modules/ajv/lib/compile/formats.js +0 -142
  47. package/packages/config-eslint/node_modules/ajv/lib/compile/index.js +0 -387
  48. package/packages/config-eslint/node_modules/ajv/lib/compile/resolve.js +0 -270
  49. package/packages/config-eslint/node_modules/ajv/lib/compile/rules.js +0 -66
  50. package/packages/config-eslint/node_modules/ajv/lib/compile/schema_obj.js +0 -9
  51. package/packages/config-eslint/node_modules/ajv/lib/compile/ucs2length.js +0 -20
  52. package/packages/config-eslint/node_modules/ajv/lib/compile/util.js +0 -239
  53. package/packages/config-eslint/node_modules/ajv/lib/data.js +0 -49
  54. package/packages/config-eslint/node_modules/ajv/lib/definition_schema.js +0 -37
  55. package/packages/config-eslint/node_modules/ajv/lib/dot/_limit.jst +0 -113
  56. package/packages/config-eslint/node_modules/ajv/lib/dot/_limitItems.jst +0 -12
  57. package/packages/config-eslint/node_modules/ajv/lib/dot/_limitLength.jst +0 -12
  58. package/packages/config-eslint/node_modules/ajv/lib/dot/_limitProperties.jst +0 -12
  59. package/packages/config-eslint/node_modules/ajv/lib/dot/allOf.jst +0 -32
  60. package/packages/config-eslint/node_modules/ajv/lib/dot/anyOf.jst +0 -46
  61. package/packages/config-eslint/node_modules/ajv/lib/dot/coerce.def +0 -51
  62. package/packages/config-eslint/node_modules/ajv/lib/dot/comment.jst +0 -9
  63. package/packages/config-eslint/node_modules/ajv/lib/dot/const.jst +0 -11
  64. package/packages/config-eslint/node_modules/ajv/lib/dot/contains.jst +0 -55
  65. package/packages/config-eslint/node_modules/ajv/lib/dot/custom.jst +0 -191
  66. package/packages/config-eslint/node_modules/ajv/lib/dot/defaults.def +0 -47
  67. package/packages/config-eslint/node_modules/ajv/lib/dot/definitions.def +0 -203
  68. package/packages/config-eslint/node_modules/ajv/lib/dot/dependencies.jst +0 -79
  69. package/packages/config-eslint/node_modules/ajv/lib/dot/enum.jst +0 -30
  70. package/packages/config-eslint/node_modules/ajv/lib/dot/errors.def +0 -194
  71. package/packages/config-eslint/node_modules/ajv/lib/dot/format.jst +0 -106
  72. package/packages/config-eslint/node_modules/ajv/lib/dot/if.jst +0 -73
  73. package/packages/config-eslint/node_modules/ajv/lib/dot/items.jst +0 -98
  74. package/packages/config-eslint/node_modules/ajv/lib/dot/missing.def +0 -39
  75. package/packages/config-eslint/node_modules/ajv/lib/dot/multipleOf.jst +0 -22
  76. package/packages/config-eslint/node_modules/ajv/lib/dot/not.jst +0 -43
  77. package/packages/config-eslint/node_modules/ajv/lib/dot/oneOf.jst +0 -54
  78. package/packages/config-eslint/node_modules/ajv/lib/dot/pattern.jst +0 -14
  79. package/packages/config-eslint/node_modules/ajv/lib/dot/properties.jst +0 -245
  80. package/packages/config-eslint/node_modules/ajv/lib/dot/propertyNames.jst +0 -52
  81. package/packages/config-eslint/node_modules/ajv/lib/dot/ref.jst +0 -85
  82. package/packages/config-eslint/node_modules/ajv/lib/dot/required.jst +0 -108
  83. package/packages/config-eslint/node_modules/ajv/lib/dot/uniqueItems.jst +0 -62
  84. package/packages/config-eslint/node_modules/ajv/lib/dot/validate.jst +0 -276
  85. package/packages/config-eslint/node_modules/ajv/lib/dotjs/README.md +0 -3
  86. package/packages/config-eslint/node_modules/ajv/lib/dotjs/_limit.js +0 -163
  87. package/packages/config-eslint/node_modules/ajv/lib/dotjs/_limitItems.js +0 -80
  88. package/packages/config-eslint/node_modules/ajv/lib/dotjs/_limitLength.js +0 -85
  89. package/packages/config-eslint/node_modules/ajv/lib/dotjs/_limitProperties.js +0 -80
  90. package/packages/config-eslint/node_modules/ajv/lib/dotjs/allOf.js +0 -42
  91. package/packages/config-eslint/node_modules/ajv/lib/dotjs/anyOf.js +0 -73
  92. package/packages/config-eslint/node_modules/ajv/lib/dotjs/comment.js +0 -14
  93. package/packages/config-eslint/node_modules/ajv/lib/dotjs/const.js +0 -56
  94. package/packages/config-eslint/node_modules/ajv/lib/dotjs/contains.js +0 -81
  95. package/packages/config-eslint/node_modules/ajv/lib/dotjs/custom.js +0 -228
  96. package/packages/config-eslint/node_modules/ajv/lib/dotjs/dependencies.js +0 -168
  97. package/packages/config-eslint/node_modules/ajv/lib/dotjs/enum.js +0 -66
  98. package/packages/config-eslint/node_modules/ajv/lib/dotjs/format.js +0 -150
  99. package/packages/config-eslint/node_modules/ajv/lib/dotjs/if.js +0 -103
  100. package/packages/config-eslint/node_modules/ajv/lib/dotjs/index.js +0 -33
  101. package/packages/config-eslint/node_modules/ajv/lib/dotjs/items.js +0 -140
  102. package/packages/config-eslint/node_modules/ajv/lib/dotjs/multipleOf.js +0 -80
  103. package/packages/config-eslint/node_modules/ajv/lib/dotjs/not.js +0 -84
  104. package/packages/config-eslint/node_modules/ajv/lib/dotjs/oneOf.js +0 -73
  105. package/packages/config-eslint/node_modules/ajv/lib/dotjs/pattern.js +0 -75
  106. package/packages/config-eslint/node_modules/ajv/lib/dotjs/properties.js +0 -335
  107. package/packages/config-eslint/node_modules/ajv/lib/dotjs/propertyNames.js +0 -81
  108. package/packages/config-eslint/node_modules/ajv/lib/dotjs/ref.js +0 -124
  109. package/packages/config-eslint/node_modules/ajv/lib/dotjs/required.js +0 -270
  110. package/packages/config-eslint/node_modules/ajv/lib/dotjs/uniqueItems.js +0 -86
  111. package/packages/config-eslint/node_modules/ajv/lib/dotjs/validate.js +0 -482
  112. package/packages/config-eslint/node_modules/ajv/lib/keyword.js +0 -146
  113. package/packages/config-eslint/node_modules/ajv/lib/refs/data.json +0 -17
  114. package/packages/config-eslint/node_modules/ajv/lib/refs/json-schema-draft-04.json +0 -149
  115. package/packages/config-eslint/node_modules/ajv/lib/refs/json-schema-draft-06.json +0 -154
  116. package/packages/config-eslint/node_modules/ajv/lib/refs/json-schema-draft-07.json +0 -168
  117. package/packages/config-eslint/node_modules/ajv/lib/refs/json-schema-secure.json +0 -94
  118. package/packages/config-eslint/node_modules/ajv/package.json +0 -106
  119. package/packages/config-eslint/node_modules/ajv/scripts/.eslintrc.yml +0 -3
  120. package/packages/config-eslint/node_modules/ajv/scripts/bundle.js +0 -61
  121. package/packages/config-eslint/node_modules/ajv/scripts/compile-dots.js +0 -73
  122. package/packages/config-eslint/node_modules/ajv/scripts/info +0 -10
  123. package/packages/config-eslint/node_modules/ajv/scripts/prepare-tests +0 -12
  124. package/packages/config-eslint/node_modules/ajv/scripts/publish-built-version +0 -32
  125. package/packages/config-eslint/node_modules/ajv/scripts/travis-gh-pages +0 -23
  126. package/packages/config-eslint/node_modules/eslint-visitor-keys/LICENSE +0 -201
  127. package/packages/config-eslint/node_modules/eslint-visitor-keys/README.md +0 -105
  128. package/packages/config-eslint/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs +0 -384
  129. package/packages/config-eslint/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts +0 -27
  130. package/packages/config-eslint/node_modules/eslint-visitor-keys/dist/index.d.ts +0 -16
  131. package/packages/config-eslint/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts +0 -12
  132. package/packages/config-eslint/node_modules/eslint-visitor-keys/lib/index.js +0 -65
  133. package/packages/config-eslint/node_modules/eslint-visitor-keys/lib/visitor-keys.js +0 -315
  134. package/packages/config-eslint/node_modules/eslint-visitor-keys/package.json +0 -74
  135. package/packages/config-eslint/node_modules/espree/LICENSE +0 -25
  136. package/packages/config-eslint/node_modules/espree/README.md +0 -244
  137. package/packages/config-eslint/node_modules/espree/dist/espree.cjs +0 -883
  138. package/packages/config-eslint/node_modules/espree/espree.js +0 -177
  139. package/packages/config-eslint/node_modules/espree/lib/espree.js +0 -349
  140. package/packages/config-eslint/node_modules/espree/lib/features.js +0 -27
  141. package/packages/config-eslint/node_modules/espree/lib/options.js +0 -123
  142. package/packages/config-eslint/node_modules/espree/lib/token-translator.js +0 -263
  143. package/packages/config-eslint/node_modules/espree/lib/version.js +0 -3
  144. package/packages/config-eslint/node_modules/espree/package.json +0 -86
  145. package/packages/config-eslint/node_modules/globals/globals.json +0 -1998
  146. package/packages/config-eslint/node_modules/globals/index.d.ts +0 -2077
  147. package/packages/config-eslint/node_modules/globals/index.js +0 -2
  148. package/packages/config-eslint/node_modules/globals/license +0 -9
  149. package/packages/config-eslint/node_modules/globals/package.json +0 -58
  150. package/packages/config-eslint/node_modules/globals/readme.md +0 -44
  151. package/packages/config-eslint/node_modules/json-schema-traverse/.eslintrc.yml +0 -27
  152. package/packages/config-eslint/node_modules/json-schema-traverse/.travis.yml +0 -8
  153. package/packages/config-eslint/node_modules/json-schema-traverse/LICENSE +0 -21
  154. package/packages/config-eslint/node_modules/json-schema-traverse/README.md +0 -83
  155. package/packages/config-eslint/node_modules/json-schema-traverse/index.js +0 -89
  156. package/packages/config-eslint/node_modules/json-schema-traverse/package.json +0 -43
  157. package/packages/config-eslint/node_modules/json-schema-traverse/spec/.eslintrc.yml +0 -6
  158. package/packages/config-eslint/node_modules/json-schema-traverse/spec/fixtures/schema.js +0 -125
  159. package/packages/config-eslint/node_modules/json-schema-traverse/spec/index.spec.js +0 -171
@@ -1,4371 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var debugOrig = require('debug');
6
- var fs = require('fs');
7
- var importFresh = require('import-fresh');
8
- var Module = require('module');
9
- var path = require('path');
10
- var stripComments = require('strip-json-comments');
11
- var assert = require('assert');
12
- var ignore = require('ignore');
13
- var util = require('util');
14
- var minimatch = require('minimatch');
15
- var Ajv = require('ajv');
16
- var globals = require('globals');
17
- var os = require('os');
18
-
19
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
20
-
21
- var debugOrig__default = /*#__PURE__*/_interopDefaultLegacy(debugOrig);
22
- var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
23
- var importFresh__default = /*#__PURE__*/_interopDefaultLegacy(importFresh);
24
- var Module__default = /*#__PURE__*/_interopDefaultLegacy(Module);
25
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
26
- var stripComments__default = /*#__PURE__*/_interopDefaultLegacy(stripComments);
27
- var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert);
28
- var ignore__default = /*#__PURE__*/_interopDefaultLegacy(ignore);
29
- var util__default = /*#__PURE__*/_interopDefaultLegacy(util);
30
- var minimatch__default = /*#__PURE__*/_interopDefaultLegacy(minimatch);
31
- var Ajv__default = /*#__PURE__*/_interopDefaultLegacy(Ajv);
32
- var globals__default = /*#__PURE__*/_interopDefaultLegacy(globals);
33
- var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
34
-
35
- /**
36
- * @fileoverview `IgnorePattern` class.
37
- *
38
- * `IgnorePattern` class has the set of glob patterns and the base path.
39
- *
40
- * It provides two static methods.
41
- *
42
- * - `IgnorePattern.createDefaultIgnore(cwd)`
43
- * Create the default predicate function.
44
- * - `IgnorePattern.createIgnore(ignorePatterns)`
45
- * Create the predicate function from multiple `IgnorePattern` objects.
46
- *
47
- * It provides two properties and a method.
48
- *
49
- * - `patterns`
50
- * The glob patterns that ignore to lint.
51
- * - `basePath`
52
- * The base path of the glob patterns. If absolute paths existed in the
53
- * glob patterns, those are handled as relative paths to the base path.
54
- * - `getPatternsRelativeTo(basePath)`
55
- * Get `patterns` as modified for a given base path. It modifies the
56
- * absolute paths in the patterns as prepending the difference of two base
57
- * paths.
58
- *
59
- * `ConfigArrayFactory` creates `IgnorePattern` objects when it processes
60
- * `ignorePatterns` properties.
61
- *
62
- * @author Toru Nagashima <https://github.com/mysticatea>
63
- */
64
-
65
- const debug$3 = debugOrig__default["default"]("eslintrc:ignore-pattern");
66
-
67
- /** @typedef {ReturnType<import("ignore").default>} Ignore */
68
-
69
- //------------------------------------------------------------------------------
70
- // Helpers
71
- //------------------------------------------------------------------------------
72
-
73
- /**
74
- * Get the path to the common ancestor directory of given paths.
75
- * @param {string[]} sourcePaths The paths to calculate the common ancestor.
76
- * @returns {string} The path to the common ancestor directory.
77
- */
78
- function getCommonAncestorPath(sourcePaths) {
79
- let result = sourcePaths[0];
80
-
81
- for (let i = 1; i < sourcePaths.length; ++i) {
82
- const a = result;
83
- const b = sourcePaths[i];
84
-
85
- // Set the shorter one (it's the common ancestor if one includes the other).
86
- result = a.length < b.length ? a : b;
87
-
88
- // Set the common ancestor.
89
- for (let j = 0, lastSepPos = 0; j < a.length && j < b.length; ++j) {
90
- if (a[j] !== b[j]) {
91
- result = a.slice(0, lastSepPos);
92
- break;
93
- }
94
- if (a[j] === path__default["default"].sep) {
95
- lastSepPos = j;
96
- }
97
- }
98
- }
99
-
100
- let resolvedResult = result || path__default["default"].sep;
101
-
102
- // if Windows common ancestor is root of drive must have trailing slash to be absolute.
103
- if (resolvedResult && resolvedResult.endsWith(":") && process.platform === "win32") {
104
- resolvedResult += path__default["default"].sep;
105
- }
106
- return resolvedResult;
107
- }
108
-
109
- /**
110
- * Make relative path.
111
- * @param {string} from The source path to get relative path.
112
- * @param {string} to The destination path to get relative path.
113
- * @returns {string} The relative path.
114
- */
115
- function relative(from, to) {
116
- const relPath = path__default["default"].relative(from, to);
117
-
118
- if (path__default["default"].sep === "/") {
119
- return relPath;
120
- }
121
- return relPath.split(path__default["default"].sep).join("/");
122
- }
123
-
124
- /**
125
- * Get the trailing slash if existed.
126
- * @param {string} filePath The path to check.
127
- * @returns {string} The trailing slash if existed.
128
- */
129
- function dirSuffix(filePath) {
130
- const isDir = (
131
- filePath.endsWith(path__default["default"].sep) ||
132
- (process.platform === "win32" && filePath.endsWith("/"))
133
- );
134
-
135
- return isDir ? "/" : "";
136
- }
137
-
138
- const DefaultPatterns = Object.freeze(["/**/node_modules/*"]);
139
- const DotPatterns = Object.freeze([".*", "!.eslintrc.*", "!../"]);
140
-
141
- //------------------------------------------------------------------------------
142
- // Public
143
- //------------------------------------------------------------------------------
144
-
145
- class IgnorePattern {
146
-
147
- /**
148
- * The default patterns.
149
- * @type {string[]}
150
- */
151
- static get DefaultPatterns() {
152
- return DefaultPatterns;
153
- }
154
-
155
- /**
156
- * Create the default predicate function.
157
- * @param {string} cwd The current working directory.
158
- * @returns {((filePath:string, dot:boolean) => boolean) & {basePath:string; patterns:string[]}}
159
- * The preficate function.
160
- * The first argument is an absolute path that is checked.
161
- * The second argument is the flag to not ignore dotfiles.
162
- * If the predicate function returned `true`, it means the path should be ignored.
163
- */
164
- static createDefaultIgnore(cwd) {
165
- return this.createIgnore([new IgnorePattern(DefaultPatterns, cwd)]);
166
- }
167
-
168
- /**
169
- * Create the predicate function from multiple `IgnorePattern` objects.
170
- * @param {IgnorePattern[]} ignorePatterns The list of ignore patterns.
171
- * @returns {((filePath:string, dot?:boolean) => boolean) & {basePath:string; patterns:string[]}}
172
- * The preficate function.
173
- * The first argument is an absolute path that is checked.
174
- * The second argument is the flag to not ignore dotfiles.
175
- * If the predicate function returned `true`, it means the path should be ignored.
176
- */
177
- static createIgnore(ignorePatterns) {
178
- debug$3("Create with: %o", ignorePatterns);
179
-
180
- const basePath = getCommonAncestorPath(ignorePatterns.map(p => p.basePath));
181
- const patterns = [].concat(
182
- ...ignorePatterns.map(p => p.getPatternsRelativeTo(basePath))
183
- );
184
- const ig = ignore__default["default"]({ allowRelativePaths: true }).add([...DotPatterns, ...patterns]);
185
- const dotIg = ignore__default["default"]({ allowRelativePaths: true }).add(patterns);
186
-
187
- debug$3(" processed: %o", { basePath, patterns });
188
-
189
- return Object.assign(
190
- (filePath, dot = false) => {
191
- assert__default["default"](path__default["default"].isAbsolute(filePath), "'filePath' should be an absolute path.");
192
- const relPathRaw = relative(basePath, filePath);
193
- const relPath = relPathRaw && (relPathRaw + dirSuffix(filePath));
194
- const adoptedIg = dot ? dotIg : ig;
195
- const result = relPath !== "" && adoptedIg.ignores(relPath);
196
-
197
- debug$3("Check", { filePath, dot, relativePath: relPath, result });
198
- return result;
199
- },
200
- { basePath, patterns }
201
- );
202
- }
203
-
204
- /**
205
- * Initialize a new `IgnorePattern` instance.
206
- * @param {string[]} patterns The glob patterns that ignore to lint.
207
- * @param {string} basePath The base path of `patterns`.
208
- */
209
- constructor(patterns, basePath) {
210
- assert__default["default"](path__default["default"].isAbsolute(basePath), "'basePath' should be an absolute path.");
211
-
212
- /**
213
- * The glob patterns that ignore to lint.
214
- * @type {string[]}
215
- */
216
- this.patterns = patterns;
217
-
218
- /**
219
- * The base path of `patterns`.
220
- * @type {string}
221
- */
222
- this.basePath = basePath;
223
-
224
- /**
225
- * If `true` then patterns which don't start with `/` will match the paths to the outside of `basePath`. Defaults to `false`.
226
- *
227
- * It's set `true` for `.eslintignore`, `package.json`, and `--ignore-path` for backward compatibility.
228
- * It's `false` as-is for `ignorePatterns` property in config files.
229
- * @type {boolean}
230
- */
231
- this.loose = false;
232
- }
233
-
234
- /**
235
- * Get `patterns` as modified for a given base path. It modifies the
236
- * absolute paths in the patterns as prepending the difference of two base
237
- * paths.
238
- * @param {string} newBasePath The base path.
239
- * @returns {string[]} Modifired patterns.
240
- */
241
- getPatternsRelativeTo(newBasePath) {
242
- assert__default["default"](path__default["default"].isAbsolute(newBasePath), "'newBasePath' should be an absolute path.");
243
- const { basePath, loose, patterns } = this;
244
-
245
- if (newBasePath === basePath) {
246
- return patterns;
247
- }
248
- const prefix = `/${relative(newBasePath, basePath)}`;
249
-
250
- return patterns.map(pattern => {
251
- const negative = pattern.startsWith("!");
252
- const head = negative ? "!" : "";
253
- const body = negative ? pattern.slice(1) : pattern;
254
-
255
- if (body.startsWith("/") || body.startsWith("../")) {
256
- return `${head}${prefix}${body}`;
257
- }
258
- return loose ? pattern : `${head}${prefix}/**/${body}`;
259
- });
260
- }
261
- }
262
-
263
- /**
264
- * @fileoverview `ExtractedConfig` class.
265
- *
266
- * `ExtractedConfig` class expresses a final configuration for a specific file.
267
- *
268
- * It provides one method.
269
- *
270
- * - `toCompatibleObjectAsConfigFileContent()`
271
- * Convert this configuration to the compatible object as the content of
272
- * config files. It converts the loaded parser and plugins to strings.
273
- * `CLIEngine#getConfigForFile(filePath)` method uses this method.
274
- *
275
- * `ConfigArray#extractConfig(filePath)` creates a `ExtractedConfig` instance.
276
- *
277
- * @author Toru Nagashima <https://github.com/mysticatea>
278
- */
279
-
280
- // For VSCode intellisense
281
- /** @typedef {import("../../shared/types").ConfigData} ConfigData */
282
- /** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
283
- /** @typedef {import("../../shared/types").SeverityConf} SeverityConf */
284
- /** @typedef {import("./config-dependency").DependentParser} DependentParser */
285
- /** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
286
-
287
- /**
288
- * Check if `xs` starts with `ys`.
289
- * @template T
290
- * @param {T[]} xs The array to check.
291
- * @param {T[]} ys The array that may be the first part of `xs`.
292
- * @returns {boolean} `true` if `xs` starts with `ys`.
293
- */
294
- function startsWith(xs, ys) {
295
- return xs.length >= ys.length && ys.every((y, i) => y === xs[i]);
296
- }
297
-
298
- /**
299
- * The class for extracted config data.
300
- */
301
- class ExtractedConfig {
302
- constructor() {
303
-
304
- /**
305
- * The config name what `noInlineConfig` setting came from.
306
- * @type {string}
307
- */
308
- this.configNameOfNoInlineConfig = "";
309
-
310
- /**
311
- * Environments.
312
- * @type {Record<string, boolean>}
313
- */
314
- this.env = {};
315
-
316
- /**
317
- * Global variables.
318
- * @type {Record<string, GlobalConf>}
319
- */
320
- this.globals = {};
321
-
322
- /**
323
- * The glob patterns that ignore to lint.
324
- * @type {(((filePath:string, dot?:boolean) => boolean) & { basePath:string; patterns:string[] }) | undefined}
325
- */
326
- this.ignores = void 0;
327
-
328
- /**
329
- * The flag that disables directive comments.
330
- * @type {boolean|undefined}
331
- */
332
- this.noInlineConfig = void 0;
333
-
334
- /**
335
- * Parser definition.
336
- * @type {DependentParser|null}
337
- */
338
- this.parser = null;
339
-
340
- /**
341
- * Options for the parser.
342
- * @type {Object}
343
- */
344
- this.parserOptions = {};
345
-
346
- /**
347
- * Plugin definitions.
348
- * @type {Record<string, DependentPlugin>}
349
- */
350
- this.plugins = {};
351
-
352
- /**
353
- * Processor ID.
354
- * @type {string|null}
355
- */
356
- this.processor = null;
357
-
358
- /**
359
- * The flag that reports unused `eslint-disable` directive comments.
360
- * @type {boolean|undefined}
361
- */
362
- this.reportUnusedDisableDirectives = void 0;
363
-
364
- /**
365
- * Rule settings.
366
- * @type {Record<string, [SeverityConf, ...any[]]>}
367
- */
368
- this.rules = {};
369
-
370
- /**
371
- * Shared settings.
372
- * @type {Object}
373
- */
374
- this.settings = {};
375
- }
376
-
377
- /**
378
- * Convert this config to the compatible object as a config file content.
379
- * @returns {ConfigData} The converted object.
380
- */
381
- toCompatibleObjectAsConfigFileContent() {
382
- const {
383
- /* eslint-disable no-unused-vars */
384
- configNameOfNoInlineConfig: _ignore1,
385
- processor: _ignore2,
386
- /* eslint-enable no-unused-vars */
387
- ignores,
388
- ...config
389
- } = this;
390
-
391
- config.parser = config.parser && config.parser.filePath;
392
- config.plugins = Object.keys(config.plugins).filter(Boolean).reverse();
393
- config.ignorePatterns = ignores ? ignores.patterns : [];
394
-
395
- // Strip the default patterns from `ignorePatterns`.
396
- if (startsWith(config.ignorePatterns, IgnorePattern.DefaultPatterns)) {
397
- config.ignorePatterns =
398
- config.ignorePatterns.slice(IgnorePattern.DefaultPatterns.length);
399
- }
400
-
401
- return config;
402
- }
403
- }
404
-
405
- /**
406
- * @fileoverview `ConfigArray` class.
407
- *
408
- * `ConfigArray` class expresses the full of a configuration. It has the entry
409
- * config file, base config files that were extended, loaded parsers, and loaded
410
- * plugins.
411
- *
412
- * `ConfigArray` class provides three properties and two methods.
413
- *
414
- * - `pluginEnvironments`
415
- * - `pluginProcessors`
416
- * - `pluginRules`
417
- * The `Map` objects that contain the members of all plugins that this
418
- * config array contains. Those map objects don't have mutation methods.
419
- * Those keys are the member ID such as `pluginId/memberName`.
420
- * - `isRoot()`
421
- * If `true` then this configuration has `root:true` property.
422
- * - `extractConfig(filePath)`
423
- * Extract the final configuration for a given file. This means merging
424
- * every config array element which that `criteria` property matched. The
425
- * `filePath` argument must be an absolute path.
426
- *
427
- * `ConfigArrayFactory` provides the loading logic of config files.
428
- *
429
- * @author Toru Nagashima <https://github.com/mysticatea>
430
- */
431
-
432
- //------------------------------------------------------------------------------
433
- // Helpers
434
- //------------------------------------------------------------------------------
435
-
436
- // Define types for VSCode IntelliSense.
437
- /** @typedef {import("../../shared/types").Environment} Environment */
438
- /** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
439
- /** @typedef {import("../../shared/types").RuleConf} RuleConf */
440
- /** @typedef {import("../../shared/types").Rule} Rule */
441
- /** @typedef {import("../../shared/types").Plugin} Plugin */
442
- /** @typedef {import("../../shared/types").Processor} Processor */
443
- /** @typedef {import("./config-dependency").DependentParser} DependentParser */
444
- /** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
445
- /** @typedef {import("./override-tester")["OverrideTester"]} OverrideTester */
446
-
447
- /**
448
- * @typedef {Object} ConfigArrayElement
449
- * @property {string} name The name of this config element.
450
- * @property {string} filePath The path to the source file of this config element.
451
- * @property {InstanceType<OverrideTester>|null} criteria The tester for the `files` and `excludedFiles` of this config element.
452
- * @property {Record<string, boolean>|undefined} env The environment settings.
453
- * @property {Record<string, GlobalConf>|undefined} globals The global variable settings.
454
- * @property {IgnorePattern|undefined} ignorePattern The ignore patterns.
455
- * @property {boolean|undefined} noInlineConfig The flag that disables directive comments.
456
- * @property {DependentParser|undefined} parser The parser loader.
457
- * @property {Object|undefined} parserOptions The parser options.
458
- * @property {Record<string, DependentPlugin>|undefined} plugins The plugin loaders.
459
- * @property {string|undefined} processor The processor name to refer plugin's processor.
460
- * @property {boolean|undefined} reportUnusedDisableDirectives The flag to report unused `eslint-disable` comments.
461
- * @property {boolean|undefined} root The flag to express root.
462
- * @property {Record<string, RuleConf>|undefined} rules The rule settings
463
- * @property {Object|undefined} settings The shared settings.
464
- * @property {"config" | "ignore" | "implicit-processor"} type The element type.
465
- */
466
-
467
- /**
468
- * @typedef {Object} ConfigArrayInternalSlots
469
- * @property {Map<string, ExtractedConfig>} cache The cache to extract configs.
470
- * @property {ReadonlyMap<string, Environment>|null} envMap The map from environment ID to environment definition.
471
- * @property {ReadonlyMap<string, Processor>|null} processorMap The map from processor ID to environment definition.
472
- * @property {ReadonlyMap<string, Rule>|null} ruleMap The map from rule ID to rule definition.
473
- */
474
-
475
- /** @type {WeakMap<ConfigArray, ConfigArrayInternalSlots>} */
476
- const internalSlotsMap$2 = new class extends WeakMap {
477
- get(key) {
478
- let value = super.get(key);
479
-
480
- if (!value) {
481
- value = {
482
- cache: new Map(),
483
- envMap: null,
484
- processorMap: null,
485
- ruleMap: null
486
- };
487
- super.set(key, value);
488
- }
489
-
490
- return value;
491
- }
492
- }();
493
-
494
- /**
495
- * Get the indices which are matched to a given file.
496
- * @param {ConfigArrayElement[]} elements The elements.
497
- * @param {string} filePath The path to a target file.
498
- * @returns {number[]} The indices.
499
- */
500
- function getMatchedIndices(elements, filePath) {
501
- const indices = [];
502
-
503
- for (let i = elements.length - 1; i >= 0; --i) {
504
- const element = elements[i];
505
-
506
- if (!element.criteria || (filePath && element.criteria.test(filePath))) {
507
- indices.push(i);
508
- }
509
- }
510
-
511
- return indices;
512
- }
513
-
514
- /**
515
- * Check if a value is a non-null object.
516
- * @param {any} x The value to check.
517
- * @returns {boolean} `true` if the value is a non-null object.
518
- */
519
- function isNonNullObject(x) {
520
- return typeof x === "object" && x !== null;
521
- }
522
-
523
- /**
524
- * Merge two objects.
525
- *
526
- * Assign every property values of `y` to `x` if `x` doesn't have the property.
527
- * If `x`'s property value is an object, it does recursive.
528
- * @param {Object} target The destination to merge
529
- * @param {Object|undefined} source The source to merge.
530
- * @returns {void}
531
- */
532
- function mergeWithoutOverwrite(target, source) {
533
- if (!isNonNullObject(source)) {
534
- return;
535
- }
536
-
537
- for (const key of Object.keys(source)) {
538
- if (key === "__proto__") {
539
- continue;
540
- }
541
-
542
- if (isNonNullObject(target[key])) {
543
- mergeWithoutOverwrite(target[key], source[key]);
544
- } else if (target[key] === void 0) {
545
- if (isNonNullObject(source[key])) {
546
- target[key] = Array.isArray(source[key]) ? [] : {};
547
- mergeWithoutOverwrite(target[key], source[key]);
548
- } else if (source[key] !== void 0) {
549
- target[key] = source[key];
550
- }
551
- }
552
- }
553
- }
554
-
555
- /**
556
- * The error for plugin conflicts.
557
- */
558
- class PluginConflictError extends Error {
559
-
560
- /**
561
- * Initialize this error object.
562
- * @param {string} pluginId The plugin ID.
563
- * @param {{filePath:string, importerName:string}[]} plugins The resolved plugins.
564
- */
565
- constructor(pluginId, plugins) {
566
- super(`Plugin "${pluginId}" was conflicted between ${plugins.map(p => `"${p.importerName}"`).join(" and ")}.`);
567
- this.messageTemplate = "plugin-conflict";
568
- this.messageData = { pluginId, plugins };
569
- }
570
- }
571
-
572
- /**
573
- * Merge plugins.
574
- * `target`'s definition is prior to `source`'s.
575
- * @param {Record<string, DependentPlugin>} target The destination to merge
576
- * @param {Record<string, DependentPlugin>|undefined} source The source to merge.
577
- * @returns {void}
578
- */
579
- function mergePlugins(target, source) {
580
- if (!isNonNullObject(source)) {
581
- return;
582
- }
583
-
584
- for (const key of Object.keys(source)) {
585
- if (key === "__proto__") {
586
- continue;
587
- }
588
- const targetValue = target[key];
589
- const sourceValue = source[key];
590
-
591
- // Adopt the plugin which was found at first.
592
- if (targetValue === void 0) {
593
- if (sourceValue.error) {
594
- throw sourceValue.error;
595
- }
596
- target[key] = sourceValue;
597
- } else if (sourceValue.filePath !== targetValue.filePath) {
598
- throw new PluginConflictError(key, [
599
- {
600
- filePath: targetValue.filePath,
601
- importerName: targetValue.importerName
602
- },
603
- {
604
- filePath: sourceValue.filePath,
605
- importerName: sourceValue.importerName
606
- }
607
- ]);
608
- }
609
- }
610
- }
611
-
612
- /**
613
- * Merge rule configs.
614
- * `target`'s definition is prior to `source`'s.
615
- * @param {Record<string, Array>} target The destination to merge
616
- * @param {Record<string, RuleConf>|undefined} source The source to merge.
617
- * @returns {void}
618
- */
619
- function mergeRuleConfigs(target, source) {
620
- if (!isNonNullObject(source)) {
621
- return;
622
- }
623
-
624
- for (const key of Object.keys(source)) {
625
- if (key === "__proto__") {
626
- continue;
627
- }
628
- const targetDef = target[key];
629
- const sourceDef = source[key];
630
-
631
- // Adopt the rule config which was found at first.
632
- if (targetDef === void 0) {
633
- if (Array.isArray(sourceDef)) {
634
- target[key] = [...sourceDef];
635
- } else {
636
- target[key] = [sourceDef];
637
- }
638
-
639
- /*
640
- * If the first found rule config is severity only and the current rule
641
- * config has options, merge the severity and the options.
642
- */
643
- } else if (
644
- targetDef.length === 1 &&
645
- Array.isArray(sourceDef) &&
646
- sourceDef.length >= 2
647
- ) {
648
- targetDef.push(...sourceDef.slice(1));
649
- }
650
- }
651
- }
652
-
653
- /**
654
- * Create the extracted config.
655
- * @param {ConfigArray} instance The config elements.
656
- * @param {number[]} indices The indices to use.
657
- * @returns {ExtractedConfig} The extracted config.
658
- */
659
- function createConfig(instance, indices) {
660
- const config = new ExtractedConfig();
661
- const ignorePatterns = [];
662
-
663
- // Merge elements.
664
- for (const index of indices) {
665
- const element = instance[index];
666
-
667
- // Adopt the parser which was found at first.
668
- if (!config.parser && element.parser) {
669
- if (element.parser.error) {
670
- throw element.parser.error;
671
- }
672
- config.parser = element.parser;
673
- }
674
-
675
- // Adopt the processor which was found at first.
676
- if (!config.processor && element.processor) {
677
- config.processor = element.processor;
678
- }
679
-
680
- // Adopt the noInlineConfig which was found at first.
681
- if (config.noInlineConfig === void 0 && element.noInlineConfig !== void 0) {
682
- config.noInlineConfig = element.noInlineConfig;
683
- config.configNameOfNoInlineConfig = element.name;
684
- }
685
-
686
- // Adopt the reportUnusedDisableDirectives which was found at first.
687
- if (config.reportUnusedDisableDirectives === void 0 && element.reportUnusedDisableDirectives !== void 0) {
688
- config.reportUnusedDisableDirectives = element.reportUnusedDisableDirectives;
689
- }
690
-
691
- // Collect ignorePatterns
692
- if (element.ignorePattern) {
693
- ignorePatterns.push(element.ignorePattern);
694
- }
695
-
696
- // Merge others.
697
- mergeWithoutOverwrite(config.env, element.env);
698
- mergeWithoutOverwrite(config.globals, element.globals);
699
- mergeWithoutOverwrite(config.parserOptions, element.parserOptions);
700
- mergeWithoutOverwrite(config.settings, element.settings);
701
- mergePlugins(config.plugins, element.plugins);
702
- mergeRuleConfigs(config.rules, element.rules);
703
- }
704
-
705
- // Create the predicate function for ignore patterns.
706
- if (ignorePatterns.length > 0) {
707
- config.ignores = IgnorePattern.createIgnore(ignorePatterns.reverse());
708
- }
709
-
710
- return config;
711
- }
712
-
713
- /**
714
- * Collect definitions.
715
- * @template T, U
716
- * @param {string} pluginId The plugin ID for prefix.
717
- * @param {Record<string,T>} defs The definitions to collect.
718
- * @param {Map<string, U>} map The map to output.
719
- * @returns {void}
720
- */
721
- function collect(pluginId, defs, map) {
722
- if (defs) {
723
- const prefix = pluginId && `${pluginId}/`;
724
-
725
- for (const [key, value] of Object.entries(defs)) {
726
- map.set(`${prefix}${key}`, value);
727
- }
728
- }
729
- }
730
-
731
- /**
732
- * Delete the mutation methods from a given map.
733
- * @param {Map<any, any>} map The map object to delete.
734
- * @returns {void}
735
- */
736
- function deleteMutationMethods(map) {
737
- Object.defineProperties(map, {
738
- clear: { configurable: true, value: void 0 },
739
- delete: { configurable: true, value: void 0 },
740
- set: { configurable: true, value: void 0 }
741
- });
742
- }
743
-
744
- /**
745
- * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
746
- * @param {ConfigArrayElement[]} elements The config elements.
747
- * @param {ConfigArrayInternalSlots} slots The internal slots.
748
- * @returns {void}
749
- */
750
- function initPluginMemberMaps(elements, slots) {
751
- const processed = new Set();
752
-
753
- slots.envMap = new Map();
754
- slots.processorMap = new Map();
755
- slots.ruleMap = new Map();
756
-
757
- for (const element of elements) {
758
- if (!element.plugins) {
759
- continue;
760
- }
761
-
762
- for (const [pluginId, value] of Object.entries(element.plugins)) {
763
- const plugin = value.definition;
764
-
765
- if (!plugin || processed.has(pluginId)) {
766
- continue;
767
- }
768
- processed.add(pluginId);
769
-
770
- collect(pluginId, plugin.environments, slots.envMap);
771
- collect(pluginId, plugin.processors, slots.processorMap);
772
- collect(pluginId, plugin.rules, slots.ruleMap);
773
- }
774
- }
775
-
776
- deleteMutationMethods(slots.envMap);
777
- deleteMutationMethods(slots.processorMap);
778
- deleteMutationMethods(slots.ruleMap);
779
- }
780
-
781
- /**
782
- * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
783
- * @param {ConfigArray} instance The config elements.
784
- * @returns {ConfigArrayInternalSlots} The extracted config.
785
- */
786
- function ensurePluginMemberMaps(instance) {
787
- const slots = internalSlotsMap$2.get(instance);
788
-
789
- if (!slots.ruleMap) {
790
- initPluginMemberMaps(instance, slots);
791
- }
792
-
793
- return slots;
794
- }
795
-
796
- //------------------------------------------------------------------------------
797
- // Public Interface
798
- //------------------------------------------------------------------------------
799
-
800
- /**
801
- * The Config Array.
802
- *
803
- * `ConfigArray` instance contains all settings, parsers, and plugins.
804
- * You need to call `ConfigArray#extractConfig(filePath)` method in order to
805
- * extract, merge and get only the config data which is related to an arbitrary
806
- * file.
807
- * @extends {Array<ConfigArrayElement>}
808
- */
809
- class ConfigArray extends Array {
810
-
811
- /**
812
- * Get the plugin environments.
813
- * The returned map cannot be mutated.
814
- * @type {ReadonlyMap<string, Environment>} The plugin environments.
815
- */
816
- get pluginEnvironments() {
817
- return ensurePluginMemberMaps(this).envMap;
818
- }
819
-
820
- /**
821
- * Get the plugin processors.
822
- * The returned map cannot be mutated.
823
- * @type {ReadonlyMap<string, Processor>} The plugin processors.
824
- */
825
- get pluginProcessors() {
826
- return ensurePluginMemberMaps(this).processorMap;
827
- }
828
-
829
- /**
830
- * Get the plugin rules.
831
- * The returned map cannot be mutated.
832
- * @returns {ReadonlyMap<string, Rule>} The plugin rules.
833
- */
834
- get pluginRules() {
835
- return ensurePluginMemberMaps(this).ruleMap;
836
- }
837
-
838
- /**
839
- * Check if this config has `root` flag.
840
- * @returns {boolean} `true` if this config array is root.
841
- */
842
- isRoot() {
843
- for (let i = this.length - 1; i >= 0; --i) {
844
- const root = this[i].root;
845
-
846
- if (typeof root === "boolean") {
847
- return root;
848
- }
849
- }
850
- return false;
851
- }
852
-
853
- /**
854
- * Extract the config data which is related to a given file.
855
- * @param {string} filePath The absolute path to the target file.
856
- * @returns {ExtractedConfig} The extracted config data.
857
- */
858
- extractConfig(filePath) {
859
- const { cache } = internalSlotsMap$2.get(this);
860
- const indices = getMatchedIndices(this, filePath);
861
- const cacheKey = indices.join(",");
862
-
863
- if (!cache.has(cacheKey)) {
864
- cache.set(cacheKey, createConfig(this, indices));
865
- }
866
-
867
- return cache.get(cacheKey);
868
- }
869
-
870
- /**
871
- * Check if a given path is an additional lint target.
872
- * @param {string} filePath The absolute path to the target file.
873
- * @returns {boolean} `true` if the file is an additional lint target.
874
- */
875
- isAdditionalTargetPath(filePath) {
876
- for (const { criteria, type } of this) {
877
- if (
878
- type === "config" &&
879
- criteria &&
880
- !criteria.endsWithWildcard &&
881
- criteria.test(filePath)
882
- ) {
883
- return true;
884
- }
885
- }
886
- return false;
887
- }
888
- }
889
-
890
- /**
891
- * Get the used extracted configs.
892
- * CLIEngine will use this method to collect used deprecated rules.
893
- * @param {ConfigArray} instance The config array object to get.
894
- * @returns {ExtractedConfig[]} The used extracted configs.
895
- * @private
896
- */
897
- function getUsedExtractedConfigs(instance) {
898
- const { cache } = internalSlotsMap$2.get(instance);
899
-
900
- return Array.from(cache.values());
901
- }
902
-
903
- /**
904
- * @fileoverview `ConfigDependency` class.
905
- *
906
- * `ConfigDependency` class expresses a loaded parser or plugin.
907
- *
908
- * If the parser or plugin was loaded successfully, it has `definition` property
909
- * and `filePath` property. Otherwise, it has `error` property.
910
- *
911
- * When `JSON.stringify()` converted a `ConfigDependency` object to a JSON, it
912
- * omits `definition` property.
913
- *
914
- * `ConfigArrayFactory` creates `ConfigDependency` objects when it loads parsers
915
- * or plugins.
916
- *
917
- * @author Toru Nagashima <https://github.com/mysticatea>
918
- */
919
-
920
- /**
921
- * The class is to store parsers or plugins.
922
- * This class hides the loaded object from `JSON.stringify()` and `console.log`.
923
- * @template T
924
- */
925
- class ConfigDependency {
926
-
927
- /**
928
- * Initialize this instance.
929
- * @param {Object} data The dependency data.
930
- * @param {T} [data.definition] The dependency if the loading succeeded.
931
- * @param {T} [data.original] The original, non-normalized dependency if the loading succeeded.
932
- * @param {Error} [data.error] The error object if the loading failed.
933
- * @param {string} [data.filePath] The actual path to the dependency if the loading succeeded.
934
- * @param {string} data.id The ID of this dependency.
935
- * @param {string} data.importerName The name of the config file which loads this dependency.
936
- * @param {string} data.importerPath The path to the config file which loads this dependency.
937
- */
938
- constructor({
939
- definition = null,
940
- original = null,
941
- error = null,
942
- filePath = null,
943
- id,
944
- importerName,
945
- importerPath
946
- }) {
947
-
948
- /**
949
- * The loaded dependency if the loading succeeded.
950
- * @type {T|null}
951
- */
952
- this.definition = definition;
953
-
954
- /**
955
- * The original dependency as loaded directly from disk if the loading succeeded.
956
- * @type {T|null}
957
- */
958
- this.original = original;
959
-
960
- /**
961
- * The error object if the loading failed.
962
- * @type {Error|null}
963
- */
964
- this.error = error;
965
-
966
- /**
967
- * The loaded dependency if the loading succeeded.
968
- * @type {string|null}
969
- */
970
- this.filePath = filePath;
971
-
972
- /**
973
- * The ID of this dependency.
974
- * @type {string}
975
- */
976
- this.id = id;
977
-
978
- /**
979
- * The name of the config file which loads this dependency.
980
- * @type {string}
981
- */
982
- this.importerName = importerName;
983
-
984
- /**
985
- * The path to the config file which loads this dependency.
986
- * @type {string}
987
- */
988
- this.importerPath = importerPath;
989
- }
990
-
991
- // eslint-disable-next-line jsdoc/require-description
992
- /**
993
- * @returns {Object} a JSON compatible object.
994
- */
995
- toJSON() {
996
- const obj = this[util__default["default"].inspect.custom]();
997
-
998
- // Display `error.message` (`Error#message` is unenumerable).
999
- if (obj.error instanceof Error) {
1000
- obj.error = { ...obj.error, message: obj.error.message };
1001
- }
1002
-
1003
- return obj;
1004
- }
1005
-
1006
- // eslint-disable-next-line jsdoc/require-description
1007
- /**
1008
- * @returns {Object} an object to display by `console.log()`.
1009
- */
1010
- [util__default["default"].inspect.custom]() {
1011
- const {
1012
- definition: _ignore1, // eslint-disable-line no-unused-vars
1013
- original: _ignore2, // eslint-disable-line no-unused-vars
1014
- ...obj
1015
- } = this;
1016
-
1017
- return obj;
1018
- }
1019
- }
1020
-
1021
- /**
1022
- * @fileoverview `OverrideTester` class.
1023
- *
1024
- * `OverrideTester` class handles `files` property and `excludedFiles` property
1025
- * of `overrides` config.
1026
- *
1027
- * It provides one method.
1028
- *
1029
- * - `test(filePath)`
1030
- * Test if a file path matches the pair of `files` property and
1031
- * `excludedFiles` property. The `filePath` argument must be an absolute
1032
- * path.
1033
- *
1034
- * `ConfigArrayFactory` creates `OverrideTester` objects when it processes
1035
- * `overrides` properties.
1036
- *
1037
- * @author Toru Nagashima <https://github.com/mysticatea>
1038
- */
1039
-
1040
- const { Minimatch } = minimatch__default["default"];
1041
-
1042
- const minimatchOpts = { dot: true, matchBase: true };
1043
-
1044
- /**
1045
- * @typedef {Object} Pattern
1046
- * @property {InstanceType<Minimatch>[] | null} includes The positive matchers.
1047
- * @property {InstanceType<Minimatch>[] | null} excludes The negative matchers.
1048
- */
1049
-
1050
- /**
1051
- * Normalize a given pattern to an array.
1052
- * @param {string|string[]|undefined} patterns A glob pattern or an array of glob patterns.
1053
- * @returns {string[]|null} Normalized patterns.
1054
- * @private
1055
- */
1056
- function normalizePatterns(patterns) {
1057
- if (Array.isArray(patterns)) {
1058
- return patterns.filter(Boolean);
1059
- }
1060
- if (typeof patterns === "string" && patterns) {
1061
- return [patterns];
1062
- }
1063
- return [];
1064
- }
1065
-
1066
- /**
1067
- * Create the matchers of given patterns.
1068
- * @param {string[]} patterns The patterns.
1069
- * @returns {InstanceType<Minimatch>[] | null} The matchers.
1070
- */
1071
- function toMatcher(patterns) {
1072
- if (patterns.length === 0) {
1073
- return null;
1074
- }
1075
- return patterns.map(pattern => {
1076
- if (/^\.[/\\]/u.test(pattern)) {
1077
- return new Minimatch(
1078
- pattern.slice(2),
1079
-
1080
- // `./*.js` should not match with `subdir/foo.js`
1081
- { ...minimatchOpts, matchBase: false }
1082
- );
1083
- }
1084
- return new Minimatch(pattern, minimatchOpts);
1085
- });
1086
- }
1087
-
1088
- /**
1089
- * Convert a given matcher to string.
1090
- * @param {Pattern} matchers The matchers.
1091
- * @returns {string} The string expression of the matcher.
1092
- */
1093
- function patternToJson({ includes, excludes }) {
1094
- return {
1095
- includes: includes && includes.map(m => m.pattern),
1096
- excludes: excludes && excludes.map(m => m.pattern)
1097
- };
1098
- }
1099
-
1100
- /**
1101
- * The class to test given paths are matched by the patterns.
1102
- */
1103
- class OverrideTester {
1104
-
1105
- /**
1106
- * Create a tester with given criteria.
1107
- * If there are no criteria, returns `null`.
1108
- * @param {string|string[]} files The glob patterns for included files.
1109
- * @param {string|string[]} excludedFiles The glob patterns for excluded files.
1110
- * @param {string} basePath The path to the base directory to test paths.
1111
- * @returns {OverrideTester|null} The created instance or `null`.
1112
- */
1113
- static create(files, excludedFiles, basePath) {
1114
- const includePatterns = normalizePatterns(files);
1115
- const excludePatterns = normalizePatterns(excludedFiles);
1116
- let endsWithWildcard = false;
1117
-
1118
- if (includePatterns.length === 0) {
1119
- return null;
1120
- }
1121
-
1122
- // Rejects absolute paths or relative paths to parents.
1123
- for (const pattern of includePatterns) {
1124
- if (path__default["default"].isAbsolute(pattern) || pattern.includes("..")) {
1125
- throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);
1126
- }
1127
- if (pattern.endsWith("*")) {
1128
- endsWithWildcard = true;
1129
- }
1130
- }
1131
- for (const pattern of excludePatterns) {
1132
- if (path__default["default"].isAbsolute(pattern) || pattern.includes("..")) {
1133
- throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);
1134
- }
1135
- }
1136
-
1137
- const includes = toMatcher(includePatterns);
1138
- const excludes = toMatcher(excludePatterns);
1139
-
1140
- return new OverrideTester(
1141
- [{ includes, excludes }],
1142
- basePath,
1143
- endsWithWildcard
1144
- );
1145
- }
1146
-
1147
- /**
1148
- * Combine two testers by logical and.
1149
- * If either of the testers was `null`, returns the other tester.
1150
- * The `basePath` property of the two must be the same value.
1151
- * @param {OverrideTester|null} a A tester.
1152
- * @param {OverrideTester|null} b Another tester.
1153
- * @returns {OverrideTester|null} Combined tester.
1154
- */
1155
- static and(a, b) {
1156
- if (!b) {
1157
- return a && new OverrideTester(
1158
- a.patterns,
1159
- a.basePath,
1160
- a.endsWithWildcard
1161
- );
1162
- }
1163
- if (!a) {
1164
- return new OverrideTester(
1165
- b.patterns,
1166
- b.basePath,
1167
- b.endsWithWildcard
1168
- );
1169
- }
1170
-
1171
- assert__default["default"].strictEqual(a.basePath, b.basePath);
1172
- return new OverrideTester(
1173
- a.patterns.concat(b.patterns),
1174
- a.basePath,
1175
- a.endsWithWildcard || b.endsWithWildcard
1176
- );
1177
- }
1178
-
1179
- /**
1180
- * Initialize this instance.
1181
- * @param {Pattern[]} patterns The matchers.
1182
- * @param {string} basePath The base path.
1183
- * @param {boolean} endsWithWildcard If `true` then a pattern ends with `*`.
1184
- */
1185
- constructor(patterns, basePath, endsWithWildcard = false) {
1186
-
1187
- /** @type {Pattern[]} */
1188
- this.patterns = patterns;
1189
-
1190
- /** @type {string} */
1191
- this.basePath = basePath;
1192
-
1193
- /** @type {boolean} */
1194
- this.endsWithWildcard = endsWithWildcard;
1195
- }
1196
-
1197
- /**
1198
- * Test if a given path is matched or not.
1199
- * @param {string} filePath The absolute path to the target file.
1200
- * @returns {boolean} `true` if the path was matched.
1201
- */
1202
- test(filePath) {
1203
- if (typeof filePath !== "string" || !path__default["default"].isAbsolute(filePath)) {
1204
- throw new Error(`'filePath' should be an absolute path, but got ${filePath}.`);
1205
- }
1206
- const relativePath = path__default["default"].relative(this.basePath, filePath);
1207
-
1208
- return this.patterns.every(({ includes, excludes }) => (
1209
- (!includes || includes.some(m => m.match(relativePath))) &&
1210
- (!excludes || !excludes.some(m => m.match(relativePath)))
1211
- ));
1212
- }
1213
-
1214
- // eslint-disable-next-line jsdoc/require-description
1215
- /**
1216
- * @returns {Object} a JSON compatible object.
1217
- */
1218
- toJSON() {
1219
- if (this.patterns.length === 1) {
1220
- return {
1221
- ...patternToJson(this.patterns[0]),
1222
- basePath: this.basePath
1223
- };
1224
- }
1225
- return {
1226
- AND: this.patterns.map(patternToJson),
1227
- basePath: this.basePath
1228
- };
1229
- }
1230
-
1231
- // eslint-disable-next-line jsdoc/require-description
1232
- /**
1233
- * @returns {Object} an object to display by `console.log()`.
1234
- */
1235
- [util__default["default"].inspect.custom]() {
1236
- return this.toJSON();
1237
- }
1238
- }
1239
-
1240
- /**
1241
- * @fileoverview `ConfigArray` class.
1242
- * @author Toru Nagashima <https://github.com/mysticatea>
1243
- */
1244
-
1245
- /**
1246
- * @fileoverview Config file operations. This file must be usable in the browser,
1247
- * so no Node-specific code can be here.
1248
- * @author Nicholas C. Zakas
1249
- */
1250
-
1251
- //------------------------------------------------------------------------------
1252
- // Private
1253
- //------------------------------------------------------------------------------
1254
-
1255
- const RULE_SEVERITY_STRINGS = ["off", "warn", "error"],
1256
- RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => {
1257
- map[value] = index;
1258
- return map;
1259
- }, {}),
1260
- VALID_SEVERITIES = [0, 1, 2, "off", "warn", "error"];
1261
-
1262
- //------------------------------------------------------------------------------
1263
- // Public Interface
1264
- //------------------------------------------------------------------------------
1265
-
1266
- /**
1267
- * Normalizes the severity value of a rule's configuration to a number
1268
- * @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally
1269
- * received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0),
1270
- * the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array
1271
- * whose first element is one of the above values. Strings are matched case-insensitively.
1272
- * @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0.
1273
- */
1274
- function getRuleSeverity(ruleConfig) {
1275
- const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
1276
-
1277
- if (severityValue === 0 || severityValue === 1 || severityValue === 2) {
1278
- return severityValue;
1279
- }
1280
-
1281
- if (typeof severityValue === "string") {
1282
- return RULE_SEVERITY[severityValue.toLowerCase()] || 0;
1283
- }
1284
-
1285
- return 0;
1286
- }
1287
-
1288
- /**
1289
- * Converts old-style severity settings (0, 1, 2) into new-style
1290
- * severity settings (off, warn, error) for all rules. Assumption is that severity
1291
- * values have already been validated as correct.
1292
- * @param {Object} config The config object to normalize.
1293
- * @returns {void}
1294
- */
1295
- function normalizeToStrings(config) {
1296
-
1297
- if (config.rules) {
1298
- Object.keys(config.rules).forEach(ruleId => {
1299
- const ruleConfig = config.rules[ruleId];
1300
-
1301
- if (typeof ruleConfig === "number") {
1302
- config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0];
1303
- } else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === "number") {
1304
- ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0];
1305
- }
1306
- });
1307
- }
1308
- }
1309
-
1310
- /**
1311
- * Determines if the severity for the given rule configuration represents an error.
1312
- * @param {int|string|Array} ruleConfig The configuration for an individual rule.
1313
- * @returns {boolean} True if the rule represents an error, false if not.
1314
- */
1315
- function isErrorSeverity(ruleConfig) {
1316
- return getRuleSeverity(ruleConfig) === 2;
1317
- }
1318
-
1319
- /**
1320
- * Checks whether a given config has valid severity or not.
1321
- * @param {number|string|Array} ruleConfig The configuration for an individual rule.
1322
- * @returns {boolean} `true` if the configuration has valid severity.
1323
- */
1324
- function isValidSeverity(ruleConfig) {
1325
- let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
1326
-
1327
- if (typeof severity === "string") {
1328
- severity = severity.toLowerCase();
1329
- }
1330
- return VALID_SEVERITIES.indexOf(severity) !== -1;
1331
- }
1332
-
1333
- /**
1334
- * Checks whether every rule of a given config has valid severity or not.
1335
- * @param {Object} config The configuration for rules.
1336
- * @returns {boolean} `true` if the configuration has valid severity.
1337
- */
1338
- function isEverySeverityValid(config) {
1339
- return Object.keys(config).every(ruleId => isValidSeverity(config[ruleId]));
1340
- }
1341
-
1342
- /**
1343
- * Normalizes a value for a global in a config
1344
- * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in
1345
- * a global directive comment
1346
- * @returns {("readable"|"writeable"|"off")} The value normalized as a string
1347
- * @throws Error if global value is invalid
1348
- */
1349
- function normalizeConfigGlobal(configuredValue) {
1350
- switch (configuredValue) {
1351
- case "off":
1352
- return "off";
1353
-
1354
- case true:
1355
- case "true":
1356
- case "writeable":
1357
- case "writable":
1358
- return "writable";
1359
-
1360
- case null:
1361
- case false:
1362
- case "false":
1363
- case "readable":
1364
- case "readonly":
1365
- return "readonly";
1366
-
1367
- default:
1368
- throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`);
1369
- }
1370
- }
1371
-
1372
- var ConfigOps = {
1373
- __proto__: null,
1374
- getRuleSeverity: getRuleSeverity,
1375
- normalizeToStrings: normalizeToStrings,
1376
- isErrorSeverity: isErrorSeverity,
1377
- isValidSeverity: isValidSeverity,
1378
- isEverySeverityValid: isEverySeverityValid,
1379
- normalizeConfigGlobal: normalizeConfigGlobal
1380
- };
1381
-
1382
- /**
1383
- * @fileoverview Provide the function that emits deprecation warnings.
1384
- * @author Toru Nagashima <http://github.com/mysticatea>
1385
- */
1386
-
1387
- //------------------------------------------------------------------------------
1388
- // Private
1389
- //------------------------------------------------------------------------------
1390
-
1391
- // Defitions for deprecation warnings.
1392
- const deprecationWarningMessages = {
1393
- ESLINT_LEGACY_ECMAFEATURES:
1394
- "The 'ecmaFeatures' config file property is deprecated and has no effect.",
1395
- ESLINT_PERSONAL_CONFIG_LOAD:
1396
- "'~/.eslintrc.*' config files have been deprecated. " +
1397
- "Please use a config file per project or the '--config' option.",
1398
- ESLINT_PERSONAL_CONFIG_SUPPRESS:
1399
- "'~/.eslintrc.*' config files have been deprecated. " +
1400
- "Please remove it or add 'root:true' to the config files in your " +
1401
- "projects in order to avoid loading '~/.eslintrc.*' accidentally."
1402
- };
1403
-
1404
- const sourceFileErrorCache = new Set();
1405
-
1406
- /**
1407
- * Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted
1408
- * for each unique file path, but repeated invocations with the same file path have no effect.
1409
- * No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active.
1410
- * @param {string} source The name of the configuration source to report the warning for.
1411
- * @param {string} errorCode The warning message to show.
1412
- * @returns {void}
1413
- */
1414
- function emitDeprecationWarning(source, errorCode) {
1415
- const cacheKey = JSON.stringify({ source, errorCode });
1416
-
1417
- if (sourceFileErrorCache.has(cacheKey)) {
1418
- return;
1419
- }
1420
- sourceFileErrorCache.add(cacheKey);
1421
-
1422
- const rel = path__default["default"].relative(process.cwd(), source);
1423
- const message = deprecationWarningMessages[errorCode];
1424
-
1425
- process.emitWarning(
1426
- `${message} (found in "${rel}")`,
1427
- "DeprecationWarning",
1428
- errorCode
1429
- );
1430
- }
1431
-
1432
- /**
1433
- * @fileoverview The instance of Ajv validator.
1434
- * @author Evgeny Poberezkin
1435
- */
1436
-
1437
- //-----------------------------------------------------------------------------
1438
- // Helpers
1439
- //-----------------------------------------------------------------------------
1440
-
1441
- /*
1442
- * Copied from ajv/lib/refs/json-schema-draft-04.json
1443
- * The MIT License (MIT)
1444
- * Copyright (c) 2015-2017 Evgeny Poberezkin
1445
- */
1446
- const metaSchema = {
1447
- id: "http://json-schema.org/draft-04/schema#",
1448
- $schema: "http://json-schema.org/draft-04/schema#",
1449
- description: "Core schema meta-schema",
1450
- definitions: {
1451
- schemaArray: {
1452
- type: "array",
1453
- minItems: 1,
1454
- items: { $ref: "#" }
1455
- },
1456
- positiveInteger: {
1457
- type: "integer",
1458
- minimum: 0
1459
- },
1460
- positiveIntegerDefault0: {
1461
- allOf: [{ $ref: "#/definitions/positiveInteger" }, { default: 0 }]
1462
- },
1463
- simpleTypes: {
1464
- enum: ["array", "boolean", "integer", "null", "number", "object", "string"]
1465
- },
1466
- stringArray: {
1467
- type: "array",
1468
- items: { type: "string" },
1469
- minItems: 1,
1470
- uniqueItems: true
1471
- }
1472
- },
1473
- type: "object",
1474
- properties: {
1475
- id: {
1476
- type: "string"
1477
- },
1478
- $schema: {
1479
- type: "string"
1480
- },
1481
- title: {
1482
- type: "string"
1483
- },
1484
- description: {
1485
- type: "string"
1486
- },
1487
- default: { },
1488
- multipleOf: {
1489
- type: "number",
1490
- minimum: 0,
1491
- exclusiveMinimum: true
1492
- },
1493
- maximum: {
1494
- type: "number"
1495
- },
1496
- exclusiveMaximum: {
1497
- type: "boolean",
1498
- default: false
1499
- },
1500
- minimum: {
1501
- type: "number"
1502
- },
1503
- exclusiveMinimum: {
1504
- type: "boolean",
1505
- default: false
1506
- },
1507
- maxLength: { $ref: "#/definitions/positiveInteger" },
1508
- minLength: { $ref: "#/definitions/positiveIntegerDefault0" },
1509
- pattern: {
1510
- type: "string",
1511
- format: "regex"
1512
- },
1513
- additionalItems: {
1514
- anyOf: [
1515
- { type: "boolean" },
1516
- { $ref: "#" }
1517
- ],
1518
- default: { }
1519
- },
1520
- items: {
1521
- anyOf: [
1522
- { $ref: "#" },
1523
- { $ref: "#/definitions/schemaArray" }
1524
- ],
1525
- default: { }
1526
- },
1527
- maxItems: { $ref: "#/definitions/positiveInteger" },
1528
- minItems: { $ref: "#/definitions/positiveIntegerDefault0" },
1529
- uniqueItems: {
1530
- type: "boolean",
1531
- default: false
1532
- },
1533
- maxProperties: { $ref: "#/definitions/positiveInteger" },
1534
- minProperties: { $ref: "#/definitions/positiveIntegerDefault0" },
1535
- required: { $ref: "#/definitions/stringArray" },
1536
- additionalProperties: {
1537
- anyOf: [
1538
- { type: "boolean" },
1539
- { $ref: "#" }
1540
- ],
1541
- default: { }
1542
- },
1543
- definitions: {
1544
- type: "object",
1545
- additionalProperties: { $ref: "#" },
1546
- default: { }
1547
- },
1548
- properties: {
1549
- type: "object",
1550
- additionalProperties: { $ref: "#" },
1551
- default: { }
1552
- },
1553
- patternProperties: {
1554
- type: "object",
1555
- additionalProperties: { $ref: "#" },
1556
- default: { }
1557
- },
1558
- dependencies: {
1559
- type: "object",
1560
- additionalProperties: {
1561
- anyOf: [
1562
- { $ref: "#" },
1563
- { $ref: "#/definitions/stringArray" }
1564
- ]
1565
- }
1566
- },
1567
- enum: {
1568
- type: "array",
1569
- minItems: 1,
1570
- uniqueItems: true
1571
- },
1572
- type: {
1573
- anyOf: [
1574
- { $ref: "#/definitions/simpleTypes" },
1575
- {
1576
- type: "array",
1577
- items: { $ref: "#/definitions/simpleTypes" },
1578
- minItems: 1,
1579
- uniqueItems: true
1580
- }
1581
- ]
1582
- },
1583
- format: { type: "string" },
1584
- allOf: { $ref: "#/definitions/schemaArray" },
1585
- anyOf: { $ref: "#/definitions/schemaArray" },
1586
- oneOf: { $ref: "#/definitions/schemaArray" },
1587
- not: { $ref: "#" }
1588
- },
1589
- dependencies: {
1590
- exclusiveMaximum: ["maximum"],
1591
- exclusiveMinimum: ["minimum"]
1592
- },
1593
- default: { }
1594
- };
1595
-
1596
- //------------------------------------------------------------------------------
1597
- // Public Interface
1598
- //------------------------------------------------------------------------------
1599
-
1600
- var ajvOrig = (additionalOptions = {}) => {
1601
- const ajv = new Ajv__default["default"]({
1602
- meta: false,
1603
- useDefaults: true,
1604
- validateSchema: false,
1605
- missingRefs: "ignore",
1606
- verbose: true,
1607
- schemaId: "auto",
1608
- ...additionalOptions
1609
- });
1610
-
1611
- ajv.addMetaSchema(metaSchema);
1612
- // eslint-disable-next-line no-underscore-dangle
1613
- ajv._opts.defaultMeta = metaSchema.id;
1614
-
1615
- return ajv;
1616
- };
1617
-
1618
- /**
1619
- * @fileoverview Defines a schema for configs.
1620
- * @author Sylvan Mably
1621
- */
1622
-
1623
- const baseConfigProperties = {
1624
- $schema: { type: "string" },
1625
- env: { type: "object" },
1626
- extends: { $ref: "#/definitions/stringOrStrings" },
1627
- globals: { type: "object" },
1628
- overrides: {
1629
- type: "array",
1630
- items: { $ref: "#/definitions/overrideConfig" },
1631
- additionalItems: false
1632
- },
1633
- parser: { type: ["string", "null"] },
1634
- parserOptions: { type: "object" },
1635
- plugins: { type: "array" },
1636
- processor: { type: "string" },
1637
- rules: { type: "object" },
1638
- settings: { type: "object" },
1639
- noInlineConfig: { type: "boolean" },
1640
- reportUnusedDisableDirectives: { type: "boolean" },
1641
-
1642
- ecmaFeatures: { type: "object" } // deprecated; logs a warning when used
1643
- };
1644
-
1645
- const configSchema = {
1646
- definitions: {
1647
- stringOrStrings: {
1648
- oneOf: [
1649
- { type: "string" },
1650
- {
1651
- type: "array",
1652
- items: { type: "string" },
1653
- additionalItems: false
1654
- }
1655
- ]
1656
- },
1657
- stringOrStringsRequired: {
1658
- oneOf: [
1659
- { type: "string" },
1660
- {
1661
- type: "array",
1662
- items: { type: "string" },
1663
- additionalItems: false,
1664
- minItems: 1
1665
- }
1666
- ]
1667
- },
1668
-
1669
- // Config at top-level.
1670
- objectConfig: {
1671
- type: "object",
1672
- properties: {
1673
- root: { type: "boolean" },
1674
- ignorePatterns: { $ref: "#/definitions/stringOrStrings" },
1675
- ...baseConfigProperties
1676
- },
1677
- additionalProperties: false
1678
- },
1679
-
1680
- // Config in `overrides`.
1681
- overrideConfig: {
1682
- type: "object",
1683
- properties: {
1684
- excludedFiles: { $ref: "#/definitions/stringOrStrings" },
1685
- files: { $ref: "#/definitions/stringOrStringsRequired" },
1686
- ...baseConfigProperties
1687
- },
1688
- required: ["files"],
1689
- additionalProperties: false
1690
- }
1691
- },
1692
-
1693
- $ref: "#/definitions/objectConfig"
1694
- };
1695
-
1696
- /**
1697
- * @fileoverview Defines environment settings and globals.
1698
- * @author Elan Shanker
1699
- */
1700
-
1701
- //------------------------------------------------------------------------------
1702
- // Helpers
1703
- //------------------------------------------------------------------------------
1704
-
1705
- /**
1706
- * Get the object that has difference.
1707
- * @param {Record<string,boolean>} current The newer object.
1708
- * @param {Record<string,boolean>} prev The older object.
1709
- * @returns {Record<string,boolean>} The difference object.
1710
- */
1711
- function getDiff(current, prev) {
1712
- const retv = {};
1713
-
1714
- for (const [key, value] of Object.entries(current)) {
1715
- if (!Object.hasOwnProperty.call(prev, key)) {
1716
- retv[key] = value;
1717
- }
1718
- }
1719
-
1720
- return retv;
1721
- }
1722
-
1723
- const newGlobals2015 = getDiff(globals__default["default"].es2015, globals__default["default"].es5); // 19 variables such as Promise, Map, ...
1724
- const newGlobals2017 = {
1725
- Atomics: false,
1726
- SharedArrayBuffer: false
1727
- };
1728
- const newGlobals2020 = {
1729
- BigInt: false,
1730
- BigInt64Array: false,
1731
- BigUint64Array: false,
1732
- globalThis: false
1733
- };
1734
-
1735
- const newGlobals2021 = {
1736
- AggregateError: false,
1737
- FinalizationRegistry: false,
1738
- WeakRef: false
1739
- };
1740
-
1741
- //------------------------------------------------------------------------------
1742
- // Public Interface
1743
- //------------------------------------------------------------------------------
1744
-
1745
- /** @type {Map<string, import("../lib/shared/types").Environment>} */
1746
- var environments = new Map(Object.entries({
1747
-
1748
- // Language
1749
- builtin: {
1750
- globals: globals__default["default"].es5
1751
- },
1752
- es6: {
1753
- globals: newGlobals2015,
1754
- parserOptions: {
1755
- ecmaVersion: 6
1756
- }
1757
- },
1758
- es2015: {
1759
- globals: newGlobals2015,
1760
- parserOptions: {
1761
- ecmaVersion: 6
1762
- }
1763
- },
1764
- es2016: {
1765
- globals: newGlobals2015,
1766
- parserOptions: {
1767
- ecmaVersion: 7
1768
- }
1769
- },
1770
- es2017: {
1771
- globals: { ...newGlobals2015, ...newGlobals2017 },
1772
- parserOptions: {
1773
- ecmaVersion: 8
1774
- }
1775
- },
1776
- es2018: {
1777
- globals: { ...newGlobals2015, ...newGlobals2017 },
1778
- parserOptions: {
1779
- ecmaVersion: 9
1780
- }
1781
- },
1782
- es2019: {
1783
- globals: { ...newGlobals2015, ...newGlobals2017 },
1784
- parserOptions: {
1785
- ecmaVersion: 10
1786
- }
1787
- },
1788
- es2020: {
1789
- globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 },
1790
- parserOptions: {
1791
- ecmaVersion: 11
1792
- }
1793
- },
1794
- es2021: {
1795
- globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
1796
- parserOptions: {
1797
- ecmaVersion: 12
1798
- }
1799
- },
1800
- es2022: {
1801
- globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
1802
- parserOptions: {
1803
- ecmaVersion: 13
1804
- }
1805
- },
1806
- es2023: {
1807
- globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
1808
- parserOptions: {
1809
- ecmaVersion: 14
1810
- }
1811
- },
1812
- es2024: {
1813
- globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
1814
- parserOptions: {
1815
- ecmaVersion: 15
1816
- }
1817
- },
1818
-
1819
- // Platforms
1820
- browser: {
1821
- globals: globals__default["default"].browser
1822
- },
1823
- node: {
1824
- globals: globals__default["default"].node,
1825
- parserOptions: {
1826
- ecmaFeatures: {
1827
- globalReturn: true
1828
- }
1829
- }
1830
- },
1831
- "shared-node-browser": {
1832
- globals: globals__default["default"]["shared-node-browser"]
1833
- },
1834
- worker: {
1835
- globals: globals__default["default"].worker
1836
- },
1837
- serviceworker: {
1838
- globals: globals__default["default"].serviceworker
1839
- },
1840
-
1841
- // Frameworks
1842
- commonjs: {
1843
- globals: globals__default["default"].commonjs,
1844
- parserOptions: {
1845
- ecmaFeatures: {
1846
- globalReturn: true
1847
- }
1848
- }
1849
- },
1850
- amd: {
1851
- globals: globals__default["default"].amd
1852
- },
1853
- mocha: {
1854
- globals: globals__default["default"].mocha
1855
- },
1856
- jasmine: {
1857
- globals: globals__default["default"].jasmine
1858
- },
1859
- jest: {
1860
- globals: globals__default["default"].jest
1861
- },
1862
- phantomjs: {
1863
- globals: globals__default["default"].phantomjs
1864
- },
1865
- jquery: {
1866
- globals: globals__default["default"].jquery
1867
- },
1868
- qunit: {
1869
- globals: globals__default["default"].qunit
1870
- },
1871
- prototypejs: {
1872
- globals: globals__default["default"].prototypejs
1873
- },
1874
- shelljs: {
1875
- globals: globals__default["default"].shelljs
1876
- },
1877
- meteor: {
1878
- globals: globals__default["default"].meteor
1879
- },
1880
- mongo: {
1881
- globals: globals__default["default"].mongo
1882
- },
1883
- protractor: {
1884
- globals: globals__default["default"].protractor
1885
- },
1886
- applescript: {
1887
- globals: globals__default["default"].applescript
1888
- },
1889
- nashorn: {
1890
- globals: globals__default["default"].nashorn
1891
- },
1892
- atomtest: {
1893
- globals: globals__default["default"].atomtest
1894
- },
1895
- embertest: {
1896
- globals: globals__default["default"].embertest
1897
- },
1898
- webextensions: {
1899
- globals: globals__default["default"].webextensions
1900
- },
1901
- greasemonkey: {
1902
- globals: globals__default["default"].greasemonkey
1903
- }
1904
- }));
1905
-
1906
- /**
1907
- * @fileoverview Validates configs.
1908
- * @author Brandon Mills
1909
- */
1910
-
1911
- const ajv = ajvOrig();
1912
-
1913
- const ruleValidators = new WeakMap();
1914
- const noop = Function.prototype;
1915
-
1916
- //------------------------------------------------------------------------------
1917
- // Private
1918
- //------------------------------------------------------------------------------
1919
- let validateSchema;
1920
- const severityMap = {
1921
- error: 2,
1922
- warn: 1,
1923
- off: 0
1924
- };
1925
-
1926
- const validated = new WeakSet();
1927
-
1928
- // JSON schema that disallows passing any options
1929
- const noOptionsSchema = Object.freeze({
1930
- type: "array",
1931
- minItems: 0,
1932
- maxItems: 0
1933
- });
1934
-
1935
- //-----------------------------------------------------------------------------
1936
- // Exports
1937
- //-----------------------------------------------------------------------------
1938
-
1939
- class ConfigValidator {
1940
- constructor({ builtInRules = new Map() } = {}) {
1941
- this.builtInRules = builtInRules;
1942
- }
1943
-
1944
- /**
1945
- * Gets a complete options schema for a rule.
1946
- * @param {Rule} rule A rule object
1947
- * @throws {TypeError} If `meta.schema` is specified but is not an array, object or `false`.
1948
- * @returns {Object|null} JSON Schema for the rule's options.
1949
- * `null` if rule wasn't passed or its `meta.schema` is `false`.
1950
- */
1951
- getRuleOptionsSchema(rule) {
1952
- if (!rule) {
1953
- return null;
1954
- }
1955
-
1956
- if (!rule.meta) {
1957
- return { ...noOptionsSchema }; // default if `meta.schema` is not specified
1958
- }
1959
-
1960
- const schema = rule.meta.schema;
1961
-
1962
- if (typeof schema === "undefined") {
1963
- return { ...noOptionsSchema }; // default if `meta.schema` is not specified
1964
- }
1965
-
1966
- // `schema:false` is an allowed explicit opt-out of options validation for the rule
1967
- if (schema === false) {
1968
- return null;
1969
- }
1970
-
1971
- if (typeof schema !== "object" || schema === null) {
1972
- throw new TypeError("Rule's `meta.schema` must be an array or object");
1973
- }
1974
-
1975
- // ESLint-specific array form needs to be converted into a valid JSON Schema definition
1976
- if (Array.isArray(schema)) {
1977
- if (schema.length) {
1978
- return {
1979
- type: "array",
1980
- items: schema,
1981
- minItems: 0,
1982
- maxItems: schema.length
1983
- };
1984
- }
1985
-
1986
- // `schema:[]` is an explicit way to specify that the rule does not accept any options
1987
- return { ...noOptionsSchema };
1988
- }
1989
-
1990
- // `schema:<object>` is assumed to be a valid JSON Schema definition
1991
- return schema;
1992
- }
1993
-
1994
- /**
1995
- * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.
1996
- * @param {options} options The given options for the rule.
1997
- * @returns {number|string} The rule's severity value
1998
- */
1999
- validateRuleSeverity(options) {
2000
- const severity = Array.isArray(options) ? options[0] : options;
2001
- const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity;
2002
-
2003
- if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) {
2004
- return normSeverity;
2005
- }
2006
-
2007
- throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util__default["default"].inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`);
2008
-
2009
- }
2010
-
2011
- /**
2012
- * Validates the non-severity options passed to a rule, based on its schema.
2013
- * @param {{create: Function}} rule The rule to validate
2014
- * @param {Array} localOptions The options for the rule, excluding severity
2015
- * @returns {void}
2016
- */
2017
- validateRuleSchema(rule, localOptions) {
2018
- if (!ruleValidators.has(rule)) {
2019
- try {
2020
- const schema = this.getRuleOptionsSchema(rule);
2021
-
2022
- if (schema) {
2023
- ruleValidators.set(rule, ajv.compile(schema));
2024
- }
2025
- } catch (err) {
2026
- const errorWithCode = new Error(err.message, { cause: err });
2027
-
2028
- errorWithCode.code = "ESLINT_INVALID_RULE_OPTIONS_SCHEMA";
2029
-
2030
- throw errorWithCode;
2031
- }
2032
- }
2033
-
2034
- const validateRule = ruleValidators.get(rule);
2035
-
2036
- if (validateRule) {
2037
- validateRule(localOptions);
2038
- if (validateRule.errors) {
2039
- throw new Error(validateRule.errors.map(
2040
- error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`
2041
- ).join(""));
2042
- }
2043
- }
2044
- }
2045
-
2046
- /**
2047
- * Validates a rule's options against its schema.
2048
- * @param {{create: Function}|null} rule The rule that the config is being validated for
2049
- * @param {string} ruleId The rule's unique name.
2050
- * @param {Array|number} options The given options for the rule.
2051
- * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,
2052
- * no source is prepended to the message.
2053
- * @returns {void}
2054
- */
2055
- validateRuleOptions(rule, ruleId, options, source = null) {
2056
- try {
2057
- const severity = this.validateRuleSeverity(options);
2058
-
2059
- if (severity !== 0) {
2060
- this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);
2061
- }
2062
- } catch (err) {
2063
- let enhancedMessage = err.code === "ESLINT_INVALID_RULE_OPTIONS_SCHEMA"
2064
- ? `Error while processing options validation schema of rule '${ruleId}': ${err.message}`
2065
- : `Configuration for rule "${ruleId}" is invalid:\n${err.message}`;
2066
-
2067
- if (typeof source === "string") {
2068
- enhancedMessage = `${source}:\n\t${enhancedMessage}`;
2069
- }
2070
-
2071
- const enhancedError = new Error(enhancedMessage, { cause: err });
2072
-
2073
- if (err.code) {
2074
- enhancedError.code = err.code;
2075
- }
2076
-
2077
- throw enhancedError;
2078
- }
2079
- }
2080
-
2081
- /**
2082
- * Validates an environment object
2083
- * @param {Object} environment The environment config object to validate.
2084
- * @param {string} source The name of the configuration source to report in any errors.
2085
- * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded environments.
2086
- * @returns {void}
2087
- */
2088
- validateEnvironment(
2089
- environment,
2090
- source,
2091
- getAdditionalEnv = noop
2092
- ) {
2093
-
2094
- // not having an environment is ok
2095
- if (!environment) {
2096
- return;
2097
- }
2098
-
2099
- Object.keys(environment).forEach(id => {
2100
- const env = getAdditionalEnv(id) || environments.get(id) || null;
2101
-
2102
- if (!env) {
2103
- const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`;
2104
-
2105
- throw new Error(message);
2106
- }
2107
- });
2108
- }
2109
-
2110
- /**
2111
- * Validates a rules config object
2112
- * @param {Object} rulesConfig The rules config object to validate.
2113
- * @param {string} source The name of the configuration source to report in any errors.
2114
- * @param {function(ruleId:string): Object} getAdditionalRule A map from strings to loaded rules
2115
- * @returns {void}
2116
- */
2117
- validateRules(
2118
- rulesConfig,
2119
- source,
2120
- getAdditionalRule = noop
2121
- ) {
2122
- if (!rulesConfig) {
2123
- return;
2124
- }
2125
-
2126
- Object.keys(rulesConfig).forEach(id => {
2127
- const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null;
2128
-
2129
- this.validateRuleOptions(rule, id, rulesConfig[id], source);
2130
- });
2131
- }
2132
-
2133
- /**
2134
- * Validates a `globals` section of a config file
2135
- * @param {Object} globalsConfig The `globals` section
2136
- * @param {string|null} source The name of the configuration source to report in the event of an error.
2137
- * @returns {void}
2138
- */
2139
- validateGlobals(globalsConfig, source = null) {
2140
- if (!globalsConfig) {
2141
- return;
2142
- }
2143
-
2144
- Object.entries(globalsConfig)
2145
- .forEach(([configuredGlobal, configuredValue]) => {
2146
- try {
2147
- normalizeConfigGlobal(configuredValue);
2148
- } catch (err) {
2149
- throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`);
2150
- }
2151
- });
2152
- }
2153
-
2154
- /**
2155
- * Validate `processor` configuration.
2156
- * @param {string|undefined} processorName The processor name.
2157
- * @param {string} source The name of config file.
2158
- * @param {function(id:string): Processor} getProcessor The getter of defined processors.
2159
- * @returns {void}
2160
- */
2161
- validateProcessor(processorName, source, getProcessor) {
2162
- if (processorName && !getProcessor(processorName)) {
2163
- throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`);
2164
- }
2165
- }
2166
-
2167
- /**
2168
- * Formats an array of schema validation errors.
2169
- * @param {Array} errors An array of error messages to format.
2170
- * @returns {string} Formatted error message
2171
- */
2172
- formatErrors(errors) {
2173
- return errors.map(error => {
2174
- if (error.keyword === "additionalProperties") {
2175
- const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty;
2176
-
2177
- return `Unexpected top-level property "${formattedPropertyPath}"`;
2178
- }
2179
- if (error.keyword === "type") {
2180
- const formattedField = error.dataPath.slice(1);
2181
- const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema;
2182
- const formattedValue = JSON.stringify(error.data);
2183
-
2184
- return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`;
2185
- }
2186
-
2187
- const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
2188
-
2189
- return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`;
2190
- }).map(message => `\t- ${message}.\n`).join("");
2191
- }
2192
-
2193
- /**
2194
- * Validates the top level properties of the config object.
2195
- * @param {Object} config The config object to validate.
2196
- * @param {string} source The name of the configuration source to report in any errors.
2197
- * @returns {void}
2198
- */
2199
- validateConfigSchema(config, source = null) {
2200
- validateSchema = validateSchema || ajv.compile(configSchema);
2201
-
2202
- if (!validateSchema(config)) {
2203
- throw new Error(`ESLint configuration in ${source} is invalid:\n${this.formatErrors(validateSchema.errors)}`);
2204
- }
2205
-
2206
- if (Object.hasOwnProperty.call(config, "ecmaFeatures")) {
2207
- emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES");
2208
- }
2209
- }
2210
-
2211
- /**
2212
- * Validates an entire config object.
2213
- * @param {Object} config The config object to validate.
2214
- * @param {string} source The name of the configuration source to report in any errors.
2215
- * @param {function(ruleId:string): Object} [getAdditionalRule] A map from strings to loaded rules.
2216
- * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded envs.
2217
- * @returns {void}
2218
- */
2219
- validate(config, source, getAdditionalRule, getAdditionalEnv) {
2220
- this.validateConfigSchema(config, source);
2221
- this.validateRules(config.rules, source, getAdditionalRule);
2222
- this.validateEnvironment(config.env, source, getAdditionalEnv);
2223
- this.validateGlobals(config.globals, source);
2224
-
2225
- for (const override of config.overrides || []) {
2226
- this.validateRules(override.rules, source, getAdditionalRule);
2227
- this.validateEnvironment(override.env, source, getAdditionalEnv);
2228
- this.validateGlobals(config.globals, source);
2229
- }
2230
- }
2231
-
2232
- /**
2233
- * Validate config array object.
2234
- * @param {ConfigArray} configArray The config array to validate.
2235
- * @returns {void}
2236
- */
2237
- validateConfigArray(configArray) {
2238
- const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments);
2239
- const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors);
2240
- const getPluginRule = Map.prototype.get.bind(configArray.pluginRules);
2241
-
2242
- // Validate.
2243
- for (const element of configArray) {
2244
- if (validated.has(element)) {
2245
- continue;
2246
- }
2247
- validated.add(element);
2248
-
2249
- this.validateEnvironment(element.env, element.name, getPluginEnv);
2250
- this.validateGlobals(element.globals, element.name);
2251
- this.validateProcessor(element.processor, element.name, getPluginProcessor);
2252
- this.validateRules(element.rules, element.name, getPluginRule);
2253
- }
2254
- }
2255
-
2256
- }
2257
-
2258
- /**
2259
- * @fileoverview Common helpers for naming of plugins, formatters and configs
2260
- */
2261
-
2262
- const NAMESPACE_REGEX = /^@.*\//iu;
2263
-
2264
- /**
2265
- * Brings package name to correct format based on prefix
2266
- * @param {string} name The name of the package.
2267
- * @param {string} prefix Can be either "eslint-plugin", "eslint-config" or "eslint-formatter"
2268
- * @returns {string} Normalized name of the package
2269
- * @private
2270
- */
2271
- function normalizePackageName(name, prefix) {
2272
- let normalizedName = name;
2273
-
2274
- /**
2275
- * On Windows, name can come in with Windows slashes instead of Unix slashes.
2276
- * Normalize to Unix first to avoid errors later on.
2277
- * https://github.com/eslint/eslint/issues/5644
2278
- */
2279
- if (normalizedName.includes("\\")) {
2280
- normalizedName = normalizedName.replace(/\\/gu, "/");
2281
- }
2282
-
2283
- if (normalizedName.charAt(0) === "@") {
2284
-
2285
- /**
2286
- * it's a scoped package
2287
- * package name is the prefix, or just a username
2288
- */
2289
- const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`, "u"),
2290
- scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, "u");
2291
-
2292
- if (scopedPackageShortcutRegex.test(normalizedName)) {
2293
- normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`);
2294
- } else if (!scopedPackageNameRegex.test(normalizedName.split("/")[1])) {
2295
-
2296
- /**
2297
- * for scoped packages, insert the prefix after the first / unless
2298
- * the path is already @scope/eslint or @scope/eslint-xxx-yyy
2299
- */
2300
- normalizedName = normalizedName.replace(/^@([^/]+)\/(.*)$/u, `@$1/${prefix}-$2`);
2301
- }
2302
- } else if (!normalizedName.startsWith(`${prefix}-`)) {
2303
- normalizedName = `${prefix}-${normalizedName}`;
2304
- }
2305
-
2306
- return normalizedName;
2307
- }
2308
-
2309
- /**
2310
- * Removes the prefix from a fullname.
2311
- * @param {string} fullname The term which may have the prefix.
2312
- * @param {string} prefix The prefix to remove.
2313
- * @returns {string} The term without prefix.
2314
- */
2315
- function getShorthandName(fullname, prefix) {
2316
- if (fullname[0] === "@") {
2317
- let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec(fullname);
2318
-
2319
- if (matchResult) {
2320
- return matchResult[1];
2321
- }
2322
-
2323
- matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec(fullname);
2324
- if (matchResult) {
2325
- return `${matchResult[1]}/${matchResult[2]}`;
2326
- }
2327
- } else if (fullname.startsWith(`${prefix}-`)) {
2328
- return fullname.slice(prefix.length + 1);
2329
- }
2330
-
2331
- return fullname;
2332
- }
2333
-
2334
- /**
2335
- * Gets the scope (namespace) of a term.
2336
- * @param {string} term The term which may have the namespace.
2337
- * @returns {string} The namespace of the term if it has one.
2338
- */
2339
- function getNamespaceFromTerm(term) {
2340
- const match = term.match(NAMESPACE_REGEX);
2341
-
2342
- return match ? match[0] : "";
2343
- }
2344
-
2345
- var naming = {
2346
- __proto__: null,
2347
- normalizePackageName: normalizePackageName,
2348
- getShorthandName: getShorthandName,
2349
- getNamespaceFromTerm: getNamespaceFromTerm
2350
- };
2351
-
2352
- /**
2353
- * Utility for resolving a module relative to another module
2354
- * @author Teddy Katz
2355
- */
2356
-
2357
- /*
2358
- * `Module.createRequire` is added in v12.2.0. It supports URL as well.
2359
- * We only support the case where the argument is a filepath, not a URL.
2360
- */
2361
- const createRequire = Module__default["default"].createRequire;
2362
-
2363
- /**
2364
- * Resolves a Node module relative to another module
2365
- * @param {string} moduleName The name of a Node module, or a path to a Node module.
2366
- * @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be
2367
- * a file rather than a directory, but the file need not actually exist.
2368
- * @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath`
2369
- */
2370
- function resolve(moduleName, relativeToPath) {
2371
- try {
2372
- return createRequire(relativeToPath).resolve(moduleName);
2373
- } catch (error) {
2374
-
2375
- // This `if` block is for older Node.js than 12.0.0. We can remove this block in the future.
2376
- if (
2377
- typeof error === "object" &&
2378
- error !== null &&
2379
- error.code === "MODULE_NOT_FOUND" &&
2380
- !error.requireStack &&
2381
- error.message.includes(moduleName)
2382
- ) {
2383
- error.message += `\nRequire stack:\n- ${relativeToPath}`;
2384
- }
2385
- throw error;
2386
- }
2387
- }
2388
-
2389
- var ModuleResolver = {
2390
- __proto__: null,
2391
- resolve: resolve
2392
- };
2393
-
2394
- /**
2395
- * @fileoverview The factory of `ConfigArray` objects.
2396
- *
2397
- * This class provides methods to create `ConfigArray` instance.
2398
- *
2399
- * - `create(configData, options)`
2400
- * Create a `ConfigArray` instance from a config data. This is to handle CLI
2401
- * options except `--config`.
2402
- * - `loadFile(filePath, options)`
2403
- * Create a `ConfigArray` instance from a config file. This is to handle
2404
- * `--config` option. If the file was not found, throws the following error:
2405
- * - If the filename was `*.js`, a `MODULE_NOT_FOUND` error.
2406
- * - If the filename was `package.json`, an IO error or an
2407
- * `ESLINT_CONFIG_FIELD_NOT_FOUND` error.
2408
- * - Otherwise, an IO error such as `ENOENT`.
2409
- * - `loadInDirectory(directoryPath, options)`
2410
- * Create a `ConfigArray` instance from a config file which is on a given
2411
- * directory. This tries to load `.eslintrc.*` or `package.json`. If not
2412
- * found, returns an empty `ConfigArray`.
2413
- * - `loadESLintIgnore(filePath)`
2414
- * Create a `ConfigArray` instance from a config file that is `.eslintignore`
2415
- * format. This is to handle `--ignore-path` option.
2416
- * - `loadDefaultESLintIgnore()`
2417
- * Create a `ConfigArray` instance from `.eslintignore` or `package.json` in
2418
- * the current working directory.
2419
- *
2420
- * `ConfigArrayFactory` class has the responsibility that loads configuration
2421
- * files, including loading `extends`, `parser`, and `plugins`. The created
2422
- * `ConfigArray` instance has the loaded `extends`, `parser`, and `plugins`.
2423
- *
2424
- * But this class doesn't handle cascading. `CascadingConfigArrayFactory` class
2425
- * handles cascading and hierarchy.
2426
- *
2427
- * @author Toru Nagashima <https://github.com/mysticatea>
2428
- */
2429
-
2430
- const require$1 = Module.createRequire(require('url').pathToFileURL(__filename).toString());
2431
-
2432
- const debug$2 = debugOrig__default["default"]("eslintrc:config-array-factory");
2433
-
2434
- //------------------------------------------------------------------------------
2435
- // Helpers
2436
- //------------------------------------------------------------------------------
2437
-
2438
- const configFilenames = [
2439
- ".eslintrc.js",
2440
- ".eslintrc.cjs",
2441
- ".eslintrc.yaml",
2442
- ".eslintrc.yml",
2443
- ".eslintrc.json",
2444
- ".eslintrc",
2445
- "package.json"
2446
- ];
2447
-
2448
- // Define types for VSCode IntelliSense.
2449
- /** @typedef {import("./shared/types").ConfigData} ConfigData */
2450
- /** @typedef {import("./shared/types").OverrideConfigData} OverrideConfigData */
2451
- /** @typedef {import("./shared/types").Parser} Parser */
2452
- /** @typedef {import("./shared/types").Plugin} Plugin */
2453
- /** @typedef {import("./shared/types").Rule} Rule */
2454
- /** @typedef {import("./config-array/config-dependency").DependentParser} DependentParser */
2455
- /** @typedef {import("./config-array/config-dependency").DependentPlugin} DependentPlugin */
2456
- /** @typedef {ConfigArray[0]} ConfigArrayElement */
2457
-
2458
- /**
2459
- * @typedef {Object} ConfigArrayFactoryOptions
2460
- * @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
2461
- * @property {string} [cwd] The path to the current working directory.
2462
- * @property {string} [resolvePluginsRelativeTo] A path to the directory that plugins should be resolved from. Defaults to `cwd`.
2463
- * @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
2464
- * @property {Object} [resolver=ModuleResolver] The module resolver object.
2465
- * @property {string} eslintAllPath The path to the definitions for eslint:all.
2466
- * @property {Function} getEslintAllConfig Returns the config data for eslint:all.
2467
- * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
2468
- * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
2469
- */
2470
-
2471
- /**
2472
- * @typedef {Object} ConfigArrayFactoryInternalSlots
2473
- * @property {Map<string,Plugin>} additionalPluginPool The map for additional plugins.
2474
- * @property {string} cwd The path to the current working directory.
2475
- * @property {string | undefined} resolvePluginsRelativeTo An absolute path the the directory that plugins should be resolved from.
2476
- * @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
2477
- * @property {Object} [resolver=ModuleResolver] The module resolver object.
2478
- * @property {string} eslintAllPath The path to the definitions for eslint:all.
2479
- * @property {Function} getEslintAllConfig Returns the config data for eslint:all.
2480
- * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
2481
- * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
2482
- */
2483
-
2484
- /**
2485
- * @typedef {Object} ConfigArrayFactoryLoadingContext
2486
- * @property {string} filePath The path to the current configuration.
2487
- * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
2488
- * @property {string} name The name of the current configuration.
2489
- * @property {string} pluginBasePath The base path to resolve plugins.
2490
- * @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors.
2491
- */
2492
-
2493
- /**
2494
- * @typedef {Object} ConfigArrayFactoryLoadingContext
2495
- * @property {string} filePath The path to the current configuration.
2496
- * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
2497
- * @property {string} name The name of the current configuration.
2498
- * @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors.
2499
- */
2500
-
2501
- /** @type {WeakMap<ConfigArrayFactory, ConfigArrayFactoryInternalSlots>} */
2502
- const internalSlotsMap$1 = new WeakMap();
2503
-
2504
- /** @type {WeakMap<object, Plugin>} */
2505
- const normalizedPlugins = new WeakMap();
2506
-
2507
- /**
2508
- * Check if a given string is a file path.
2509
- * @param {string} nameOrPath A module name or file path.
2510
- * @returns {boolean} `true` if the `nameOrPath` is a file path.
2511
- */
2512
- function isFilePath(nameOrPath) {
2513
- return (
2514
- /^\.{1,2}[/\\]/u.test(nameOrPath) ||
2515
- path__default["default"].isAbsolute(nameOrPath)
2516
- );
2517
- }
2518
-
2519
- /**
2520
- * Convenience wrapper for synchronously reading file contents.
2521
- * @param {string} filePath The filename to read.
2522
- * @returns {string} The file contents, with the BOM removed.
2523
- * @private
2524
- */
2525
- function readFile(filePath) {
2526
- return fs__default["default"].readFileSync(filePath, "utf8").replace(/^\ufeff/u, "");
2527
- }
2528
-
2529
- /**
2530
- * Loads a YAML configuration from a file.
2531
- * @param {string} filePath The filename to load.
2532
- * @returns {ConfigData} The configuration object from the file.
2533
- * @throws {Error} If the file cannot be read.
2534
- * @private
2535
- */
2536
- function loadYAMLConfigFile(filePath) {
2537
- debug$2(`Loading YAML config file: ${filePath}`);
2538
-
2539
- // lazy load YAML to improve performance when not used
2540
- const yaml = require$1("js-yaml");
2541
-
2542
- try {
2543
-
2544
- // empty YAML file can be null, so always use
2545
- return yaml.load(readFile(filePath)) || {};
2546
- } catch (e) {
2547
- debug$2(`Error reading YAML file: ${filePath}`);
2548
- e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
2549
- throw e;
2550
- }
2551
- }
2552
-
2553
- /**
2554
- * Loads a JSON configuration from a file.
2555
- * @param {string} filePath The filename to load.
2556
- * @returns {ConfigData} The configuration object from the file.
2557
- * @throws {Error} If the file cannot be read.
2558
- * @private
2559
- */
2560
- function loadJSONConfigFile(filePath) {
2561
- debug$2(`Loading JSON config file: ${filePath}`);
2562
-
2563
- try {
2564
- return JSON.parse(stripComments__default["default"](readFile(filePath)));
2565
- } catch (e) {
2566
- debug$2(`Error reading JSON file: ${filePath}`);
2567
- e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
2568
- e.messageTemplate = "failed-to-read-json";
2569
- e.messageData = {
2570
- path: filePath,
2571
- message: e.message
2572
- };
2573
- throw e;
2574
- }
2575
- }
2576
-
2577
- /**
2578
- * Loads a legacy (.eslintrc) configuration from a file.
2579
- * @param {string} filePath The filename to load.
2580
- * @returns {ConfigData} The configuration object from the file.
2581
- * @throws {Error} If the file cannot be read.
2582
- * @private
2583
- */
2584
- function loadLegacyConfigFile(filePath) {
2585
- debug$2(`Loading legacy config file: ${filePath}`);
2586
-
2587
- // lazy load YAML to improve performance when not used
2588
- const yaml = require$1("js-yaml");
2589
-
2590
- try {
2591
- return yaml.load(stripComments__default["default"](readFile(filePath))) || /* istanbul ignore next */ {};
2592
- } catch (e) {
2593
- debug$2("Error reading YAML file: %s\n%o", filePath, e);
2594
- e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
2595
- throw e;
2596
- }
2597
- }
2598
-
2599
- /**
2600
- * Loads a JavaScript configuration from a file.
2601
- * @param {string} filePath The filename to load.
2602
- * @returns {ConfigData} The configuration object from the file.
2603
- * @throws {Error} If the file cannot be read.
2604
- * @private
2605
- */
2606
- function loadJSConfigFile(filePath) {
2607
- debug$2(`Loading JS config file: ${filePath}`);
2608
- try {
2609
- return importFresh__default["default"](filePath);
2610
- } catch (e) {
2611
- debug$2(`Error reading JavaScript file: ${filePath}`);
2612
- e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
2613
- throw e;
2614
- }
2615
- }
2616
-
2617
- /**
2618
- * Loads a configuration from a package.json file.
2619
- * @param {string} filePath The filename to load.
2620
- * @returns {ConfigData} The configuration object from the file.
2621
- * @throws {Error} If the file cannot be read.
2622
- * @private
2623
- */
2624
- function loadPackageJSONConfigFile(filePath) {
2625
- debug$2(`Loading package.json config file: ${filePath}`);
2626
- try {
2627
- const packageData = loadJSONConfigFile(filePath);
2628
-
2629
- if (!Object.hasOwnProperty.call(packageData, "eslintConfig")) {
2630
- throw Object.assign(
2631
- new Error("package.json file doesn't have 'eslintConfig' field."),
2632
- { code: "ESLINT_CONFIG_FIELD_NOT_FOUND" }
2633
- );
2634
- }
2635
-
2636
- return packageData.eslintConfig;
2637
- } catch (e) {
2638
- debug$2(`Error reading package.json file: ${filePath}`);
2639
- e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
2640
- throw e;
2641
- }
2642
- }
2643
-
2644
- /**
2645
- * Loads a `.eslintignore` from a file.
2646
- * @param {string} filePath The filename to load.
2647
- * @returns {string[]} The ignore patterns from the file.
2648
- * @private
2649
- */
2650
- function loadESLintIgnoreFile(filePath) {
2651
- debug$2(`Loading .eslintignore file: ${filePath}`);
2652
-
2653
- try {
2654
- return readFile(filePath)
2655
- .split(/\r?\n/gu)
2656
- .filter(line => line.trim() !== "" && !line.startsWith("#"));
2657
- } catch (e) {
2658
- debug$2(`Error reading .eslintignore file: ${filePath}`);
2659
- e.message = `Cannot read .eslintignore file: ${filePath}\nError: ${e.message}`;
2660
- throw e;
2661
- }
2662
- }
2663
-
2664
- /**
2665
- * Creates an error to notify about a missing config to extend from.
2666
- * @param {string} configName The name of the missing config.
2667
- * @param {string} importerName The name of the config that imported the missing config
2668
- * @param {string} messageTemplate The text template to source error strings from.
2669
- * @returns {Error} The error object to throw
2670
- * @private
2671
- */
2672
- function configInvalidError(configName, importerName, messageTemplate) {
2673
- return Object.assign(
2674
- new Error(`Failed to load config "${configName}" to extend from.`),
2675
- {
2676
- messageTemplate,
2677
- messageData: { configName, importerName }
2678
- }
2679
- );
2680
- }
2681
-
2682
- /**
2683
- * Loads a configuration file regardless of the source. Inspects the file path
2684
- * to determine the correctly way to load the config file.
2685
- * @param {string} filePath The path to the configuration.
2686
- * @returns {ConfigData|null} The configuration information.
2687
- * @private
2688
- */
2689
- function loadConfigFile(filePath) {
2690
- switch (path__default["default"].extname(filePath)) {
2691
- case ".js":
2692
- case ".cjs":
2693
- return loadJSConfigFile(filePath);
2694
-
2695
- case ".json":
2696
- if (path__default["default"].basename(filePath) === "package.json") {
2697
- return loadPackageJSONConfigFile(filePath);
2698
- }
2699
- return loadJSONConfigFile(filePath);
2700
-
2701
- case ".yaml":
2702
- case ".yml":
2703
- return loadYAMLConfigFile(filePath);
2704
-
2705
- default:
2706
- return loadLegacyConfigFile(filePath);
2707
- }
2708
- }
2709
-
2710
- /**
2711
- * Write debug log.
2712
- * @param {string} request The requested module name.
2713
- * @param {string} relativeTo The file path to resolve the request relative to.
2714
- * @param {string} filePath The resolved file path.
2715
- * @returns {void}
2716
- */
2717
- function writeDebugLogForLoading(request, relativeTo, filePath) {
2718
- /* istanbul ignore next */
2719
- if (debug$2.enabled) {
2720
- let nameAndVersion = null;
2721
-
2722
- try {
2723
- const packageJsonPath = resolve(
2724
- `${request}/package.json`,
2725
- relativeTo
2726
- );
2727
- const { version = "unknown" } = require$1(packageJsonPath);
2728
-
2729
- nameAndVersion = `${request}@${version}`;
2730
- } catch (error) {
2731
- debug$2("package.json was not found:", error.message);
2732
- nameAndVersion = request;
2733
- }
2734
-
2735
- debug$2("Loaded: %s (%s)", nameAndVersion, filePath);
2736
- }
2737
- }
2738
-
2739
- /**
2740
- * Create a new context with default values.
2741
- * @param {ConfigArrayFactoryInternalSlots} slots The internal slots.
2742
- * @param {"config" | "ignore" | "implicit-processor" | undefined} providedType The type of the current configuration. Default is `"config"`.
2743
- * @param {string | undefined} providedName The name of the current configuration. Default is the relative path from `cwd` to `filePath`.
2744
- * @param {string | undefined} providedFilePath The path to the current configuration. Default is empty string.
2745
- * @param {string | undefined} providedMatchBasePath The type of the current configuration. Default is the directory of `filePath` or `cwd`.
2746
- * @returns {ConfigArrayFactoryLoadingContext} The created context.
2747
- */
2748
- function createContext(
2749
- { cwd, resolvePluginsRelativeTo },
2750
- providedType,
2751
- providedName,
2752
- providedFilePath,
2753
- providedMatchBasePath
2754
- ) {
2755
- const filePath = providedFilePath
2756
- ? path__default["default"].resolve(cwd, providedFilePath)
2757
- : "";
2758
- const matchBasePath =
2759
- (providedMatchBasePath && path__default["default"].resolve(cwd, providedMatchBasePath)) ||
2760
- (filePath && path__default["default"].dirname(filePath)) ||
2761
- cwd;
2762
- const name =
2763
- providedName ||
2764
- (filePath && path__default["default"].relative(cwd, filePath)) ||
2765
- "";
2766
- const pluginBasePath =
2767
- resolvePluginsRelativeTo ||
2768
- (filePath && path__default["default"].dirname(filePath)) ||
2769
- cwd;
2770
- const type = providedType || "config";
2771
-
2772
- return { filePath, matchBasePath, name, pluginBasePath, type };
2773
- }
2774
-
2775
- /**
2776
- * Normalize a given plugin.
2777
- * - Ensure the object to have four properties: configs, environments, processors, and rules.
2778
- * - Ensure the object to not have other properties.
2779
- * @param {Plugin} plugin The plugin to normalize.
2780
- * @returns {Plugin} The normalized plugin.
2781
- */
2782
- function normalizePlugin(plugin) {
2783
-
2784
- // first check the cache
2785
- let normalizedPlugin = normalizedPlugins.get(plugin);
2786
-
2787
- if (normalizedPlugin) {
2788
- return normalizedPlugin;
2789
- }
2790
-
2791
- normalizedPlugin = {
2792
- configs: plugin.configs || {},
2793
- environments: plugin.environments || {},
2794
- processors: plugin.processors || {},
2795
- rules: plugin.rules || {}
2796
- };
2797
-
2798
- // save the reference for later
2799
- normalizedPlugins.set(plugin, normalizedPlugin);
2800
-
2801
- return normalizedPlugin;
2802
- }
2803
-
2804
- //------------------------------------------------------------------------------
2805
- // Public Interface
2806
- //------------------------------------------------------------------------------
2807
-
2808
- /**
2809
- * The factory of `ConfigArray` objects.
2810
- */
2811
- class ConfigArrayFactory {
2812
-
2813
- /**
2814
- * Initialize this instance.
2815
- * @param {ConfigArrayFactoryOptions} [options] The map for additional plugins.
2816
- */
2817
- constructor({
2818
- additionalPluginPool = new Map(),
2819
- cwd = process.cwd(),
2820
- resolvePluginsRelativeTo,
2821
- builtInRules,
2822
- resolver = ModuleResolver,
2823
- eslintAllPath,
2824
- getEslintAllConfig,
2825
- eslintRecommendedPath,
2826
- getEslintRecommendedConfig
2827
- } = {}) {
2828
- internalSlotsMap$1.set(this, {
2829
- additionalPluginPool,
2830
- cwd,
2831
- resolvePluginsRelativeTo:
2832
- resolvePluginsRelativeTo &&
2833
- path__default["default"].resolve(cwd, resolvePluginsRelativeTo),
2834
- builtInRules,
2835
- resolver,
2836
- eslintAllPath,
2837
- getEslintAllConfig,
2838
- eslintRecommendedPath,
2839
- getEslintRecommendedConfig
2840
- });
2841
- }
2842
-
2843
- /**
2844
- * Create `ConfigArray` instance from a config data.
2845
- * @param {ConfigData|null} configData The config data to create.
2846
- * @param {Object} [options] The options.
2847
- * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
2848
- * @param {string} [options.filePath] The path to this config data.
2849
- * @param {string} [options.name] The config name.
2850
- * @returns {ConfigArray} Loaded config.
2851
- */
2852
- create(configData, { basePath, filePath, name } = {}) {
2853
- if (!configData) {
2854
- return new ConfigArray();
2855
- }
2856
-
2857
- const slots = internalSlotsMap$1.get(this);
2858
- const ctx = createContext(slots, "config", name, filePath, basePath);
2859
- const elements = this._normalizeConfigData(configData, ctx);
2860
-
2861
- return new ConfigArray(...elements);
2862
- }
2863
-
2864
- /**
2865
- * Load a config file.
2866
- * @param {string} filePath The path to a config file.
2867
- * @param {Object} [options] The options.
2868
- * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
2869
- * @param {string} [options.name] The config name.
2870
- * @returns {ConfigArray} Loaded config.
2871
- */
2872
- loadFile(filePath, { basePath, name } = {}) {
2873
- const slots = internalSlotsMap$1.get(this);
2874
- const ctx = createContext(slots, "config", name, filePath, basePath);
2875
-
2876
- return new ConfigArray(...this._loadConfigData(ctx));
2877
- }
2878
-
2879
- /**
2880
- * Load the config file on a given directory if exists.
2881
- * @param {string} directoryPath The path to a directory.
2882
- * @param {Object} [options] The options.
2883
- * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
2884
- * @param {string} [options.name] The config name.
2885
- * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
2886
- */
2887
- loadInDirectory(directoryPath, { basePath, name } = {}) {
2888
- const slots = internalSlotsMap$1.get(this);
2889
-
2890
- for (const filename of configFilenames) {
2891
- const ctx = createContext(
2892
- slots,
2893
- "config",
2894
- name,
2895
- path__default["default"].join(directoryPath, filename),
2896
- basePath
2897
- );
2898
-
2899
- if (fs__default["default"].existsSync(ctx.filePath) && fs__default["default"].statSync(ctx.filePath).isFile()) {
2900
- let configData;
2901
-
2902
- try {
2903
- configData = loadConfigFile(ctx.filePath);
2904
- } catch (error) {
2905
- if (!error || error.code !== "ESLINT_CONFIG_FIELD_NOT_FOUND") {
2906
- throw error;
2907
- }
2908
- }
2909
-
2910
- if (configData) {
2911
- debug$2(`Config file found: ${ctx.filePath}`);
2912
- return new ConfigArray(
2913
- ...this._normalizeConfigData(configData, ctx)
2914
- );
2915
- }
2916
- }
2917
- }
2918
-
2919
- debug$2(`Config file not found on ${directoryPath}`);
2920
- return new ConfigArray();
2921
- }
2922
-
2923
- /**
2924
- * Check if a config file on a given directory exists or not.
2925
- * @param {string} directoryPath The path to a directory.
2926
- * @returns {string | null} The path to the found config file. If not found then null.
2927
- */
2928
- static getPathToConfigFileInDirectory(directoryPath) {
2929
- for (const filename of configFilenames) {
2930
- const filePath = path__default["default"].join(directoryPath, filename);
2931
-
2932
- if (fs__default["default"].existsSync(filePath)) {
2933
- if (filename === "package.json") {
2934
- try {
2935
- loadPackageJSONConfigFile(filePath);
2936
- return filePath;
2937
- } catch { /* ignore */ }
2938
- } else {
2939
- return filePath;
2940
- }
2941
- }
2942
- }
2943
- return null;
2944
- }
2945
-
2946
- /**
2947
- * Load `.eslintignore` file.
2948
- * @param {string} filePath The path to a `.eslintignore` file to load.
2949
- * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
2950
- */
2951
- loadESLintIgnore(filePath) {
2952
- const slots = internalSlotsMap$1.get(this);
2953
- const ctx = createContext(
2954
- slots,
2955
- "ignore",
2956
- void 0,
2957
- filePath,
2958
- slots.cwd
2959
- );
2960
- const ignorePatterns = loadESLintIgnoreFile(ctx.filePath);
2961
-
2962
- return new ConfigArray(
2963
- ...this._normalizeESLintIgnoreData(ignorePatterns, ctx)
2964
- );
2965
- }
2966
-
2967
- /**
2968
- * Load `.eslintignore` file in the current working directory.
2969
- * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
2970
- */
2971
- loadDefaultESLintIgnore() {
2972
- const slots = internalSlotsMap$1.get(this);
2973
- const eslintIgnorePath = path__default["default"].resolve(slots.cwd, ".eslintignore");
2974
- const packageJsonPath = path__default["default"].resolve(slots.cwd, "package.json");
2975
-
2976
- if (fs__default["default"].existsSync(eslintIgnorePath)) {
2977
- return this.loadESLintIgnore(eslintIgnorePath);
2978
- }
2979
- if (fs__default["default"].existsSync(packageJsonPath)) {
2980
- const data = loadJSONConfigFile(packageJsonPath);
2981
-
2982
- if (Object.hasOwnProperty.call(data, "eslintIgnore")) {
2983
- if (!Array.isArray(data.eslintIgnore)) {
2984
- throw new Error("Package.json eslintIgnore property requires an array of paths");
2985
- }
2986
- const ctx = createContext(
2987
- slots,
2988
- "ignore",
2989
- "eslintIgnore in package.json",
2990
- packageJsonPath,
2991
- slots.cwd
2992
- );
2993
-
2994
- return new ConfigArray(
2995
- ...this._normalizeESLintIgnoreData(data.eslintIgnore, ctx)
2996
- );
2997
- }
2998
- }
2999
-
3000
- return new ConfigArray();
3001
- }
3002
-
3003
- /**
3004
- * Load a given config file.
3005
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3006
- * @returns {IterableIterator<ConfigArrayElement>} Loaded config.
3007
- * @private
3008
- */
3009
- _loadConfigData(ctx) {
3010
- return this._normalizeConfigData(loadConfigFile(ctx.filePath), ctx);
3011
- }
3012
-
3013
- /**
3014
- * Normalize a given `.eslintignore` data to config array elements.
3015
- * @param {string[]} ignorePatterns The patterns to ignore files.
3016
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3017
- * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
3018
- * @private
3019
- */
3020
- *_normalizeESLintIgnoreData(ignorePatterns, ctx) {
3021
- const elements = this._normalizeObjectConfigData(
3022
- { ignorePatterns },
3023
- ctx
3024
- );
3025
-
3026
- // Set `ignorePattern.loose` flag for backward compatibility.
3027
- for (const element of elements) {
3028
- if (element.ignorePattern) {
3029
- element.ignorePattern.loose = true;
3030
- }
3031
- yield element;
3032
- }
3033
- }
3034
-
3035
- /**
3036
- * Normalize a given config to an array.
3037
- * @param {ConfigData} configData The config data to normalize.
3038
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3039
- * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
3040
- * @private
3041
- */
3042
- _normalizeConfigData(configData, ctx) {
3043
- const validator = new ConfigValidator();
3044
-
3045
- validator.validateConfigSchema(configData, ctx.name || ctx.filePath);
3046
- return this._normalizeObjectConfigData(configData, ctx);
3047
- }
3048
-
3049
- /**
3050
- * Normalize a given config to an array.
3051
- * @param {ConfigData|OverrideConfigData} configData The config data to normalize.
3052
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3053
- * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
3054
- * @private
3055
- */
3056
- *_normalizeObjectConfigData(configData, ctx) {
3057
- const { files, excludedFiles, ...configBody } = configData;
3058
- const criteria = OverrideTester.create(
3059
- files,
3060
- excludedFiles,
3061
- ctx.matchBasePath
3062
- );
3063
- const elements = this._normalizeObjectConfigDataBody(configBody, ctx);
3064
-
3065
- // Apply the criteria to every element.
3066
- for (const element of elements) {
3067
-
3068
- /*
3069
- * Merge the criteria.
3070
- * This is for the `overrides` entries that came from the
3071
- * configurations of `overrides[].extends`.
3072
- */
3073
- element.criteria = OverrideTester.and(criteria, element.criteria);
3074
-
3075
- /*
3076
- * Remove `root` property to ignore `root` settings which came from
3077
- * `extends` in `overrides`.
3078
- */
3079
- if (element.criteria) {
3080
- element.root = void 0;
3081
- }
3082
-
3083
- yield element;
3084
- }
3085
- }
3086
-
3087
- /**
3088
- * Normalize a given config to an array.
3089
- * @param {ConfigData} configData The config data to normalize.
3090
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3091
- * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
3092
- * @private
3093
- */
3094
- *_normalizeObjectConfigDataBody(
3095
- {
3096
- env,
3097
- extends: extend,
3098
- globals,
3099
- ignorePatterns,
3100
- noInlineConfig,
3101
- parser: parserName,
3102
- parserOptions,
3103
- plugins: pluginList,
3104
- processor,
3105
- reportUnusedDisableDirectives,
3106
- root,
3107
- rules,
3108
- settings,
3109
- overrides: overrideList = []
3110
- },
3111
- ctx
3112
- ) {
3113
- const extendList = Array.isArray(extend) ? extend : [extend];
3114
- const ignorePattern = ignorePatterns && new IgnorePattern(
3115
- Array.isArray(ignorePatterns) ? ignorePatterns : [ignorePatterns],
3116
- ctx.matchBasePath
3117
- );
3118
-
3119
- // Flatten `extends`.
3120
- for (const extendName of extendList.filter(Boolean)) {
3121
- yield* this._loadExtends(extendName, ctx);
3122
- }
3123
-
3124
- // Load parser & plugins.
3125
- const parser = parserName && this._loadParser(parserName, ctx);
3126
- const plugins = pluginList && this._loadPlugins(pluginList, ctx);
3127
-
3128
- // Yield pseudo config data for file extension processors.
3129
- if (plugins) {
3130
- yield* this._takeFileExtensionProcessors(plugins, ctx);
3131
- }
3132
-
3133
- // Yield the config data except `extends` and `overrides`.
3134
- yield {
3135
-
3136
- // Debug information.
3137
- type: ctx.type,
3138
- name: ctx.name,
3139
- filePath: ctx.filePath,
3140
-
3141
- // Config data.
3142
- criteria: null,
3143
- env,
3144
- globals,
3145
- ignorePattern,
3146
- noInlineConfig,
3147
- parser,
3148
- parserOptions,
3149
- plugins,
3150
- processor,
3151
- reportUnusedDisableDirectives,
3152
- root,
3153
- rules,
3154
- settings
3155
- };
3156
-
3157
- // Flatten `overries`.
3158
- for (let i = 0; i < overrideList.length; ++i) {
3159
- yield* this._normalizeObjectConfigData(
3160
- overrideList[i],
3161
- { ...ctx, name: `${ctx.name}#overrides[${i}]` }
3162
- );
3163
- }
3164
- }
3165
-
3166
- /**
3167
- * Load configs of an element in `extends`.
3168
- * @param {string} extendName The name of a base config.
3169
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3170
- * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
3171
- * @private
3172
- */
3173
- _loadExtends(extendName, ctx) {
3174
- debug$2("Loading {extends:%j} relative to %s", extendName, ctx.filePath);
3175
- try {
3176
- if (extendName.startsWith("eslint:")) {
3177
- return this._loadExtendedBuiltInConfig(extendName, ctx);
3178
- }
3179
- if (extendName.startsWith("plugin:")) {
3180
- return this._loadExtendedPluginConfig(extendName, ctx);
3181
- }
3182
- return this._loadExtendedShareableConfig(extendName, ctx);
3183
- } catch (error) {
3184
- error.message += `\nReferenced from: ${ctx.filePath || ctx.name}`;
3185
- throw error;
3186
- }
3187
- }
3188
-
3189
- /**
3190
- * Load configs of an element in `extends`.
3191
- * @param {string} extendName The name of a base config.
3192
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3193
- * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
3194
- * @private
3195
- */
3196
- _loadExtendedBuiltInConfig(extendName, ctx) {
3197
- const {
3198
- eslintAllPath,
3199
- getEslintAllConfig,
3200
- eslintRecommendedPath,
3201
- getEslintRecommendedConfig
3202
- } = internalSlotsMap$1.get(this);
3203
-
3204
- if (extendName === "eslint:recommended") {
3205
- const name = `${ctx.name} » ${extendName}`;
3206
-
3207
- if (getEslintRecommendedConfig) {
3208
- if (typeof getEslintRecommendedConfig !== "function") {
3209
- throw new Error(`getEslintRecommendedConfig must be a function instead of '${getEslintRecommendedConfig}'`);
3210
- }
3211
- return this._normalizeConfigData(getEslintRecommendedConfig(), { ...ctx, name, filePath: "" });
3212
- }
3213
- return this._loadConfigData({
3214
- ...ctx,
3215
- name,
3216
- filePath: eslintRecommendedPath
3217
- });
3218
- }
3219
- if (extendName === "eslint:all") {
3220
- const name = `${ctx.name} » ${extendName}`;
3221
-
3222
- if (getEslintAllConfig) {
3223
- if (typeof getEslintAllConfig !== "function") {
3224
- throw new Error(`getEslintAllConfig must be a function instead of '${getEslintAllConfig}'`);
3225
- }
3226
- return this._normalizeConfigData(getEslintAllConfig(), { ...ctx, name, filePath: "" });
3227
- }
3228
- return this._loadConfigData({
3229
- ...ctx,
3230
- name,
3231
- filePath: eslintAllPath
3232
- });
3233
- }
3234
-
3235
- throw configInvalidError(extendName, ctx.name, "extend-config-missing");
3236
- }
3237
-
3238
- /**
3239
- * Load configs of an element in `extends`.
3240
- * @param {string} extendName The name of a base config.
3241
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3242
- * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
3243
- * @private
3244
- */
3245
- _loadExtendedPluginConfig(extendName, ctx) {
3246
- const slashIndex = extendName.lastIndexOf("/");
3247
-
3248
- if (slashIndex === -1) {
3249
- throw configInvalidError(extendName, ctx.filePath, "plugin-invalid");
3250
- }
3251
-
3252
- const pluginName = extendName.slice("plugin:".length, slashIndex);
3253
- const configName = extendName.slice(slashIndex + 1);
3254
-
3255
- if (isFilePath(pluginName)) {
3256
- throw new Error("'extends' cannot use a file path for plugins.");
3257
- }
3258
-
3259
- const plugin = this._loadPlugin(pluginName, ctx);
3260
- const configData =
3261
- plugin.definition &&
3262
- plugin.definition.configs[configName];
3263
-
3264
- if (configData) {
3265
- return this._normalizeConfigData(configData, {
3266
- ...ctx,
3267
- filePath: plugin.filePath || ctx.filePath,
3268
- name: `${ctx.name} » plugin:${plugin.id}/${configName}`
3269
- });
3270
- }
3271
-
3272
- throw plugin.error || configInvalidError(extendName, ctx.filePath, "extend-config-missing");
3273
- }
3274
-
3275
- /**
3276
- * Load configs of an element in `extends`.
3277
- * @param {string} extendName The name of a base config.
3278
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3279
- * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
3280
- * @private
3281
- */
3282
- _loadExtendedShareableConfig(extendName, ctx) {
3283
- const { cwd, resolver } = internalSlotsMap$1.get(this);
3284
- const relativeTo = ctx.filePath || path__default["default"].join(cwd, "__placeholder__.js");
3285
- let request;
3286
-
3287
- if (isFilePath(extendName)) {
3288
- request = extendName;
3289
- } else if (extendName.startsWith(".")) {
3290
- request = `./${extendName}`; // For backward compatibility. A ton of tests depended on this behavior.
3291
- } else {
3292
- request = normalizePackageName(
3293
- extendName,
3294
- "eslint-config"
3295
- );
3296
- }
3297
-
3298
- let filePath;
3299
-
3300
- try {
3301
- filePath = resolver.resolve(request, relativeTo);
3302
- } catch (error) {
3303
- /* istanbul ignore else */
3304
- if (error && error.code === "MODULE_NOT_FOUND") {
3305
- throw configInvalidError(extendName, ctx.filePath, "extend-config-missing");
3306
- }
3307
- throw error;
3308
- }
3309
-
3310
- writeDebugLogForLoading(request, relativeTo, filePath);
3311
- return this._loadConfigData({
3312
- ...ctx,
3313
- filePath,
3314
- name: `${ctx.name} » ${request}`
3315
- });
3316
- }
3317
-
3318
- /**
3319
- * Load given plugins.
3320
- * @param {string[]} names The plugin names to load.
3321
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3322
- * @returns {Record<string,DependentPlugin>} The loaded parser.
3323
- * @private
3324
- */
3325
- _loadPlugins(names, ctx) {
3326
- return names.reduce((map, name) => {
3327
- if (isFilePath(name)) {
3328
- throw new Error("Plugins array cannot includes file paths.");
3329
- }
3330
- const plugin = this._loadPlugin(name, ctx);
3331
-
3332
- map[plugin.id] = plugin;
3333
-
3334
- return map;
3335
- }, {});
3336
- }
3337
-
3338
- /**
3339
- * Load a given parser.
3340
- * @param {string} nameOrPath The package name or the path to a parser file.
3341
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3342
- * @returns {DependentParser} The loaded parser.
3343
- */
3344
- _loadParser(nameOrPath, ctx) {
3345
- debug$2("Loading parser %j from %s", nameOrPath, ctx.filePath);
3346
-
3347
- const { cwd, resolver } = internalSlotsMap$1.get(this);
3348
- const relativeTo = ctx.filePath || path__default["default"].join(cwd, "__placeholder__.js");
3349
-
3350
- try {
3351
- const filePath = resolver.resolve(nameOrPath, relativeTo);
3352
-
3353
- writeDebugLogForLoading(nameOrPath, relativeTo, filePath);
3354
-
3355
- return new ConfigDependency({
3356
- definition: require$1(filePath),
3357
- filePath,
3358
- id: nameOrPath,
3359
- importerName: ctx.name,
3360
- importerPath: ctx.filePath
3361
- });
3362
- } catch (error) {
3363
-
3364
- // If the parser name is "espree", load the espree of ESLint.
3365
- if (nameOrPath === "espree") {
3366
- debug$2("Fallback espree.");
3367
- return new ConfigDependency({
3368
- definition: require$1("espree"),
3369
- filePath: require$1.resolve("espree"),
3370
- id: nameOrPath,
3371
- importerName: ctx.name,
3372
- importerPath: ctx.filePath
3373
- });
3374
- }
3375
-
3376
- debug$2("Failed to load parser '%s' declared in '%s'.", nameOrPath, ctx.name);
3377
- error.message = `Failed to load parser '${nameOrPath}' declared in '${ctx.name}': ${error.message}`;
3378
-
3379
- return new ConfigDependency({
3380
- error,
3381
- id: nameOrPath,
3382
- importerName: ctx.name,
3383
- importerPath: ctx.filePath
3384
- });
3385
- }
3386
- }
3387
-
3388
- /**
3389
- * Load a given plugin.
3390
- * @param {string} name The plugin name to load.
3391
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3392
- * @returns {DependentPlugin} The loaded plugin.
3393
- * @private
3394
- */
3395
- _loadPlugin(name, ctx) {
3396
- debug$2("Loading plugin %j from %s", name, ctx.filePath);
3397
-
3398
- const { additionalPluginPool, resolver } = internalSlotsMap$1.get(this);
3399
- const request = normalizePackageName(name, "eslint-plugin");
3400
- const id = getShorthandName(request, "eslint-plugin");
3401
- const relativeTo = path__default["default"].join(ctx.pluginBasePath, "__placeholder__.js");
3402
-
3403
- if (name.match(/\s+/u)) {
3404
- const error = Object.assign(
3405
- new Error(`Whitespace found in plugin name '${name}'`),
3406
- {
3407
- messageTemplate: "whitespace-found",
3408
- messageData: { pluginName: request }
3409
- }
3410
- );
3411
-
3412
- return new ConfigDependency({
3413
- error,
3414
- id,
3415
- importerName: ctx.name,
3416
- importerPath: ctx.filePath
3417
- });
3418
- }
3419
-
3420
- // Check for additional pool.
3421
- const plugin =
3422
- additionalPluginPool.get(request) ||
3423
- additionalPluginPool.get(id);
3424
-
3425
- if (plugin) {
3426
- return new ConfigDependency({
3427
- definition: normalizePlugin(plugin),
3428
- original: plugin,
3429
- filePath: "", // It's unknown where the plugin came from.
3430
- id,
3431
- importerName: ctx.name,
3432
- importerPath: ctx.filePath
3433
- });
3434
- }
3435
-
3436
- let filePath;
3437
- let error;
3438
-
3439
- try {
3440
- filePath = resolver.resolve(request, relativeTo);
3441
- } catch (resolveError) {
3442
- error = resolveError;
3443
- /* istanbul ignore else */
3444
- if (error && error.code === "MODULE_NOT_FOUND") {
3445
- error.messageTemplate = "plugin-missing";
3446
- error.messageData = {
3447
- pluginName: request,
3448
- resolvePluginsRelativeTo: ctx.pluginBasePath,
3449
- importerName: ctx.name
3450
- };
3451
- }
3452
- }
3453
-
3454
- if (filePath) {
3455
- try {
3456
- writeDebugLogForLoading(request, relativeTo, filePath);
3457
-
3458
- const startTime = Date.now();
3459
- const pluginDefinition = require$1(filePath);
3460
-
3461
- debug$2(`Plugin ${filePath} loaded in: ${Date.now() - startTime}ms`);
3462
-
3463
- return new ConfigDependency({
3464
- definition: normalizePlugin(pluginDefinition),
3465
- original: pluginDefinition,
3466
- filePath,
3467
- id,
3468
- importerName: ctx.name,
3469
- importerPath: ctx.filePath
3470
- });
3471
- } catch (loadError) {
3472
- error = loadError;
3473
- }
3474
- }
3475
-
3476
- debug$2("Failed to load plugin '%s' declared in '%s'.", name, ctx.name);
3477
- error.message = `Failed to load plugin '${name}' declared in '${ctx.name}': ${error.message}`;
3478
- return new ConfigDependency({
3479
- error,
3480
- id,
3481
- importerName: ctx.name,
3482
- importerPath: ctx.filePath
3483
- });
3484
- }
3485
-
3486
- /**
3487
- * Take file expression processors as config array elements.
3488
- * @param {Record<string,DependentPlugin>} plugins The plugin definitions.
3489
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3490
- * @returns {IterableIterator<ConfigArrayElement>} The config array elements of file expression processors.
3491
- * @private
3492
- */
3493
- *_takeFileExtensionProcessors(plugins, ctx) {
3494
- for (const pluginId of Object.keys(plugins)) {
3495
- const processors =
3496
- plugins[pluginId] &&
3497
- plugins[pluginId].definition &&
3498
- plugins[pluginId].definition.processors;
3499
-
3500
- if (!processors) {
3501
- continue;
3502
- }
3503
-
3504
- for (const processorId of Object.keys(processors)) {
3505
- if (processorId.startsWith(".")) {
3506
- yield* this._normalizeObjectConfigData(
3507
- {
3508
- files: [`*${processorId}`],
3509
- processor: `${pluginId}/${processorId}`
3510
- },
3511
- {
3512
- ...ctx,
3513
- type: "implicit-processor",
3514
- name: `${ctx.name}#processors["${pluginId}/${processorId}"]`
3515
- }
3516
- );
3517
- }
3518
- }
3519
- }
3520
- }
3521
- }
3522
-
3523
- /**
3524
- * @fileoverview `CascadingConfigArrayFactory` class.
3525
- *
3526
- * `CascadingConfigArrayFactory` class has a responsibility:
3527
- *
3528
- * 1. Handles cascading of config files.
3529
- *
3530
- * It provides two methods:
3531
- *
3532
- * - `getConfigArrayForFile(filePath)`
3533
- * Get the corresponded configuration of a given file. This method doesn't
3534
- * throw even if the given file didn't exist.
3535
- * - `clearCache()`
3536
- * Clear the internal cache. You have to call this method when
3537
- * `additionalPluginPool` was updated if `baseConfig` or `cliConfig` depends
3538
- * on the additional plugins. (`CLIEngine#addPlugin()` method calls this.)
3539
- *
3540
- * @author Toru Nagashima <https://github.com/mysticatea>
3541
- */
3542
-
3543
- const debug$1 = debugOrig__default["default"]("eslintrc:cascading-config-array-factory");
3544
-
3545
- //------------------------------------------------------------------------------
3546
- // Helpers
3547
- //------------------------------------------------------------------------------
3548
-
3549
- // Define types for VSCode IntelliSense.
3550
- /** @typedef {import("./shared/types").ConfigData} ConfigData */
3551
- /** @typedef {import("./shared/types").Parser} Parser */
3552
- /** @typedef {import("./shared/types").Plugin} Plugin */
3553
- /** @typedef {import("./shared/types").Rule} Rule */
3554
- /** @typedef {ReturnType<ConfigArrayFactory["create"]>} ConfigArray */
3555
-
3556
- /**
3557
- * @typedef {Object} CascadingConfigArrayFactoryOptions
3558
- * @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
3559
- * @property {ConfigData} [baseConfig] The config by `baseConfig` option.
3560
- * @property {ConfigData} [cliConfig] The config by CLI options (`--env`, `--global`, `--ignore-pattern`, `--parser`, `--parser-options`, `--plugin`, and `--rule`). CLI options overwrite the setting in config files.
3561
- * @property {string} [cwd] The base directory to start lookup.
3562
- * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
3563
- * @property {string[]} [rulePaths] The value of `--rulesdir` option.
3564
- * @property {string} [specificConfigPath] The value of `--config` option.
3565
- * @property {boolean} [useEslintrc] if `false` then it doesn't load config files.
3566
- * @property {Function} loadRules The function to use to load rules.
3567
- * @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
3568
- * @property {Object} [resolver=ModuleResolver] The module resolver object.
3569
- * @property {string} eslintAllPath The path to the definitions for eslint:all.
3570
- * @property {Function} getEslintAllConfig Returns the config data for eslint:all.
3571
- * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
3572
- * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
3573
- */
3574
-
3575
- /**
3576
- * @typedef {Object} CascadingConfigArrayFactoryInternalSlots
3577
- * @property {ConfigArray} baseConfigArray The config array of `baseConfig` option.
3578
- * @property {ConfigData} baseConfigData The config data of `baseConfig` option. This is used to reset `baseConfigArray`.
3579
- * @property {ConfigArray} cliConfigArray The config array of CLI options.
3580
- * @property {ConfigData} cliConfigData The config data of CLI options. This is used to reset `cliConfigArray`.
3581
- * @property {ConfigArrayFactory} configArrayFactory The factory for config arrays.
3582
- * @property {Map<string, ConfigArray>} configCache The cache from directory paths to config arrays.
3583
- * @property {string} cwd The base directory to start lookup.
3584
- * @property {WeakMap<ConfigArray, ConfigArray>} finalizeCache The cache from config arrays to finalized config arrays.
3585
- * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
3586
- * @property {string[]|null} rulePaths The value of `--rulesdir` option. This is used to reset `baseConfigArray`.
3587
- * @property {string|null} specificConfigPath The value of `--config` option. This is used to reset `cliConfigArray`.
3588
- * @property {boolean} useEslintrc if `false` then it doesn't load config files.
3589
- * @property {Function} loadRules The function to use to load rules.
3590
- * @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
3591
- * @property {Object} [resolver=ModuleResolver] The module resolver object.
3592
- * @property {string} eslintAllPath The path to the definitions for eslint:all.
3593
- * @property {Function} getEslintAllConfig Returns the config data for eslint:all.
3594
- * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
3595
- * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
3596
- */
3597
-
3598
- /** @type {WeakMap<CascadingConfigArrayFactory, CascadingConfigArrayFactoryInternalSlots>} */
3599
- const internalSlotsMap = new WeakMap();
3600
-
3601
- /**
3602
- * Create the config array from `baseConfig` and `rulePaths`.
3603
- * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
3604
- * @returns {ConfigArray} The config array of the base configs.
3605
- */
3606
- function createBaseConfigArray({
3607
- configArrayFactory,
3608
- baseConfigData,
3609
- rulePaths,
3610
- cwd,
3611
- loadRules
3612
- }) {
3613
- const baseConfigArray = configArrayFactory.create(
3614
- baseConfigData,
3615
- { name: "BaseConfig" }
3616
- );
3617
-
3618
- /*
3619
- * Create the config array element for the default ignore patterns.
3620
- * This element has `ignorePattern` property that ignores the default
3621
- * patterns in the current working directory.
3622
- */
3623
- baseConfigArray.unshift(configArrayFactory.create(
3624
- { ignorePatterns: IgnorePattern.DefaultPatterns },
3625
- { name: "DefaultIgnorePattern" }
3626
- )[0]);
3627
-
3628
- /*
3629
- * Load rules `--rulesdir` option as a pseudo plugin.
3630
- * Use a pseudo plugin to define rules of `--rulesdir`, so we can validate
3631
- * the rule's options with only information in the config array.
3632
- */
3633
- if (rulePaths && rulePaths.length > 0) {
3634
- baseConfigArray.push({
3635
- type: "config",
3636
- name: "--rulesdir",
3637
- filePath: "",
3638
- plugins: {
3639
- "": new ConfigDependency({
3640
- definition: {
3641
- rules: rulePaths.reduce(
3642
- (map, rulesPath) => Object.assign(
3643
- map,
3644
- loadRules(rulesPath, cwd)
3645
- ),
3646
- {}
3647
- )
3648
- },
3649
- filePath: "",
3650
- id: "",
3651
- importerName: "--rulesdir",
3652
- importerPath: ""
3653
- })
3654
- }
3655
- });
3656
- }
3657
-
3658
- return baseConfigArray;
3659
- }
3660
-
3661
- /**
3662
- * Create the config array from CLI options.
3663
- * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
3664
- * @returns {ConfigArray} The config array of the base configs.
3665
- */
3666
- function createCLIConfigArray({
3667
- cliConfigData,
3668
- configArrayFactory,
3669
- cwd,
3670
- ignorePath,
3671
- specificConfigPath
3672
- }) {
3673
- const cliConfigArray = configArrayFactory.create(
3674
- cliConfigData,
3675
- { name: "CLIOptions" }
3676
- );
3677
-
3678
- cliConfigArray.unshift(
3679
- ...(ignorePath
3680
- ? configArrayFactory.loadESLintIgnore(ignorePath)
3681
- : configArrayFactory.loadDefaultESLintIgnore())
3682
- );
3683
-
3684
- if (specificConfigPath) {
3685
- cliConfigArray.unshift(
3686
- ...configArrayFactory.loadFile(
3687
- specificConfigPath,
3688
- { name: "--config", basePath: cwd }
3689
- )
3690
- );
3691
- }
3692
-
3693
- return cliConfigArray;
3694
- }
3695
-
3696
- /**
3697
- * The error type when there are files matched by a glob, but all of them have been ignored.
3698
- */
3699
- class ConfigurationNotFoundError extends Error {
3700
-
3701
- // eslint-disable-next-line jsdoc/require-description
3702
- /**
3703
- * @param {string} directoryPath The directory path.
3704
- */
3705
- constructor(directoryPath) {
3706
- super(`No ESLint configuration found in ${directoryPath}.`);
3707
- this.messageTemplate = "no-config-found";
3708
- this.messageData = { directoryPath };
3709
- }
3710
- }
3711
-
3712
- /**
3713
- * This class provides the functionality that enumerates every file which is
3714
- * matched by given glob patterns and that configuration.
3715
- */
3716
- class CascadingConfigArrayFactory {
3717
-
3718
- /**
3719
- * Initialize this enumerator.
3720
- * @param {CascadingConfigArrayFactoryOptions} options The options.
3721
- */
3722
- constructor({
3723
- additionalPluginPool = new Map(),
3724
- baseConfig: baseConfigData = null,
3725
- cliConfig: cliConfigData = null,
3726
- cwd = process.cwd(),
3727
- ignorePath,
3728
- resolvePluginsRelativeTo,
3729
- rulePaths = [],
3730
- specificConfigPath = null,
3731
- useEslintrc = true,
3732
- builtInRules = new Map(),
3733
- loadRules,
3734
- resolver,
3735
- eslintRecommendedPath,
3736
- getEslintRecommendedConfig,
3737
- eslintAllPath,
3738
- getEslintAllConfig
3739
- } = {}) {
3740
- const configArrayFactory = new ConfigArrayFactory({
3741
- additionalPluginPool,
3742
- cwd,
3743
- resolvePluginsRelativeTo,
3744
- builtInRules,
3745
- resolver,
3746
- eslintRecommendedPath,
3747
- getEslintRecommendedConfig,
3748
- eslintAllPath,
3749
- getEslintAllConfig
3750
- });
3751
-
3752
- internalSlotsMap.set(this, {
3753
- baseConfigArray: createBaseConfigArray({
3754
- baseConfigData,
3755
- configArrayFactory,
3756
- cwd,
3757
- rulePaths,
3758
- loadRules
3759
- }),
3760
- baseConfigData,
3761
- cliConfigArray: createCLIConfigArray({
3762
- cliConfigData,
3763
- configArrayFactory,
3764
- cwd,
3765
- ignorePath,
3766
- specificConfigPath
3767
- }),
3768
- cliConfigData,
3769
- configArrayFactory,
3770
- configCache: new Map(),
3771
- cwd,
3772
- finalizeCache: new WeakMap(),
3773
- ignorePath,
3774
- rulePaths,
3775
- specificConfigPath,
3776
- useEslintrc,
3777
- builtInRules,
3778
- loadRules
3779
- });
3780
- }
3781
-
3782
- /**
3783
- * The path to the current working directory.
3784
- * This is used by tests.
3785
- * @type {string}
3786
- */
3787
- get cwd() {
3788
- const { cwd } = internalSlotsMap.get(this);
3789
-
3790
- return cwd;
3791
- }
3792
-
3793
- /**
3794
- * Get the config array of a given file.
3795
- * If `filePath` was not given, it returns the config which contains only
3796
- * `baseConfigData` and `cliConfigData`.
3797
- * @param {string} [filePath] The file path to a file.
3798
- * @param {Object} [options] The options.
3799
- * @param {boolean} [options.ignoreNotFoundError] If `true` then it doesn't throw `ConfigurationNotFoundError`.
3800
- * @returns {ConfigArray} The config array of the file.
3801
- */
3802
- getConfigArrayForFile(filePath, { ignoreNotFoundError = false } = {}) {
3803
- const {
3804
- baseConfigArray,
3805
- cliConfigArray,
3806
- cwd
3807
- } = internalSlotsMap.get(this);
3808
-
3809
- if (!filePath) {
3810
- return new ConfigArray(...baseConfigArray, ...cliConfigArray);
3811
- }
3812
-
3813
- const directoryPath = path__default["default"].dirname(path__default["default"].resolve(cwd, filePath));
3814
-
3815
- debug$1(`Load config files for ${directoryPath}.`);
3816
-
3817
- return this._finalizeConfigArray(
3818
- this._loadConfigInAncestors(directoryPath),
3819
- directoryPath,
3820
- ignoreNotFoundError
3821
- );
3822
- }
3823
-
3824
- /**
3825
- * Set the config data to override all configs.
3826
- * Require to call `clearCache()` method after this method is called.
3827
- * @param {ConfigData} configData The config data to override all configs.
3828
- * @returns {void}
3829
- */
3830
- setOverrideConfig(configData) {
3831
- const slots = internalSlotsMap.get(this);
3832
-
3833
- slots.cliConfigData = configData;
3834
- }
3835
-
3836
- /**
3837
- * Clear config cache.
3838
- * @returns {void}
3839
- */
3840
- clearCache() {
3841
- const slots = internalSlotsMap.get(this);
3842
-
3843
- slots.baseConfigArray = createBaseConfigArray(slots);
3844
- slots.cliConfigArray = createCLIConfigArray(slots);
3845
- slots.configCache.clear();
3846
- }
3847
-
3848
- /**
3849
- * Load and normalize config files from the ancestor directories.
3850
- * @param {string} directoryPath The path to a leaf directory.
3851
- * @param {boolean} configsExistInSubdirs `true` if configurations exist in subdirectories.
3852
- * @returns {ConfigArray} The loaded config.
3853
- * @private
3854
- */
3855
- _loadConfigInAncestors(directoryPath, configsExistInSubdirs = false) {
3856
- const {
3857
- baseConfigArray,
3858
- configArrayFactory,
3859
- configCache,
3860
- cwd,
3861
- useEslintrc
3862
- } = internalSlotsMap.get(this);
3863
-
3864
- if (!useEslintrc) {
3865
- return baseConfigArray;
3866
- }
3867
-
3868
- let configArray = configCache.get(directoryPath);
3869
-
3870
- // Hit cache.
3871
- if (configArray) {
3872
- debug$1(`Cache hit: ${directoryPath}.`);
3873
- return configArray;
3874
- }
3875
- debug$1(`No cache found: ${directoryPath}.`);
3876
-
3877
- const homePath = os__default["default"].homedir();
3878
-
3879
- // Consider this is root.
3880
- if (directoryPath === homePath && cwd !== homePath) {
3881
- debug$1("Stop traversing because of considered root.");
3882
- if (configsExistInSubdirs) {
3883
- const filePath = ConfigArrayFactory.getPathToConfigFileInDirectory(directoryPath);
3884
-
3885
- if (filePath) {
3886
- emitDeprecationWarning(
3887
- filePath,
3888
- "ESLINT_PERSONAL_CONFIG_SUPPRESS"
3889
- );
3890
- }
3891
- }
3892
- return this._cacheConfig(directoryPath, baseConfigArray);
3893
- }
3894
-
3895
- // Load the config on this directory.
3896
- try {
3897
- configArray = configArrayFactory.loadInDirectory(directoryPath);
3898
- } catch (error) {
3899
- /* istanbul ignore next */
3900
- if (error.code === "EACCES") {
3901
- debug$1("Stop traversing because of 'EACCES' error.");
3902
- return this._cacheConfig(directoryPath, baseConfigArray);
3903
- }
3904
- throw error;
3905
- }
3906
-
3907
- if (configArray.length > 0 && configArray.isRoot()) {
3908
- debug$1("Stop traversing because of 'root:true'.");
3909
- configArray.unshift(...baseConfigArray);
3910
- return this._cacheConfig(directoryPath, configArray);
3911
- }
3912
-
3913
- // Load from the ancestors and merge it.
3914
- const parentPath = path__default["default"].dirname(directoryPath);
3915
- const parentConfigArray = parentPath && parentPath !== directoryPath
3916
- ? this._loadConfigInAncestors(
3917
- parentPath,
3918
- configsExistInSubdirs || configArray.length > 0
3919
- )
3920
- : baseConfigArray;
3921
-
3922
- if (configArray.length > 0) {
3923
- configArray.unshift(...parentConfigArray);
3924
- } else {
3925
- configArray = parentConfigArray;
3926
- }
3927
-
3928
- // Cache and return.
3929
- return this._cacheConfig(directoryPath, configArray);
3930
- }
3931
-
3932
- /**
3933
- * Freeze and cache a given config.
3934
- * @param {string} directoryPath The path to a directory as a cache key.
3935
- * @param {ConfigArray} configArray The config array as a cache value.
3936
- * @returns {ConfigArray} The `configArray` (frozen).
3937
- */
3938
- _cacheConfig(directoryPath, configArray) {
3939
- const { configCache } = internalSlotsMap.get(this);
3940
-
3941
- Object.freeze(configArray);
3942
- configCache.set(directoryPath, configArray);
3943
-
3944
- return configArray;
3945
- }
3946
-
3947
- /**
3948
- * Finalize a given config array.
3949
- * Concatenate `--config` and other CLI options.
3950
- * @param {ConfigArray} configArray The parent config array.
3951
- * @param {string} directoryPath The path to the leaf directory to find config files.
3952
- * @param {boolean} ignoreNotFoundError If `true` then it doesn't throw `ConfigurationNotFoundError`.
3953
- * @returns {ConfigArray} The loaded config.
3954
- * @private
3955
- */
3956
- _finalizeConfigArray(configArray, directoryPath, ignoreNotFoundError) {
3957
- const {
3958
- cliConfigArray,
3959
- configArrayFactory,
3960
- finalizeCache,
3961
- useEslintrc,
3962
- builtInRules
3963
- } = internalSlotsMap.get(this);
3964
-
3965
- let finalConfigArray = finalizeCache.get(configArray);
3966
-
3967
- if (!finalConfigArray) {
3968
- finalConfigArray = configArray;
3969
-
3970
- // Load the personal config if there are no regular config files.
3971
- if (
3972
- useEslintrc &&
3973
- configArray.every(c => !c.filePath) &&
3974
- cliConfigArray.every(c => !c.filePath) // `--config` option can be a file.
3975
- ) {
3976
- const homePath = os__default["default"].homedir();
3977
-
3978
- debug$1("Loading the config file of the home directory:", homePath);
3979
-
3980
- const personalConfigArray = configArrayFactory.loadInDirectory(
3981
- homePath,
3982
- { name: "PersonalConfig" }
3983
- );
3984
-
3985
- if (
3986
- personalConfigArray.length > 0 &&
3987
- !directoryPath.startsWith(homePath)
3988
- ) {
3989
- const lastElement =
3990
- personalConfigArray[personalConfigArray.length - 1];
3991
-
3992
- emitDeprecationWarning(
3993
- lastElement.filePath,
3994
- "ESLINT_PERSONAL_CONFIG_LOAD"
3995
- );
3996
- }
3997
-
3998
- finalConfigArray = finalConfigArray.concat(personalConfigArray);
3999
- }
4000
-
4001
- // Apply CLI options.
4002
- if (cliConfigArray.length > 0) {
4003
- finalConfigArray = finalConfigArray.concat(cliConfigArray);
4004
- }
4005
-
4006
- // Validate rule settings and environments.
4007
- const validator = new ConfigValidator({
4008
- builtInRules
4009
- });
4010
-
4011
- validator.validateConfigArray(finalConfigArray);
4012
-
4013
- // Cache it.
4014
- Object.freeze(finalConfigArray);
4015
- finalizeCache.set(configArray, finalConfigArray);
4016
-
4017
- debug$1(
4018
- "Configuration was determined: %o on %s",
4019
- finalConfigArray,
4020
- directoryPath
4021
- );
4022
- }
4023
-
4024
- // At least one element (the default ignore patterns) exists.
4025
- if (!ignoreNotFoundError && useEslintrc && finalConfigArray.length <= 1) {
4026
- throw new ConfigurationNotFoundError(directoryPath);
4027
- }
4028
-
4029
- return finalConfigArray;
4030
- }
4031
- }
4032
-
4033
- /**
4034
- * @fileoverview Compatibility class for flat config.
4035
- * @author Nicholas C. Zakas
4036
- */
4037
-
4038
- //-----------------------------------------------------------------------------
4039
- // Helpers
4040
- //-----------------------------------------------------------------------------
4041
-
4042
- /** @typedef {import("../../shared/types").Environment} Environment */
4043
- /** @typedef {import("../../shared/types").Processor} Processor */
4044
-
4045
- const debug = debugOrig__default["default"]("eslintrc:flat-compat");
4046
- const cafactory = Symbol("cafactory");
4047
-
4048
- /**
4049
- * Translates an ESLintRC-style config object into a flag-config-style config
4050
- * object.
4051
- * @param {Object} eslintrcConfig An ESLintRC-style config object.
4052
- * @param {Object} options Options to help translate the config.
4053
- * @param {string} options.resolveConfigRelativeTo To the directory to resolve
4054
- * configs from.
4055
- * @param {string} options.resolvePluginsRelativeTo The directory to resolve
4056
- * plugins from.
4057
- * @param {ReadOnlyMap<string,Environment>} options.pluginEnvironments A map of plugin environment
4058
- * names to objects.
4059
- * @param {ReadOnlyMap<string,Processor>} options.pluginProcessors A map of plugin processor
4060
- * names to objects.
4061
- * @returns {Object} A flag-config-style config object.
4062
- */
4063
- function translateESLintRC(eslintrcConfig, {
4064
- resolveConfigRelativeTo,
4065
- resolvePluginsRelativeTo,
4066
- pluginEnvironments,
4067
- pluginProcessors
4068
- }) {
4069
-
4070
- const flatConfig = {};
4071
- const configs = [];
4072
- const languageOptions = {};
4073
- const linterOptions = {};
4074
- const keysToCopy = ["settings", "rules", "processor"];
4075
- const languageOptionsKeysToCopy = ["globals", "parser", "parserOptions"];
4076
- const linterOptionsKeysToCopy = ["noInlineConfig", "reportUnusedDisableDirectives"];
4077
-
4078
- // copy over simple translations
4079
- for (const key of keysToCopy) {
4080
- if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
4081
- flatConfig[key] = eslintrcConfig[key];
4082
- }
4083
- }
4084
-
4085
- // copy over languageOptions
4086
- for (const key of languageOptionsKeysToCopy) {
4087
- if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
4088
-
4089
- // create the languageOptions key in the flat config
4090
- flatConfig.languageOptions = languageOptions;
4091
-
4092
- if (key === "parser") {
4093
- debug(`Resolving parser '${languageOptions[key]}' relative to ${resolveConfigRelativeTo}`);
4094
-
4095
- if (eslintrcConfig[key].error) {
4096
- throw eslintrcConfig[key].error;
4097
- }
4098
-
4099
- languageOptions[key] = eslintrcConfig[key].definition;
4100
- continue;
4101
- }
4102
-
4103
- // clone any object values that are in the eslintrc config
4104
- if (eslintrcConfig[key] && typeof eslintrcConfig[key] === "object") {
4105
- languageOptions[key] = {
4106
- ...eslintrcConfig[key]
4107
- };
4108
- } else {
4109
- languageOptions[key] = eslintrcConfig[key];
4110
- }
4111
- }
4112
- }
4113
-
4114
- // copy over linterOptions
4115
- for (const key of linterOptionsKeysToCopy) {
4116
- if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
4117
- flatConfig.linterOptions = linterOptions;
4118
- linterOptions[key] = eslintrcConfig[key];
4119
- }
4120
- }
4121
-
4122
- // move ecmaVersion a level up
4123
- if (languageOptions.parserOptions) {
4124
-
4125
- if ("ecmaVersion" in languageOptions.parserOptions) {
4126
- languageOptions.ecmaVersion = languageOptions.parserOptions.ecmaVersion;
4127
- delete languageOptions.parserOptions.ecmaVersion;
4128
- }
4129
-
4130
- if ("sourceType" in languageOptions.parserOptions) {
4131
- languageOptions.sourceType = languageOptions.parserOptions.sourceType;
4132
- delete languageOptions.parserOptions.sourceType;
4133
- }
4134
-
4135
- // check to see if we even need parserOptions anymore and remove it if not
4136
- if (Object.keys(languageOptions.parserOptions).length === 0) {
4137
- delete languageOptions.parserOptions;
4138
- }
4139
- }
4140
-
4141
- // overrides
4142
- if (eslintrcConfig.criteria) {
4143
- flatConfig.files = [absoluteFilePath => eslintrcConfig.criteria.test(absoluteFilePath)];
4144
- }
4145
-
4146
- // translate plugins
4147
- if (eslintrcConfig.plugins && typeof eslintrcConfig.plugins === "object") {
4148
- debug(`Translating plugins: ${eslintrcConfig.plugins}`);
4149
-
4150
- flatConfig.plugins = {};
4151
-
4152
- for (const pluginName of Object.keys(eslintrcConfig.plugins)) {
4153
-
4154
- debug(`Translating plugin: ${pluginName}`);
4155
- debug(`Resolving plugin '${pluginName} relative to ${resolvePluginsRelativeTo}`);
4156
-
4157
- const { original: plugin, error } = eslintrcConfig.plugins[pluginName];
4158
-
4159
- if (error) {
4160
- throw error;
4161
- }
4162
-
4163
- flatConfig.plugins[pluginName] = plugin;
4164
-
4165
- // create a config for any processors
4166
- if (plugin.processors) {
4167
- for (const processorName of Object.keys(plugin.processors)) {
4168
- if (processorName.startsWith(".")) {
4169
- debug(`Assigning processor: ${pluginName}/${processorName}`);
4170
-
4171
- configs.unshift({
4172
- files: [`**/*${processorName}`],
4173
- processor: pluginProcessors.get(`${pluginName}/${processorName}`)
4174
- });
4175
- }
4176
-
4177
- }
4178
- }
4179
- }
4180
- }
4181
-
4182
- // translate env - must come after plugins
4183
- if (eslintrcConfig.env && typeof eslintrcConfig.env === "object") {
4184
- for (const envName of Object.keys(eslintrcConfig.env)) {
4185
-
4186
- // only add environments that are true
4187
- if (eslintrcConfig.env[envName]) {
4188
- debug(`Translating environment: ${envName}`);
4189
-
4190
- if (environments.has(envName)) {
4191
-
4192
- // built-in environments should be defined first
4193
- configs.unshift(...translateESLintRC({
4194
- criteria: eslintrcConfig.criteria,
4195
- ...environments.get(envName)
4196
- }, {
4197
- resolveConfigRelativeTo,
4198
- resolvePluginsRelativeTo
4199
- }));
4200
- } else if (pluginEnvironments.has(envName)) {
4201
-
4202
- // if the environment comes from a plugin, it should come after the plugin config
4203
- configs.push(...translateESLintRC({
4204
- criteria: eslintrcConfig.criteria,
4205
- ...pluginEnvironments.get(envName)
4206
- }, {
4207
- resolveConfigRelativeTo,
4208
- resolvePluginsRelativeTo
4209
- }));
4210
- }
4211
- }
4212
- }
4213
- }
4214
-
4215
- // only add if there are actually keys in the config
4216
- if (Object.keys(flatConfig).length > 0) {
4217
- configs.push(flatConfig);
4218
- }
4219
-
4220
- return configs;
4221
- }
4222
-
4223
-
4224
- //-----------------------------------------------------------------------------
4225
- // Exports
4226
- //-----------------------------------------------------------------------------
4227
-
4228
- /**
4229
- * A compatibility class for working with configs.
4230
- */
4231
- class FlatCompat {
4232
-
4233
- constructor({
4234
- baseDirectory = process.cwd(),
4235
- resolvePluginsRelativeTo = baseDirectory,
4236
- recommendedConfig,
4237
- allConfig
4238
- } = {}) {
4239
- this.baseDirectory = baseDirectory;
4240
- this.resolvePluginsRelativeTo = resolvePluginsRelativeTo;
4241
- this[cafactory] = new ConfigArrayFactory({
4242
- cwd: baseDirectory,
4243
- resolvePluginsRelativeTo,
4244
- getEslintAllConfig: () => {
4245
-
4246
- if (!allConfig) {
4247
- throw new TypeError("Missing parameter 'allConfig' in FlatCompat constructor.");
4248
- }
4249
-
4250
- return allConfig;
4251
- },
4252
- getEslintRecommendedConfig: () => {
4253
-
4254
- if (!recommendedConfig) {
4255
- throw new TypeError("Missing parameter 'recommendedConfig' in FlatCompat constructor.");
4256
- }
4257
-
4258
- return recommendedConfig;
4259
- }
4260
- });
4261
- }
4262
-
4263
- /**
4264
- * Translates an ESLintRC-style config into a flag-config-style config.
4265
- * @param {Object} eslintrcConfig The ESLintRC-style config object.
4266
- * @returns {Object} A flag-config-style config object.
4267
- */
4268
- config(eslintrcConfig) {
4269
- const eslintrcArray = this[cafactory].create(eslintrcConfig, {
4270
- basePath: this.baseDirectory
4271
- });
4272
-
4273
- const flatArray = [];
4274
- let hasIgnorePatterns = false;
4275
-
4276
- eslintrcArray.forEach(configData => {
4277
- if (configData.type === "config") {
4278
- hasIgnorePatterns = hasIgnorePatterns || configData.ignorePattern;
4279
- flatArray.push(...translateESLintRC(configData, {
4280
- resolveConfigRelativeTo: path__default["default"].join(this.baseDirectory, "__placeholder.js"),
4281
- resolvePluginsRelativeTo: path__default["default"].join(this.resolvePluginsRelativeTo, "__placeholder.js"),
4282
- pluginEnvironments: eslintrcArray.pluginEnvironments,
4283
- pluginProcessors: eslintrcArray.pluginProcessors
4284
- }));
4285
- }
4286
- });
4287
-
4288
- // combine ignorePatterns to emulate ESLintRC behavior better
4289
- if (hasIgnorePatterns) {
4290
- flatArray.unshift({
4291
- ignores: [filePath => {
4292
-
4293
- // Compute the final config for this file.
4294
- // This filters config array elements by `files`/`excludedFiles` then merges the elements.
4295
- const finalConfig = eslintrcArray.extractConfig(filePath);
4296
-
4297
- // Test the `ignorePattern` properties of the final config.
4298
- return Boolean(finalConfig.ignores) && finalConfig.ignores(filePath);
4299
- }]
4300
- });
4301
- }
4302
-
4303
- return flatArray;
4304
- }
4305
-
4306
- /**
4307
- * Translates the `env` section of an ESLintRC-style config.
4308
- * @param {Object} envConfig The `env` section of an ESLintRC config.
4309
- * @returns {Object[]} An array of flag-config objects representing the environments.
4310
- */
4311
- env(envConfig) {
4312
- return this.config({
4313
- env: envConfig
4314
- });
4315
- }
4316
-
4317
- /**
4318
- * Translates the `extends` section of an ESLintRC-style config.
4319
- * @param {...string} configsToExtend The names of the configs to load.
4320
- * @returns {Object[]} An array of flag-config objects representing the config.
4321
- */
4322
- extends(...configsToExtend) {
4323
- return this.config({
4324
- extends: configsToExtend
4325
- });
4326
- }
4327
-
4328
- /**
4329
- * Translates the `plugins` section of an ESLintRC-style config.
4330
- * @param {...string} plugins The names of the plugins to load.
4331
- * @returns {Object[]} An array of flag-config objects representing the plugins.
4332
- */
4333
- plugins(...plugins) {
4334
- return this.config({
4335
- plugins
4336
- });
4337
- }
4338
- }
4339
-
4340
- /**
4341
- * @fileoverview Package exports for @eslint/eslintrc
4342
- * @author Nicholas C. Zakas
4343
- */
4344
-
4345
- //-----------------------------------------------------------------------------
4346
- // Exports
4347
- //-----------------------------------------------------------------------------
4348
-
4349
- const Legacy = {
4350
- ConfigArray,
4351
- createConfigArrayFactoryContext: createContext,
4352
- CascadingConfigArrayFactory,
4353
- ConfigArrayFactory,
4354
- ConfigDependency,
4355
- ExtractedConfig,
4356
- IgnorePattern,
4357
- OverrideTester,
4358
- getUsedExtractedConfigs,
4359
- environments,
4360
- loadConfigFile,
4361
-
4362
- // shared
4363
- ConfigOps,
4364
- ConfigValidator,
4365
- ModuleResolver,
4366
- naming
4367
- };
4368
-
4369
- exports.FlatCompat = FlatCompat;
4370
- exports.Legacy = Legacy;
4371
- //# sourceMappingURL=eslintrc.cjs.map