config-array-factory.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  1. /**
  2. * @fileoverview The factory of `ConfigArray` objects.
  3. *
  4. * This class provides methods to create `ConfigArray` instance.
  5. *
  6. * - `create(configData, options)`
  7. * Create a `ConfigArray` instance from a config data. This is to handle CLI
  8. * options except `--config`.
  9. * - `loadFile(filePath, options)`
  10. * Create a `ConfigArray` instance from a config file. This is to handle
  11. * `--config` option. If the file was not found, throws the following error:
  12. * - If the filename was `*.js`, a `MODULE_NOT_FOUND` error.
  13. * - If the filename was `package.json`, an IO error or an
  14. * `ESLINT_CONFIG_FIELD_NOT_FOUND` error.
  15. * - Otherwise, an IO error such as `ENOENT`.
  16. * - `loadInDirectory(directoryPath, options)`
  17. * Create a `ConfigArray` instance from a config file which is on a given
  18. * directory. This tries to load `.eslintrc.*` or `package.json`. If not
  19. * found, returns an empty `ConfigArray`.
  20. * - `loadESLintIgnore(filePath)`
  21. * Create a `ConfigArray` instance from a config file that is `.eslintignore`
  22. * format. This is to handle `--ignore-path` option.
  23. * - `loadDefaultESLintIgnore()`
  24. * Create a `ConfigArray` instance from `.eslintignore` or `package.json` in
  25. * the current working directory.
  26. *
  27. * `ConfigArrayFactory` class has the responsibility that loads configuration
  28. * files, including loading `extends`, `parser`, and `plugins`. The created
  29. * `ConfigArray` instance has the loaded `extends`, `parser`, and `plugins`.
  30. *
  31. * But this class doesn't handle cascading. `CascadingConfigArrayFactory` class
  32. * handles cascading and hierarchy.
  33. *
  34. * @author Toru Nagashima <https://github.com/mysticatea>
  35. */
  36. "use strict";
  37. //------------------------------------------------------------------------------
  38. // Requirements
  39. //------------------------------------------------------------------------------
  40. const fs = require("fs");
  41. const path = require("path");
  42. const importFresh = require("import-fresh");
  43. const stripComments = require("strip-json-comments");
  44. const ConfigValidator = require("./shared/config-validator");
  45. const naming = require("./shared/naming");
  46. const ModuleResolver = require("./shared/relative-module-resolver");
  47. const {
  48. ConfigArray,
  49. ConfigDependency,
  50. IgnorePattern,
  51. OverrideTester
  52. } = require("./config-array");
  53. const debug = require("debug")("eslintrc:config-array-factory");
  54. //------------------------------------------------------------------------------
  55. // Helpers
  56. //------------------------------------------------------------------------------
  57. const configFilenames = [
  58. ".eslintrc.js",
  59. ".eslintrc.cjs",
  60. ".eslintrc.yaml",
  61. ".eslintrc.yml",
  62. ".eslintrc.json",
  63. ".eslintrc",
  64. "package.json"
  65. ];
  66. // Define types for VSCode IntelliSense.
  67. /** @typedef {import("./shared/types").ConfigData} ConfigData */
  68. /** @typedef {import("./shared/types").OverrideConfigData} OverrideConfigData */
  69. /** @typedef {import("./shared/types").Parser} Parser */
  70. /** @typedef {import("./shared/types").Plugin} Plugin */
  71. /** @typedef {import("./shared/types").Rule} Rule */
  72. /** @typedef {import("./config-array/config-dependency").DependentParser} DependentParser */
  73. /** @typedef {import("./config-array/config-dependency").DependentPlugin} DependentPlugin */
  74. /** @typedef {ConfigArray[0]} ConfigArrayElement */
  75. /**
  76. * @typedef {Object} ConfigArrayFactoryOptions
  77. * @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
  78. * @property {string} [cwd] The path to the current working directory.
  79. * @property {string} [resolvePluginsRelativeTo] A path to the directory that plugins should be resolved from. Defaults to `cwd`.
  80. * @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
  81. * @property {Object} [resolver=ModuleResolver] The module resolver object.
  82. * @property {string} eslintAllPath The path to the definitions for eslint:all.
  83. * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
  84. */
  85. /**
  86. * @typedef {Object} ConfigArrayFactoryInternalSlots
  87. * @property {Map<string,Plugin>} additionalPluginPool The map for additional plugins.
  88. * @property {string} cwd The path to the current working directory.
  89. * @property {string | undefined} resolvePluginsRelativeTo An absolute path the the directory that plugins should be resolved from.
  90. * @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
  91. * @property {Object} [resolver=ModuleResolver] The module resolver object.
  92. * @property {string} eslintAllPath The path to the definitions for eslint:all.
  93. * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
  94. */
  95. /**
  96. * @typedef {Object} ConfigArrayFactoryLoadingContext
  97. * @property {string} filePath The path to the current configuration.
  98. * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
  99. * @property {string} name The name of the current configuration.
  100. * @property {string} pluginBasePath The base path to resolve plugins.
  101. * @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.
  102. */
  103. /**
  104. * @typedef {Object} ConfigArrayFactoryLoadingContext
  105. * @property {string} filePath The path to the current configuration.
  106. * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
  107. * @property {string} name The name of the current configuration.
  108. * @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.
  109. */
  110. /** @type {WeakMap<ConfigArrayFactory, ConfigArrayFactoryInternalSlots>} */
  111. const internalSlotsMap = new WeakMap();
  112. /**
  113. * Check if a given string is a file path.
  114. * @param {string} nameOrPath A module name or file path.
  115. * @returns {boolean} `true` if the `nameOrPath` is a file path.
  116. */
  117. function isFilePath(nameOrPath) {
  118. return (
  119. /^\.{1,2}[/\\]/u.test(nameOrPath) ||
  120. path.isAbsolute(nameOrPath)
  121. );
  122. }
  123. /**
  124. * Convenience wrapper for synchronously reading file contents.
  125. * @param {string} filePath The filename to read.
  126. * @returns {string} The file contents, with the BOM removed.
  127. * @private
  128. */
  129. function readFile(filePath) {
  130. return fs.readFileSync(filePath, "utf8").replace(/^\ufeff/u, "");
  131. }
  132. /**
  133. * Loads a YAML configuration from a file.
  134. * @param {string} filePath The filename to load.
  135. * @returns {ConfigData} The configuration object from the file.
  136. * @throws {Error} If the file cannot be read.
  137. * @private
  138. */
  139. function loadYAMLConfigFile(filePath) {
  140. debug(`Loading YAML config file: ${filePath}`);
  141. // lazy load YAML to improve performance when not used
  142. const yaml = require("js-yaml");
  143. try {
  144. // empty YAML file can be null, so always use
  145. return yaml.safeLoad(readFile(filePath)) || {};
  146. } catch (e) {
  147. debug(`Error reading YAML file: ${filePath}`);
  148. e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
  149. throw e;
  150. }
  151. }
  152. /**
  153. * Loads a JSON configuration from a file.
  154. * @param {string} filePath The filename to load.
  155. * @returns {ConfigData} The configuration object from the file.
  156. * @throws {Error} If the file cannot be read.
  157. * @private
  158. */
  159. function loadJSONConfigFile(filePath) {
  160. debug(`Loading JSON config file: ${filePath}`);
  161. try {
  162. return JSON.parse(stripComments(readFile(filePath)));
  163. } catch (e) {
  164. debug(`Error reading JSON file: ${filePath}`);
  165. e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
  166. e.messageTemplate = "failed-to-read-json";
  167. e.messageData = {
  168. path: filePath,
  169. message: e.message
  170. };
  171. throw e;
  172. }
  173. }
  174. /**
  175. * Loads a legacy (.eslintrc) configuration from a file.
  176. * @param {string} filePath The filename to load.
  177. * @returns {ConfigData} The configuration object from the file.
  178. * @throws {Error} If the file cannot be read.
  179. * @private
  180. */
  181. function loadLegacyConfigFile(filePath) {
  182. debug(`Loading legacy config file: ${filePath}`);
  183. // lazy load YAML to improve performance when not used
  184. const yaml = require("js-yaml");
  185. try {
  186. return yaml.safeLoad(stripComments(readFile(filePath))) || /* istanbul ignore next */ {};
  187. } catch (e) {
  188. debug("Error reading YAML file: %s\n%o", filePath, e);
  189. e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
  190. throw e;
  191. }
  192. }
  193. /**
  194. * Loads a JavaScript configuration from a file.
  195. * @param {string} filePath The filename to load.
  196. * @returns {ConfigData} The configuration object from the file.
  197. * @throws {Error} If the file cannot be read.
  198. * @private
  199. */
  200. function loadJSConfigFile(filePath) {
  201. debug(`Loading JS config file: ${filePath}`);
  202. try {
  203. return importFresh(filePath);
  204. } catch (e) {
  205. debug(`Error reading JavaScript file: ${filePath}`);
  206. e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
  207. throw e;
  208. }
  209. }
  210. /**
  211. * Loads a configuration from a package.json file.
  212. * @param {string} filePath The filename to load.
  213. * @returns {ConfigData} The configuration object from the file.
  214. * @throws {Error} If the file cannot be read.
  215. * @private
  216. */
  217. function loadPackageJSONConfigFile(filePath) {
  218. debug(`Loading package.json config file: ${filePath}`);
  219. try {
  220. const packageData = loadJSONConfigFile(filePath);
  221. if (!Object.hasOwnProperty.call(packageData, "eslintConfig")) {
  222. throw Object.assign(
  223. new Error("package.json file doesn't have 'eslintConfig' field."),
  224. { code: "ESLINT_CONFIG_FIELD_NOT_FOUND" }
  225. );
  226. }
  227. return packageData.eslintConfig;
  228. } catch (e) {
  229. debug(`Error reading package.json file: ${filePath}`);
  230. e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
  231. throw e;
  232. }
  233. }
  234. /**
  235. * Loads a `.eslintignore` from a file.
  236. * @param {string} filePath The filename to load.
  237. * @returns {string[]} The ignore patterns from the file.
  238. * @private
  239. */
  240. function loadESLintIgnoreFile(filePath) {
  241. debug(`Loading .eslintignore file: ${filePath}`);
  242. try {
  243. return readFile(filePath)
  244. .split(/\r?\n/gu)
  245. .filter(line => line.trim() !== "" && !line.startsWith("#"));
  246. } catch (e) {
  247. debug(`Error reading .eslintignore file: ${filePath}`);
  248. e.message = `Cannot read .eslintignore file: ${filePath}\nError: ${e.message}`;
  249. throw e;
  250. }
  251. }
  252. /**
  253. * Creates an error to notify about a missing config to extend from.
  254. * @param {string} configName The name of the missing config.
  255. * @param {string} importerName The name of the config that imported the missing config
  256. * @returns {Error} The error object to throw
  257. * @private
  258. */
  259. function configMissingError(configName, importerName) {
  260. return Object.assign(
  261. new Error(`Failed to load config "${configName}" to extend from.`),
  262. {
  263. messageTemplate: "extend-config-missing",
  264. messageData: { configName, importerName }
  265. }
  266. );
  267. }
  268. /**
  269. * Loads a configuration file regardless of the source. Inspects the file path
  270. * to determine the correctly way to load the config file.
  271. * @param {string} filePath The path to the configuration.
  272. * @returns {ConfigData|null} The configuration information.
  273. * @private
  274. */
  275. function loadConfigFile(filePath) {
  276. switch (path.extname(filePath)) {
  277. case ".js":
  278. case ".cjs":
  279. return loadJSConfigFile(filePath);
  280. case ".json":
  281. if (path.basename(filePath) === "package.json") {
  282. return loadPackageJSONConfigFile(filePath);
  283. }
  284. return loadJSONConfigFile(filePath);
  285. case ".yaml":
  286. case ".yml":
  287. return loadYAMLConfigFile(filePath);
  288. default:
  289. return loadLegacyConfigFile(filePath);
  290. }
  291. }
  292. /**
  293. * Write debug log.
  294. * @param {string} request The requested module name.
  295. * @param {string} relativeTo The file path to resolve the request relative to.
  296. * @param {string} filePath The resolved file path.
  297. * @returns {void}
  298. */
  299. function writeDebugLogForLoading(request, relativeTo, filePath) {
  300. /* istanbul ignore next */
  301. if (debug.enabled) {
  302. let nameAndVersion = null;
  303. try {
  304. const packageJsonPath = ModuleResolver.resolve(
  305. `${request}/package.json`,
  306. relativeTo
  307. );
  308. const { version = "unknown" } = require(packageJsonPath);
  309. nameAndVersion = `${request}@${version}`;
  310. } catch (error) {
  311. debug("package.json was not found:", error.message);
  312. nameAndVersion = request;
  313. }
  314. debug("Loaded: %s (%s)", nameAndVersion, filePath);
  315. }
  316. }
  317. /**
  318. * Create a new context with default values.
  319. * @param {ConfigArrayFactoryInternalSlots} slots The internal slots.
  320. * @param {"config" | "ignore" | "implicit-processor" | undefined} providedType The type of the current configuration. Default is `"config"`.
  321. * @param {string | undefined} providedName The name of the current configuration. Default is the relative path from `cwd` to `filePath`.
  322. * @param {string | undefined} providedFilePath The path to the current configuration. Default is empty string.
  323. * @param {string | undefined} providedMatchBasePath The type of the current configuration. Default is the directory of `filePath` or `cwd`.
  324. * @returns {ConfigArrayFactoryLoadingContext} The created context.
  325. */
  326. function createContext(
  327. { cwd, resolvePluginsRelativeTo },
  328. providedType,
  329. providedName,
  330. providedFilePath,
  331. providedMatchBasePath
  332. ) {
  333. const filePath = providedFilePath
  334. ? path.resolve(cwd, providedFilePath)
  335. : "";
  336. const matchBasePath =
  337. (providedMatchBasePath && path.resolve(cwd, providedMatchBasePath)) ||
  338. (filePath && path.dirname(filePath)) ||
  339. cwd;
  340. const name =
  341. providedName ||
  342. (filePath && path.relative(cwd, filePath)) ||
  343. "";
  344. const pluginBasePath =
  345. resolvePluginsRelativeTo ||
  346. (filePath && path.dirname(filePath)) ||
  347. cwd;
  348. const type = providedType || "config";
  349. return { filePath, matchBasePath, name, pluginBasePath, type };
  350. }
  351. /**
  352. * Normalize a given plugin.
  353. * - Ensure the object to have four properties: configs, environments, processors, and rules.
  354. * - Ensure the object to not have other properties.
  355. * @param {Plugin} plugin The plugin to normalize.
  356. * @returns {Plugin} The normalized plugin.
  357. */
  358. function normalizePlugin(plugin) {
  359. return {
  360. configs: plugin.configs || {},
  361. environments: plugin.environments || {},
  362. processors: plugin.processors || {},
  363. rules: plugin.rules || {}
  364. };
  365. }
  366. //------------------------------------------------------------------------------
  367. // Public Interface
  368. //------------------------------------------------------------------------------
  369. /**
  370. * The factory of `ConfigArray` objects.
  371. */
  372. class ConfigArrayFactory {
  373. /**
  374. * Initialize this instance.
  375. * @param {ConfigArrayFactoryOptions} [options] The map for additional plugins.
  376. */
  377. constructor({
  378. additionalPluginPool = new Map(),
  379. cwd = process.cwd(),
  380. resolvePluginsRelativeTo,
  381. builtInRules,
  382. resolver = ModuleResolver,
  383. eslintAllPath,
  384. eslintRecommendedPath
  385. } = {}) {
  386. internalSlotsMap.set(this, {
  387. additionalPluginPool,
  388. cwd,
  389. resolvePluginsRelativeTo:
  390. resolvePluginsRelativeTo &&
  391. path.resolve(cwd, resolvePluginsRelativeTo),
  392. builtInRules,
  393. resolver,
  394. eslintAllPath,
  395. eslintRecommendedPath
  396. });
  397. }
  398. /**
  399. * Create `ConfigArray` instance from a config data.
  400. * @param {ConfigData|null} configData The config data to create.
  401. * @param {Object} [options] The options.
  402. * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
  403. * @param {string} [options.filePath] The path to this config data.
  404. * @param {string} [options.name] The config name.
  405. * @returns {ConfigArray} Loaded config.
  406. */
  407. create(configData, { basePath, filePath, name } = {}) {
  408. if (!configData) {
  409. return new ConfigArray();
  410. }
  411. const slots = internalSlotsMap.get(this);
  412. const ctx = createContext(slots, "config", name, filePath, basePath);
  413. const elements = this._normalizeConfigData(configData, ctx);
  414. return new ConfigArray(...elements);
  415. }
  416. /**
  417. * Load a config file.
  418. * @param {string} filePath The path to a config file.
  419. * @param {Object} [options] The options.
  420. * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
  421. * @param {string} [options.name] The config name.
  422. * @returns {ConfigArray} Loaded config.
  423. */
  424. loadFile(filePath, { basePath, name } = {}) {
  425. const slots = internalSlotsMap.get(this);
  426. const ctx = createContext(slots, "config", name, filePath, basePath);
  427. return new ConfigArray(...this._loadConfigData(ctx));
  428. }
  429. /**
  430. * Load the config file on a given directory if exists.
  431. * @param {string} directoryPath The path to a directory.
  432. * @param {Object} [options] The options.
  433. * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
  434. * @param {string} [options.name] The config name.
  435. * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
  436. */
  437. loadInDirectory(directoryPath, { basePath, name } = {}) {
  438. const slots = internalSlotsMap.get(this);
  439. for (const filename of configFilenames) {
  440. const ctx = createContext(
  441. slots,
  442. "config",
  443. name,
  444. path.join(directoryPath, filename),
  445. basePath
  446. );
  447. if (fs.existsSync(ctx.filePath)) {
  448. let configData;
  449. try {
  450. configData = loadConfigFile(ctx.filePath);
  451. } catch (error) {
  452. if (!error || error.code !== "ESLINT_CONFIG_FIELD_NOT_FOUND") {
  453. throw error;
  454. }
  455. }
  456. if (configData) {
  457. debug(`Config file found: ${ctx.filePath}`);
  458. return new ConfigArray(
  459. ...this._normalizeConfigData(configData, ctx)
  460. );
  461. }
  462. }
  463. }
  464. debug(`Config file not found on ${directoryPath}`);
  465. return new ConfigArray();
  466. }
  467. /**
  468. * Check if a config file on a given directory exists or not.
  469. * @param {string} directoryPath The path to a directory.
  470. * @returns {string | null} The path to the found config file. If not found then null.
  471. */
  472. static getPathToConfigFileInDirectory(directoryPath) {
  473. for (const filename of configFilenames) {
  474. const filePath = path.join(directoryPath, filename);
  475. if (fs.existsSync(filePath)) {
  476. if (filename === "package.json") {
  477. try {
  478. loadPackageJSONConfigFile(filePath);
  479. return filePath;
  480. } catch { /* ignore */ }
  481. } else {
  482. return filePath;
  483. }
  484. }
  485. }
  486. return null;
  487. }
  488. /**
  489. * Load `.eslintignore` file.
  490. * @param {string} filePath The path to a `.eslintignore` file to load.
  491. * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
  492. */
  493. loadESLintIgnore(filePath) {
  494. const slots = internalSlotsMap.get(this);
  495. const ctx = createContext(
  496. slots,
  497. "ignore",
  498. void 0,
  499. filePath,
  500. slots.cwd
  501. );
  502. const ignorePatterns = loadESLintIgnoreFile(ctx.filePath);
  503. return new ConfigArray(
  504. ...this._normalizeESLintIgnoreData(ignorePatterns, ctx)
  505. );
  506. }
  507. /**
  508. * Load `.eslintignore` file in the current working directory.
  509. * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
  510. */
  511. loadDefaultESLintIgnore() {
  512. const slots = internalSlotsMap.get(this);
  513. const eslintIgnorePath = path.resolve(slots.cwd, ".eslintignore");
  514. const packageJsonPath = path.resolve(slots.cwd, "package.json");
  515. if (fs.existsSync(eslintIgnorePath)) {
  516. return this.loadESLintIgnore(eslintIgnorePath);
  517. }
  518. if (fs.existsSync(packageJsonPath)) {
  519. const data = loadJSONConfigFile(packageJsonPath);
  520. if (Object.hasOwnProperty.call(data, "eslintIgnore")) {
  521. if (!Array.isArray(data.eslintIgnore)) {
  522. throw new Error("Package.json eslintIgnore property requires an array of paths");
  523. }
  524. const ctx = createContext(
  525. slots,
  526. "ignore",
  527. "eslintIgnore in package.json",
  528. packageJsonPath,
  529. slots.cwd
  530. );
  531. return new ConfigArray(
  532. ...this._normalizeESLintIgnoreData(data.eslintIgnore, ctx)
  533. );
  534. }
  535. }
  536. return new ConfigArray();
  537. }
  538. /**
  539. * Load a given config file.
  540. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  541. * @returns {IterableIterator<ConfigArrayElement>} Loaded config.
  542. * @private
  543. */
  544. _loadConfigData(ctx) {
  545. return this._normalizeConfigData(loadConfigFile(ctx.filePath), ctx);
  546. }
  547. /**
  548. * Normalize a given `.eslintignore` data to config array elements.
  549. * @param {string[]} ignorePatterns The patterns to ignore files.
  550. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  551. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  552. * @private
  553. */
  554. *_normalizeESLintIgnoreData(ignorePatterns, ctx) {
  555. const elements = this._normalizeObjectConfigData(
  556. { ignorePatterns },
  557. ctx
  558. );
  559. // Set `ignorePattern.loose` flag for backward compatibility.
  560. for (const element of elements) {
  561. if (element.ignorePattern) {
  562. element.ignorePattern.loose = true;
  563. }
  564. yield element;
  565. }
  566. }
  567. /**
  568. * Normalize a given config to an array.
  569. * @param {ConfigData} configData The config data to normalize.
  570. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  571. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  572. * @private
  573. */
  574. _normalizeConfigData(configData, ctx) {
  575. const validator = new ConfigValidator();
  576. validator.validateConfigSchema(configData, ctx.name || ctx.filePath);
  577. return this._normalizeObjectConfigData(configData, ctx);
  578. }
  579. /**
  580. * Normalize a given config to an array.
  581. * @param {ConfigData|OverrideConfigData} configData The config data to normalize.
  582. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  583. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  584. * @private
  585. */
  586. *_normalizeObjectConfigData(configData, ctx) {
  587. const { files, excludedFiles, ...configBody } = configData;
  588. const criteria = OverrideTester.create(
  589. files,
  590. excludedFiles,
  591. ctx.matchBasePath
  592. );
  593. const elements = this._normalizeObjectConfigDataBody(configBody, ctx);
  594. // Apply the criteria to every element.
  595. for (const element of elements) {
  596. /*
  597. * Merge the criteria.
  598. * This is for the `overrides` entries that came from the
  599. * configurations of `overrides[].extends`.
  600. */
  601. element.criteria = OverrideTester.and(criteria, element.criteria);
  602. /*
  603. * Remove `root` property to ignore `root` settings which came from
  604. * `extends` in `overrides`.
  605. */
  606. if (element.criteria) {
  607. element.root = void 0;
  608. }
  609. yield element;
  610. }
  611. }
  612. /**
  613. * Normalize a given config to an array.
  614. * @param {ConfigData} configData The config data to normalize.
  615. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  616. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  617. * @private
  618. */
  619. *_normalizeObjectConfigDataBody(
  620. {
  621. env,
  622. extends: extend,
  623. globals,
  624. ignorePatterns,
  625. noInlineConfig,
  626. parser: parserName,
  627. parserOptions,
  628. plugins: pluginList,
  629. processor,
  630. reportUnusedDisableDirectives,
  631. root,
  632. rules,
  633. settings,
  634. overrides: overrideList = []
  635. },
  636. ctx
  637. ) {
  638. const extendList = Array.isArray(extend) ? extend : [extend];
  639. const ignorePattern = ignorePatterns && new IgnorePattern(
  640. Array.isArray(ignorePatterns) ? ignorePatterns : [ignorePatterns],
  641. ctx.matchBasePath
  642. );
  643. // Flatten `extends`.
  644. for (const extendName of extendList.filter(Boolean)) {
  645. yield* this._loadExtends(extendName, ctx);
  646. }
  647. // Load parser & plugins.
  648. const parser = parserName && this._loadParser(parserName, ctx);
  649. const plugins = pluginList && this._loadPlugins(pluginList, ctx);
  650. // Yield pseudo config data for file extension processors.
  651. if (plugins) {
  652. yield* this._takeFileExtensionProcessors(plugins, ctx);
  653. }
  654. // Yield the config data except `extends` and `overrides`.
  655. yield {
  656. // Debug information.
  657. type: ctx.type,
  658. name: ctx.name,
  659. filePath: ctx.filePath,
  660. // Config data.
  661. criteria: null,
  662. env,
  663. globals,
  664. ignorePattern,
  665. noInlineConfig,
  666. parser,
  667. parserOptions,
  668. plugins,
  669. processor,
  670. reportUnusedDisableDirectives,
  671. root,
  672. rules,
  673. settings
  674. };
  675. // Flatten `overries`.
  676. for (let i = 0; i < overrideList.length; ++i) {
  677. yield* this._normalizeObjectConfigData(
  678. overrideList[i],
  679. { ...ctx, name: `${ctx.name}#overrides[${i}]` }
  680. );
  681. }
  682. }
  683. /**
  684. * Load configs of an element in `extends`.
  685. * @param {string} extendName The name of a base config.
  686. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  687. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  688. * @private
  689. */
  690. _loadExtends(extendName, ctx) {
  691. debug("Loading {extends:%j} relative to %s", extendName, ctx.filePath);
  692. try {
  693. if (extendName.startsWith("eslint:")) {
  694. return this._loadExtendedBuiltInConfig(extendName, ctx);
  695. }
  696. if (extendName.startsWith("plugin:")) {
  697. return this._loadExtendedPluginConfig(extendName, ctx);
  698. }
  699. return this._loadExtendedShareableConfig(extendName, ctx);
  700. } catch (error) {
  701. error.message += `\nReferenced from: ${ctx.filePath || ctx.name}`;
  702. throw error;
  703. }
  704. }
  705. /**
  706. * Load configs of an element in `extends`.
  707. * @param {string} extendName The name of a base config.
  708. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  709. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  710. * @private
  711. */
  712. _loadExtendedBuiltInConfig(extendName, ctx) {
  713. const { eslintAllPath, eslintRecommendedPath } = internalSlotsMap.get(this);
  714. if (extendName === "eslint:recommended") {
  715. return this._loadConfigData({
  716. ...ctx,
  717. filePath: eslintRecommendedPath,
  718. name: `${ctx.name} » ${extendName}`
  719. });
  720. }
  721. if (extendName === "eslint:all") {
  722. return this._loadConfigData({
  723. ...ctx,
  724. filePath: eslintAllPath,
  725. name: `${ctx.name} » ${extendName}`
  726. });
  727. }
  728. throw configMissingError(extendName, ctx.name);
  729. }
  730. /**
  731. * Load configs of an element in `extends`.
  732. * @param {string} extendName The name of a base config.
  733. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  734. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  735. * @private
  736. */
  737. _loadExtendedPluginConfig(extendName, ctx) {
  738. const slashIndex = extendName.lastIndexOf("/");
  739. const pluginName = extendName.slice("plugin:".length, slashIndex);
  740. const configName = extendName.slice(slashIndex + 1);
  741. if (isFilePath(pluginName)) {
  742. throw new Error("'extends' cannot use a file path for plugins.");
  743. }
  744. const plugin = this._loadPlugin(pluginName, ctx);
  745. const configData =
  746. plugin.definition &&
  747. plugin.definition.configs[configName];
  748. if (configData) {
  749. return this._normalizeConfigData(configData, {
  750. ...ctx,
  751. filePath: plugin.filePath || ctx.filePath,
  752. name: `${ctx.name} » plugin:${plugin.id}/${configName}`
  753. });
  754. }
  755. throw plugin.error || configMissingError(extendName, ctx.filePath);
  756. }
  757. /**
  758. * Load configs of an element in `extends`.
  759. * @param {string} extendName The name of a base config.
  760. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  761. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  762. * @private
  763. */
  764. _loadExtendedShareableConfig(extendName, ctx) {
  765. const { cwd, resolver } = internalSlotsMap.get(this);
  766. const relativeTo = ctx.filePath || path.join(cwd, "__placeholder__.js");
  767. let request;
  768. if (isFilePath(extendName)) {
  769. request = extendName;
  770. } else if (extendName.startsWith(".")) {
  771. request = `./${extendName}`; // For backward compatibility. A ton of tests depended on this behavior.
  772. } else {
  773. request = naming.normalizePackageName(
  774. extendName,
  775. "eslint-config"
  776. );
  777. }
  778. let filePath;
  779. try {
  780. filePath = resolver.resolve(request, relativeTo);
  781. } catch (error) {
  782. /* istanbul ignore else */
  783. if (error && error.code === "MODULE_NOT_FOUND") {
  784. throw configMissingError(extendName, ctx.filePath);
  785. }
  786. throw error;
  787. }
  788. writeDebugLogForLoading(request, relativeTo, filePath);
  789. return this._loadConfigData({
  790. ...ctx,
  791. filePath,
  792. name: `${ctx.name} » ${request}`
  793. });
  794. }
  795. /**
  796. * Load given plugins.
  797. * @param {string[]} names The plugin names to load.
  798. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  799. * @returns {Record<string,DependentPlugin>} The loaded parser.
  800. * @private
  801. */
  802. _loadPlugins(names, ctx) {
  803. return names.reduce((map, name) => {
  804. if (isFilePath(name)) {
  805. throw new Error("Plugins array cannot includes file paths.");
  806. }
  807. const plugin = this._loadPlugin(name, ctx);
  808. map[plugin.id] = plugin;
  809. return map;
  810. }, {});
  811. }
  812. /**
  813. * Load a given parser.
  814. * @param {string} nameOrPath The package name or the path to a parser file.
  815. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  816. * @returns {DependentParser} The loaded parser.
  817. */
  818. _loadParser(nameOrPath, ctx) {
  819. debug("Loading parser %j from %s", nameOrPath, ctx.filePath);
  820. const { cwd } = internalSlotsMap.get(this);
  821. const relativeTo = ctx.filePath || path.join(cwd, "__placeholder__.js");
  822. try {
  823. const filePath = ModuleResolver.resolve(nameOrPath, relativeTo);
  824. writeDebugLogForLoading(nameOrPath, relativeTo, filePath);
  825. return new ConfigDependency({
  826. definition: require(filePath),
  827. filePath,
  828. id: nameOrPath,
  829. importerName: ctx.name,
  830. importerPath: ctx.filePath
  831. });
  832. } catch (error) {
  833. // If the parser name is "espree", load the espree of ESLint.
  834. if (nameOrPath === "espree") {
  835. debug("Fallback espree.");
  836. return new ConfigDependency({
  837. definition: require("espree"),
  838. filePath: require.resolve("espree"),
  839. id: nameOrPath,
  840. importerName: ctx.name,
  841. importerPath: ctx.filePath
  842. });
  843. }
  844. debug("Failed to load parser '%s' declared in '%s'.", nameOrPath, ctx.name);
  845. error.message = `Failed to load parser '${nameOrPath}' declared in '${ctx.name}': ${error.message}`;
  846. return new ConfigDependency({
  847. error,
  848. id: nameOrPath,
  849. importerName: ctx.name,
  850. importerPath: ctx.filePath
  851. });
  852. }
  853. }
  854. /**
  855. * Load a given plugin.
  856. * @param {string} name The plugin name to load.
  857. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  858. * @returns {DependentPlugin} The loaded plugin.
  859. * @private
  860. */
  861. _loadPlugin(name, ctx) {
  862. debug("Loading plugin %j from %s", name, ctx.filePath);
  863. const { additionalPluginPool } = internalSlotsMap.get(this);
  864. const request = naming.normalizePackageName(name, "eslint-plugin");
  865. const id = naming.getShorthandName(request, "eslint-plugin");
  866. const relativeTo = path.join(ctx.pluginBasePath, "__placeholder__.js");
  867. if (name.match(/\s+/u)) {
  868. const error = Object.assign(
  869. new Error(`Whitespace found in plugin name '${name}'`),
  870. {
  871. messageTemplate: "whitespace-found",
  872. messageData: { pluginName: request }
  873. }
  874. );
  875. return new ConfigDependency({
  876. error,
  877. id,
  878. importerName: ctx.name,
  879. importerPath: ctx.filePath
  880. });
  881. }
  882. // Check for additional pool.
  883. const plugin =
  884. additionalPluginPool.get(request) ||
  885. additionalPluginPool.get(id);
  886. if (plugin) {
  887. return new ConfigDependency({
  888. definition: normalizePlugin(plugin),
  889. filePath: "", // It's unknown where the plugin came from.
  890. id,
  891. importerName: ctx.name,
  892. importerPath: ctx.filePath
  893. });
  894. }
  895. let filePath;
  896. let error;
  897. try {
  898. filePath = ModuleResolver.resolve(request, relativeTo);
  899. } catch (resolveError) {
  900. error = resolveError;
  901. /* istanbul ignore else */
  902. if (error && error.code === "MODULE_NOT_FOUND") {
  903. error.messageTemplate = "plugin-missing";
  904. error.messageData = {
  905. pluginName: request,
  906. resolvePluginsRelativeTo: ctx.pluginBasePath,
  907. importerName: ctx.name
  908. };
  909. }
  910. }
  911. if (filePath) {
  912. try {
  913. writeDebugLogForLoading(request, relativeTo, filePath);
  914. const startTime = Date.now();
  915. const pluginDefinition = require(filePath);
  916. debug(`Plugin ${filePath} loaded in: ${Date.now() - startTime}ms`);
  917. return new ConfigDependency({
  918. definition: normalizePlugin(pluginDefinition),
  919. filePath,
  920. id,
  921. importerName: ctx.name,
  922. importerPath: ctx.filePath
  923. });
  924. } catch (loadError) {
  925. error = loadError;
  926. }
  927. }
  928. debug("Failed to load plugin '%s' declared in '%s'.", name, ctx.name);
  929. error.message = `Failed to load plugin '${name}' declared in '${ctx.name}': ${error.message}`;
  930. return new ConfigDependency({
  931. error,
  932. id,
  933. importerName: ctx.name,
  934. importerPath: ctx.filePath
  935. });
  936. }
  937. /**
  938. * Take file expression processors as config array elements.
  939. * @param {Record<string,DependentPlugin>} plugins The plugin definitions.
  940. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  941. * @returns {IterableIterator<ConfigArrayElement>} The config array elements of file expression processors.
  942. * @private
  943. */
  944. *_takeFileExtensionProcessors(plugins, ctx) {
  945. for (const pluginId of Object.keys(plugins)) {
  946. const processors =
  947. plugins[pluginId] &&
  948. plugins[pluginId].definition &&
  949. plugins[pluginId].definition.processors;
  950. if (!processors) {
  951. continue;
  952. }
  953. for (const processorId of Object.keys(processors)) {
  954. if (processorId.startsWith(".")) {
  955. yield* this._normalizeObjectConfigData(
  956. {
  957. files: [`*${processorId}`],
  958. processor: `${pluginId}/${processorId}`
  959. },
  960. {
  961. ...ctx,
  962. type: "implicit-processor",
  963. name: `${ctx.name}#processors["${pluginId}/${processorId}"]`
  964. }
  965. );
  966. }
  967. }
  968. }
  969. }
  970. }
  971. module.exports = { ConfigArrayFactory, createContext };