config-array.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. /**
  2. * @fileoverview `ConfigArray` class.
  3. *
  4. * `ConfigArray` class expresses the full of a configuration. It has the entry
  5. * config file, base config files that were extended, loaded parsers, and loaded
  6. * plugins.
  7. *
  8. * `ConfigArray` class provides three properties and two methods.
  9. *
  10. * - `pluginEnvironments`
  11. * - `pluginProcessors`
  12. * - `pluginRules`
  13. * The `Map` objects that contain the members of all plugins that this
  14. * config array contains. Those map objects don't have mutation methods.
  15. * Those keys are the member ID such as `pluginId/memberName`.
  16. * - `isRoot()`
  17. * If `true` then this configuration has `root:true` property.
  18. * - `extractConfig(filePath)`
  19. * Extract the final configuration for a given file. This means merging
  20. * every config array element which that `criteria` property matched. The
  21. * `filePath` argument must be an absolute path.
  22. *
  23. * `ConfigArrayFactory` provides the loading logic of config files.
  24. *
  25. * @author Toru Nagashima <https://github.com/mysticatea>
  26. */
  27. //------------------------------------------------------------------------------
  28. // Requirements
  29. //------------------------------------------------------------------------------
  30. import { ExtractedConfig } from "./extracted-config.js";
  31. import { IgnorePattern } from "./ignore-pattern.js";
  32. //------------------------------------------------------------------------------
  33. // Helpers
  34. //------------------------------------------------------------------------------
  35. // Define types for VSCode IntelliSense.
  36. /** @typedef {import("../../shared/types").Environment} Environment */
  37. /** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
  38. /** @typedef {import("../../shared/types").RuleConf} RuleConf */
  39. /** @typedef {import("../../shared/types").Rule} Rule */
  40. /** @typedef {import("../../shared/types").Plugin} Plugin */
  41. /** @typedef {import("../../shared/types").Processor} Processor */
  42. /** @typedef {import("./config-dependency").DependentParser} DependentParser */
  43. /** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
  44. /** @typedef {import("./override-tester")["OverrideTester"]} OverrideTester */
  45. /**
  46. * @typedef {Object} ConfigArrayElement
  47. * @property {string} name The name of this config element.
  48. * @property {string} filePath The path to the source file of this config element.
  49. * @property {InstanceType<OverrideTester>|null} criteria The tester for the `files` and `excludedFiles` of this config element.
  50. * @property {Record<string, boolean>|undefined} env The environment settings.
  51. * @property {Record<string, GlobalConf>|undefined} globals The global variable settings.
  52. * @property {IgnorePattern|undefined} ignorePattern The ignore patterns.
  53. * @property {boolean|undefined} noInlineConfig The flag that disables directive comments.
  54. * @property {DependentParser|undefined} parser The parser loader.
  55. * @property {Object|undefined} parserOptions The parser options.
  56. * @property {Record<string, DependentPlugin>|undefined} plugins The plugin loaders.
  57. * @property {string|undefined} processor The processor name to refer plugin's processor.
  58. * @property {boolean|undefined} reportUnusedDisableDirectives The flag to report unused `eslint-disable` comments.
  59. * @property {boolean|undefined} root The flag to express root.
  60. * @property {Record<string, RuleConf>|undefined} rules The rule settings
  61. * @property {Object|undefined} settings The shared settings.
  62. * @property {"config" | "ignore" | "implicit-processor"} type The element type.
  63. */
  64. /**
  65. * @typedef {Object} ConfigArrayInternalSlots
  66. * @property {Map<string, ExtractedConfig>} cache The cache to extract configs.
  67. * @property {ReadonlyMap<string, Environment>|null} envMap The map from environment ID to environment definition.
  68. * @property {ReadonlyMap<string, Processor>|null} processorMap The map from processor ID to environment definition.
  69. * @property {ReadonlyMap<string, Rule>|null} ruleMap The map from rule ID to rule definition.
  70. */
  71. /** @type {WeakMap<ConfigArray, ConfigArrayInternalSlots>} */
  72. const internalSlotsMap = new class extends WeakMap {
  73. get(key) {
  74. let value = super.get(key);
  75. if (!value) {
  76. value = {
  77. cache: new Map(),
  78. envMap: null,
  79. processorMap: null,
  80. ruleMap: null
  81. };
  82. super.set(key, value);
  83. }
  84. return value;
  85. }
  86. }();
  87. /**
  88. * Get the indices which are matched to a given file.
  89. * @param {ConfigArrayElement[]} elements The elements.
  90. * @param {string} filePath The path to a target file.
  91. * @returns {number[]} The indices.
  92. */
  93. function getMatchedIndices(elements, filePath) {
  94. const indices = [];
  95. for (let i = elements.length - 1; i >= 0; --i) {
  96. const element = elements[i];
  97. if (!element.criteria || (filePath && element.criteria.test(filePath))) {
  98. indices.push(i);
  99. }
  100. }
  101. return indices;
  102. }
  103. /**
  104. * Check if a value is a non-null object.
  105. * @param {any} x The value to check.
  106. * @returns {boolean} `true` if the value is a non-null object.
  107. */
  108. function isNonNullObject(x) {
  109. return typeof x === "object" && x !== null;
  110. }
  111. /**
  112. * Merge two objects.
  113. *
  114. * Assign every property values of `y` to `x` if `x` doesn't have the property.
  115. * If `x`'s property value is an object, it does recursive.
  116. * @param {Object} target The destination to merge
  117. * @param {Object|undefined} source The source to merge.
  118. * @returns {void}
  119. */
  120. function mergeWithoutOverwrite(target, source) {
  121. if (!isNonNullObject(source)) {
  122. return;
  123. }
  124. for (const key of Object.keys(source)) {
  125. if (key === "__proto__") {
  126. continue;
  127. }
  128. if (isNonNullObject(target[key])) {
  129. mergeWithoutOverwrite(target[key], source[key]);
  130. } else if (target[key] === void 0) {
  131. if (isNonNullObject(source[key])) {
  132. target[key] = Array.isArray(source[key]) ? [] : {};
  133. mergeWithoutOverwrite(target[key], source[key]);
  134. } else if (source[key] !== void 0) {
  135. target[key] = source[key];
  136. }
  137. }
  138. }
  139. }
  140. /**
  141. * The error for plugin conflicts.
  142. */
  143. class PluginConflictError extends Error {
  144. /**
  145. * Initialize this error object.
  146. * @param {string} pluginId The plugin ID.
  147. * @param {{filePath:string, importerName:string}[]} plugins The resolved plugins.
  148. */
  149. constructor(pluginId, plugins) {
  150. super(`Plugin "${pluginId}" was conflicted between ${plugins.map(p => `"${p.importerName}"`).join(" and ")}.`);
  151. this.messageTemplate = "plugin-conflict";
  152. this.messageData = { pluginId, plugins };
  153. }
  154. }
  155. /**
  156. * Merge plugins.
  157. * `target`'s definition is prior to `source`'s.
  158. * @param {Record<string, DependentPlugin>} target The destination to merge
  159. * @param {Record<string, DependentPlugin>|undefined} source The source to merge.
  160. * @returns {void}
  161. */
  162. function mergePlugins(target, source) {
  163. if (!isNonNullObject(source)) {
  164. return;
  165. }
  166. for (const key of Object.keys(source)) {
  167. if (key === "__proto__") {
  168. continue;
  169. }
  170. const targetValue = target[key];
  171. const sourceValue = source[key];
  172. // Adopt the plugin which was found at first.
  173. if (targetValue === void 0) {
  174. if (sourceValue.error) {
  175. throw sourceValue.error;
  176. }
  177. target[key] = sourceValue;
  178. } else if (sourceValue.filePath !== targetValue.filePath) {
  179. throw new PluginConflictError(key, [
  180. {
  181. filePath: targetValue.filePath,
  182. importerName: targetValue.importerName
  183. },
  184. {
  185. filePath: sourceValue.filePath,
  186. importerName: sourceValue.importerName
  187. }
  188. ]);
  189. }
  190. }
  191. }
  192. /**
  193. * Merge rule configs.
  194. * `target`'s definition is prior to `source`'s.
  195. * @param {Record<string, Array>} target The destination to merge
  196. * @param {Record<string, RuleConf>|undefined} source The source to merge.
  197. * @returns {void}
  198. */
  199. function mergeRuleConfigs(target, source) {
  200. if (!isNonNullObject(source)) {
  201. return;
  202. }
  203. for (const key of Object.keys(source)) {
  204. if (key === "__proto__") {
  205. continue;
  206. }
  207. const targetDef = target[key];
  208. const sourceDef = source[key];
  209. // Adopt the rule config which was found at first.
  210. if (targetDef === void 0) {
  211. if (Array.isArray(sourceDef)) {
  212. target[key] = [...sourceDef];
  213. } else {
  214. target[key] = [sourceDef];
  215. }
  216. /*
  217. * If the first found rule config is severity only and the current rule
  218. * config has options, merge the severity and the options.
  219. */
  220. } else if (
  221. targetDef.length === 1 &&
  222. Array.isArray(sourceDef) &&
  223. sourceDef.length >= 2
  224. ) {
  225. targetDef.push(...sourceDef.slice(1));
  226. }
  227. }
  228. }
  229. /**
  230. * Create the extracted config.
  231. * @param {ConfigArray} instance The config elements.
  232. * @param {number[]} indices The indices to use.
  233. * @returns {ExtractedConfig} The extracted config.
  234. */
  235. function createConfig(instance, indices) {
  236. const config = new ExtractedConfig();
  237. const ignorePatterns = [];
  238. // Merge elements.
  239. for (const index of indices) {
  240. const element = instance[index];
  241. // Adopt the parser which was found at first.
  242. if (!config.parser && element.parser) {
  243. if (element.parser.error) {
  244. throw element.parser.error;
  245. }
  246. config.parser = element.parser;
  247. }
  248. // Adopt the processor which was found at first.
  249. if (!config.processor && element.processor) {
  250. config.processor = element.processor;
  251. }
  252. // Adopt the noInlineConfig which was found at first.
  253. if (config.noInlineConfig === void 0 && element.noInlineConfig !== void 0) {
  254. config.noInlineConfig = element.noInlineConfig;
  255. config.configNameOfNoInlineConfig = element.name;
  256. }
  257. // Adopt the reportUnusedDisableDirectives which was found at first.
  258. if (config.reportUnusedDisableDirectives === void 0 && element.reportUnusedDisableDirectives !== void 0) {
  259. config.reportUnusedDisableDirectives = element.reportUnusedDisableDirectives;
  260. }
  261. // Collect ignorePatterns
  262. if (element.ignorePattern) {
  263. ignorePatterns.push(element.ignorePattern);
  264. }
  265. // Merge others.
  266. mergeWithoutOverwrite(config.env, element.env);
  267. mergeWithoutOverwrite(config.globals, element.globals);
  268. mergeWithoutOverwrite(config.parserOptions, element.parserOptions);
  269. mergeWithoutOverwrite(config.settings, element.settings);
  270. mergePlugins(config.plugins, element.plugins);
  271. mergeRuleConfigs(config.rules, element.rules);
  272. }
  273. // Create the predicate function for ignore patterns.
  274. if (ignorePatterns.length > 0) {
  275. config.ignores = IgnorePattern.createIgnore(ignorePatterns.reverse());
  276. }
  277. return config;
  278. }
  279. /**
  280. * Collect definitions.
  281. * @template T, U
  282. * @param {string} pluginId The plugin ID for prefix.
  283. * @param {Record<string,T>} defs The definitions to collect.
  284. * @param {Map<string, U>} map The map to output.
  285. * @returns {void}
  286. */
  287. function collect(pluginId, defs, map) {
  288. if (defs) {
  289. const prefix = pluginId && `${pluginId}/`;
  290. for (const [key, value] of Object.entries(defs)) {
  291. map.set(`${prefix}${key}`, value);
  292. }
  293. }
  294. }
  295. /**
  296. * Delete the mutation methods from a given map.
  297. * @param {Map<any, any>} map The map object to delete.
  298. * @returns {void}
  299. */
  300. function deleteMutationMethods(map) {
  301. Object.defineProperties(map, {
  302. clear: { configurable: true, value: void 0 },
  303. delete: { configurable: true, value: void 0 },
  304. set: { configurable: true, value: void 0 }
  305. });
  306. }
  307. /**
  308. * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
  309. * @param {ConfigArrayElement[]} elements The config elements.
  310. * @param {ConfigArrayInternalSlots} slots The internal slots.
  311. * @returns {void}
  312. */
  313. function initPluginMemberMaps(elements, slots) {
  314. const processed = new Set();
  315. slots.envMap = new Map();
  316. slots.processorMap = new Map();
  317. slots.ruleMap = new Map();
  318. for (const element of elements) {
  319. if (!element.plugins) {
  320. continue;
  321. }
  322. for (const [pluginId, value] of Object.entries(element.plugins)) {
  323. const plugin = value.definition;
  324. if (!plugin || processed.has(pluginId)) {
  325. continue;
  326. }
  327. processed.add(pluginId);
  328. collect(pluginId, plugin.environments, slots.envMap);
  329. collect(pluginId, plugin.processors, slots.processorMap);
  330. collect(pluginId, plugin.rules, slots.ruleMap);
  331. }
  332. }
  333. deleteMutationMethods(slots.envMap);
  334. deleteMutationMethods(slots.processorMap);
  335. deleteMutationMethods(slots.ruleMap);
  336. }
  337. /**
  338. * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
  339. * @param {ConfigArray} instance The config elements.
  340. * @returns {ConfigArrayInternalSlots} The extracted config.
  341. */
  342. function ensurePluginMemberMaps(instance) {
  343. const slots = internalSlotsMap.get(instance);
  344. if (!slots.ruleMap) {
  345. initPluginMemberMaps(instance, slots);
  346. }
  347. return slots;
  348. }
  349. //------------------------------------------------------------------------------
  350. // Public Interface
  351. //------------------------------------------------------------------------------
  352. /**
  353. * The Config Array.
  354. *
  355. * `ConfigArray` instance contains all settings, parsers, and plugins.
  356. * You need to call `ConfigArray#extractConfig(filePath)` method in order to
  357. * extract, merge and get only the config data which is related to an arbitrary
  358. * file.
  359. * @extends {Array<ConfigArrayElement>}
  360. */
  361. class ConfigArray extends Array {
  362. /**
  363. * Get the plugin environments.
  364. * The returned map cannot be mutated.
  365. * @type {ReadonlyMap<string, Environment>} The plugin environments.
  366. */
  367. get pluginEnvironments() {
  368. return ensurePluginMemberMaps(this).envMap;
  369. }
  370. /**
  371. * Get the plugin processors.
  372. * The returned map cannot be mutated.
  373. * @type {ReadonlyMap<string, Processor>} The plugin processors.
  374. */
  375. get pluginProcessors() {
  376. return ensurePluginMemberMaps(this).processorMap;
  377. }
  378. /**
  379. * Get the plugin rules.
  380. * The returned map cannot be mutated.
  381. * @returns {ReadonlyMap<string, Rule>} The plugin rules.
  382. */
  383. get pluginRules() {
  384. return ensurePluginMemberMaps(this).ruleMap;
  385. }
  386. /**
  387. * Check if this config has `root` flag.
  388. * @returns {boolean} `true` if this config array is root.
  389. */
  390. isRoot() {
  391. for (let i = this.length - 1; i >= 0; --i) {
  392. const root = this[i].root;
  393. if (typeof root === "boolean") {
  394. return root;
  395. }
  396. }
  397. return false;
  398. }
  399. /**
  400. * Extract the config data which is related to a given file.
  401. * @param {string} filePath The absolute path to the target file.
  402. * @returns {ExtractedConfig} The extracted config data.
  403. */
  404. extractConfig(filePath) {
  405. const { cache } = internalSlotsMap.get(this);
  406. const indices = getMatchedIndices(this, filePath);
  407. const cacheKey = indices.join(",");
  408. if (!cache.has(cacheKey)) {
  409. cache.set(cacheKey, createConfig(this, indices));
  410. }
  411. return cache.get(cacheKey);
  412. }
  413. /**
  414. * Check if a given path is an additional lint target.
  415. * @param {string} filePath The absolute path to the target file.
  416. * @returns {boolean} `true` if the file is an additional lint target.
  417. */
  418. isAdditionalTargetPath(filePath) {
  419. for (const { criteria, type } of this) {
  420. if (
  421. type === "config" &&
  422. criteria &&
  423. !criteria.endsWithWildcard &&
  424. criteria.test(filePath)
  425. ) {
  426. return true;
  427. }
  428. }
  429. return false;
  430. }
  431. }
  432. /**
  433. * Get the used extracted configs.
  434. * CLIEngine will use this method to collect used deprecated rules.
  435. * @param {ConfigArray} instance The config array object to get.
  436. * @returns {ExtractedConfig[]} The used extracted configs.
  437. * @private
  438. */
  439. function getUsedExtractedConfigs(instance) {
  440. const { cache } = internalSlotsMap.get(instance);
  441. return Array.from(cache.values());
  442. }
  443. export {
  444. ConfigArray,
  445. getUsedExtractedConfigs
  446. };