config-array.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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 provies 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. "use strict";
  28. //------------------------------------------------------------------------------
  29. // Requirements
  30. //------------------------------------------------------------------------------
  31. const { ExtractedConfig } = require("./extracted-config");
  32. const { IgnorePattern } = require("./ignore-pattern");
  33. //------------------------------------------------------------------------------
  34. // Helpers
  35. //------------------------------------------------------------------------------
  36. // Define types for VSCode IntelliSense.
  37. /** @typedef {import("../../shared/types").Environment} Environment */
  38. /** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
  39. /** @typedef {import("../../shared/types").RuleConf} RuleConf */
  40. /** @typedef {import("../../shared/types").Rule} Rule */
  41. /** @typedef {import("../../shared/types").Plugin} Plugin */
  42. /** @typedef {import("../../shared/types").Processor} Processor */
  43. /** @typedef {import("./config-dependency").DependentParser} DependentParser */
  44. /** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
  45. /** @typedef {import("./override-tester")["OverrideTester"]} OverrideTester */
  46. /**
  47. * @typedef {Object} ConfigArrayElement
  48. * @property {string} name The name of this config element.
  49. * @property {string} filePath The path to the source file of this config element.
  50. * @property {InstanceType<OverrideTester>|null} criteria The tester for the `files` and `excludedFiles` of this config element.
  51. * @property {Record<string, boolean>|undefined} env The environment settings.
  52. * @property {Record<string, GlobalConf>|undefined} globals The global variable settings.
  53. * @property {IgnorePattern|undefined} ignorePattern The ignore patterns.
  54. * @property {boolean|undefined} noInlineConfig The flag that disables directive comments.
  55. * @property {DependentParser|undefined} parser The parser loader.
  56. * @property {Object|undefined} parserOptions The parser options.
  57. * @property {Record<string, DependentPlugin>|undefined} plugins The plugin loaders.
  58. * @property {string|undefined} processor The processor name to refer plugin's processor.
  59. * @property {boolean|undefined} reportUnusedDisableDirectives The flag to report unused `eslint-disable` comments.
  60. * @property {boolean|undefined} root The flag to express root.
  61. * @property {Record<string, RuleConf>|undefined} rules The rule settings
  62. * @property {Object|undefined} settings The shared settings.
  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 || 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. * Merge plugins.
  142. * `target`'s definition is prior to `source`'s.
  143. * @param {Record<string, DependentPlugin>} target The destination to merge
  144. * @param {Record<string, DependentPlugin>|undefined} source The source to merge.
  145. * @returns {void}
  146. */
  147. function mergePlugins(target, source) {
  148. if (!isNonNullObject(source)) {
  149. return;
  150. }
  151. for (const key of Object.keys(source)) {
  152. if (key === "__proto__") {
  153. continue;
  154. }
  155. const targetValue = target[key];
  156. const sourceValue = source[key];
  157. // Adopt the plugin which was found at first.
  158. if (targetValue === void 0) {
  159. if (sourceValue.error) {
  160. throw sourceValue.error;
  161. }
  162. target[key] = sourceValue;
  163. }
  164. }
  165. }
  166. /**
  167. * Merge rule configs.
  168. * `target`'s definition is prior to `source`'s.
  169. * @param {Record<string, Array>} target The destination to merge
  170. * @param {Record<string, RuleConf>|undefined} source The source to merge.
  171. * @returns {void}
  172. */
  173. function mergeRuleConfigs(target, source) {
  174. if (!isNonNullObject(source)) {
  175. return;
  176. }
  177. for (const key of Object.keys(source)) {
  178. if (key === "__proto__") {
  179. continue;
  180. }
  181. const targetDef = target[key];
  182. const sourceDef = source[key];
  183. // Adopt the rule config which was found at first.
  184. if (targetDef === void 0) {
  185. if (Array.isArray(sourceDef)) {
  186. target[key] = [...sourceDef];
  187. } else {
  188. target[key] = [sourceDef];
  189. }
  190. /*
  191. * If the first found rule config is severity only and the current rule
  192. * config has options, merge the severity and the options.
  193. */
  194. } else if (
  195. targetDef.length === 1 &&
  196. Array.isArray(sourceDef) &&
  197. sourceDef.length >= 2
  198. ) {
  199. targetDef.push(...sourceDef.slice(1));
  200. }
  201. }
  202. }
  203. /**
  204. * Create the extracted config.
  205. * @param {ConfigArray} instance The config elements.
  206. * @param {number[]} indices The indices to use.
  207. * @returns {ExtractedConfig} The extracted config.
  208. */
  209. function createConfig(instance, indices) {
  210. const config = new ExtractedConfig();
  211. const ignorePatterns = [];
  212. // Merge elements.
  213. for (const index of indices) {
  214. const element = instance[index];
  215. // Adopt the parser which was found at first.
  216. if (!config.parser && element.parser) {
  217. if (element.parser.error) {
  218. throw element.parser.error;
  219. }
  220. config.parser = element.parser;
  221. }
  222. // Adopt the processor which was found at first.
  223. if (!config.processor && element.processor) {
  224. config.processor = element.processor;
  225. }
  226. // Adopt the noInlineConfig which was found at first.
  227. if (config.noInlineConfig === void 0 && element.noInlineConfig !== void 0) {
  228. config.noInlineConfig = element.noInlineConfig;
  229. config.configNameOfNoInlineConfig = element.name;
  230. }
  231. // Adopt the reportUnusedDisableDirectives which was found at first.
  232. if (config.reportUnusedDisableDirectives === void 0 && element.reportUnusedDisableDirectives !== void 0) {
  233. config.reportUnusedDisableDirectives = element.reportUnusedDisableDirectives;
  234. }
  235. // Collect ignorePatterns
  236. if (element.ignorePattern) {
  237. ignorePatterns.push(element.ignorePattern);
  238. }
  239. // Merge others.
  240. mergeWithoutOverwrite(config.env, element.env);
  241. mergeWithoutOverwrite(config.globals, element.globals);
  242. mergeWithoutOverwrite(config.parserOptions, element.parserOptions);
  243. mergeWithoutOverwrite(config.settings, element.settings);
  244. mergePlugins(config.plugins, element.plugins);
  245. mergeRuleConfigs(config.rules, element.rules);
  246. }
  247. // Create the predicate function for ignore patterns.
  248. if (ignorePatterns.length > 0) {
  249. config.ignores = IgnorePattern.createIgnore(ignorePatterns.reverse());
  250. }
  251. return config;
  252. }
  253. /**
  254. * Collect definitions.
  255. * @template T, U
  256. * @param {string} pluginId The plugin ID for prefix.
  257. * @param {Record<string,T>} defs The definitions to collect.
  258. * @param {Map<string, U>} map The map to output.
  259. * @param {function(T): U} [normalize] The normalize function for each value.
  260. * @returns {void}
  261. */
  262. function collect(pluginId, defs, map, normalize) {
  263. if (defs) {
  264. const prefix = pluginId && `${pluginId}/`;
  265. for (const [key, value] of Object.entries(defs)) {
  266. map.set(
  267. `${prefix}${key}`,
  268. normalize ? normalize(value) : value
  269. );
  270. }
  271. }
  272. }
  273. /**
  274. * Normalize a rule definition.
  275. * @param {Function|Rule} rule The rule definition to normalize.
  276. * @returns {Rule} The normalized rule definition.
  277. */
  278. function normalizePluginRule(rule) {
  279. return typeof rule === "function" ? { create: rule } : rule;
  280. }
  281. /**
  282. * Delete the mutation methods from a given map.
  283. * @param {Map<any, any>} map The map object to delete.
  284. * @returns {void}
  285. */
  286. function deleteMutationMethods(map) {
  287. Object.defineProperties(map, {
  288. clear: { configurable: true, value: void 0 },
  289. delete: { configurable: true, value: void 0 },
  290. set: { configurable: true, value: void 0 }
  291. });
  292. }
  293. /**
  294. * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
  295. * @param {ConfigArrayElement[]} elements The config elements.
  296. * @param {ConfigArrayInternalSlots} slots The internal slots.
  297. * @returns {void}
  298. */
  299. function initPluginMemberMaps(elements, slots) {
  300. const processed = new Set();
  301. slots.envMap = new Map();
  302. slots.processorMap = new Map();
  303. slots.ruleMap = new Map();
  304. for (const element of elements) {
  305. if (!element.plugins) {
  306. continue;
  307. }
  308. for (const [pluginId, value] of Object.entries(element.plugins)) {
  309. const plugin = value.definition;
  310. if (!plugin || processed.has(pluginId)) {
  311. continue;
  312. }
  313. processed.add(pluginId);
  314. collect(pluginId, plugin.environments, slots.envMap);
  315. collect(pluginId, plugin.processors, slots.processorMap);
  316. collect(pluginId, plugin.rules, slots.ruleMap, normalizePluginRule);
  317. }
  318. }
  319. deleteMutationMethods(slots.envMap);
  320. deleteMutationMethods(slots.processorMap);
  321. deleteMutationMethods(slots.ruleMap);
  322. }
  323. /**
  324. * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
  325. * @param {ConfigArray} instance The config elements.
  326. * @returns {ConfigArrayInternalSlots} The extracted config.
  327. */
  328. function ensurePluginMemberMaps(instance) {
  329. const slots = internalSlotsMap.get(instance);
  330. if (!slots.ruleMap) {
  331. initPluginMemberMaps(instance, slots);
  332. }
  333. return slots;
  334. }
  335. //------------------------------------------------------------------------------
  336. // Public Interface
  337. //------------------------------------------------------------------------------
  338. /**
  339. * The Config Array.
  340. *
  341. * `ConfigArray` instance contains all settings, parsers, and plugins.
  342. * You need to call `ConfigArray#extractConfig(filePath)` method in order to
  343. * extract, merge and get only the config data which is related to an arbitrary
  344. * file.
  345. * @extends {Array<ConfigArrayElement>}
  346. */
  347. class ConfigArray extends Array {
  348. /**
  349. * Get the plugin environments.
  350. * The returned map cannot be mutated.
  351. * @type {ReadonlyMap<string, Environment>} The plugin environments.
  352. */
  353. get pluginEnvironments() {
  354. return ensurePluginMemberMaps(this).envMap;
  355. }
  356. /**
  357. * Get the plugin processors.
  358. * The returned map cannot be mutated.
  359. * @type {ReadonlyMap<string, Processor>} The plugin processors.
  360. */
  361. get pluginProcessors() {
  362. return ensurePluginMemberMaps(this).processorMap;
  363. }
  364. /**
  365. * Get the plugin rules.
  366. * The returned map cannot be mutated.
  367. * @returns {ReadonlyMap<string, Rule>} The plugin rules.
  368. */
  369. get pluginRules() {
  370. return ensurePluginMemberMaps(this).ruleMap;
  371. }
  372. /**
  373. * Check if this config has `root` flag.
  374. * @returns {boolean} `true` if this config array is root.
  375. */
  376. isRoot() {
  377. for (let i = this.length - 1; i >= 0; --i) {
  378. const root = this[i].root;
  379. if (typeof root === "boolean") {
  380. return root;
  381. }
  382. }
  383. return false;
  384. }
  385. /**
  386. * Extract the config data which is related to a given file.
  387. * @param {string} filePath The absolute path to the target file.
  388. * @returns {ExtractedConfig} The extracted config data.
  389. */
  390. extractConfig(filePath) {
  391. const { cache } = internalSlotsMap.get(this);
  392. const indices = getMatchedIndices(this, filePath);
  393. const cacheKey = indices.join(",");
  394. if (!cache.has(cacheKey)) {
  395. cache.set(cacheKey, createConfig(this, indices));
  396. }
  397. return cache.get(cacheKey);
  398. }
  399. }
  400. const exportObject = {
  401. ConfigArray,
  402. /**
  403. * Get the used extracted configs.
  404. * CLIEngine will use this method to collect used deprecated rules.
  405. * @param {ConfigArray} instance The config array object to get.
  406. * @returns {ExtractedConfig[]} The used extracted configs.
  407. * @private
  408. */
  409. getUsedExtractedConfigs(instance) {
  410. const { cache } = internalSlotsMap.get(instance);
  411. return Array.from(cache.values());
  412. }
  413. };
  414. module.exports = exportObject;