config-array-factory.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  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. * @param {string} messageTemplate The text template to source error strings from.
  257. * @returns {Error} The error object to throw
  258. * @private
  259. */
  260. function configInvalidError(configName, importerName, messageTemplate) {
  261. return Object.assign(
  262. new Error(`Failed to load config "${configName}" to extend from.`),
  263. {
  264. messageTemplate,
  265. messageData: { configName, importerName }
  266. }
  267. );
  268. }
  269. /**
  270. * Loads a configuration file regardless of the source. Inspects the file path
  271. * to determine the correctly way to load the config file.
  272. * @param {string} filePath The path to the configuration.
  273. * @returns {ConfigData|null} The configuration information.
  274. * @private
  275. */
  276. function loadConfigFile(filePath) {
  277. switch (path.extname(filePath)) {
  278. case ".js":
  279. case ".cjs":
  280. return loadJSConfigFile(filePath);
  281. case ".json":
  282. if (path.basename(filePath) === "package.json") {
  283. return loadPackageJSONConfigFile(filePath);
  284. }
  285. return loadJSONConfigFile(filePath);
  286. case ".yaml":
  287. case ".yml":
  288. return loadYAMLConfigFile(filePath);
  289. default:
  290. return loadLegacyConfigFile(filePath);
  291. }
  292. }
  293. /**
  294. * Write debug log.
  295. * @param {string} request The requested module name.
  296. * @param {string} relativeTo The file path to resolve the request relative to.
  297. * @param {string} filePath The resolved file path.
  298. * @returns {void}
  299. */
  300. function writeDebugLogForLoading(request, relativeTo, filePath) {
  301. /* istanbul ignore next */
  302. if (debug.enabled) {
  303. let nameAndVersion = null;
  304. try {
  305. const packageJsonPath = ModuleResolver.resolve(
  306. `${request}/package.json`,
  307. relativeTo
  308. );
  309. const { version = "unknown" } = require(packageJsonPath);
  310. nameAndVersion = `${request}@${version}`;
  311. } catch (error) {
  312. debug("package.json was not found:", error.message);
  313. nameAndVersion = request;
  314. }
  315. debug("Loaded: %s (%s)", nameAndVersion, filePath);
  316. }
  317. }
  318. /**
  319. * Create a new context with default values.
  320. * @param {ConfigArrayFactoryInternalSlots} slots The internal slots.
  321. * @param {"config" | "ignore" | "implicit-processor" | undefined} providedType The type of the current configuration. Default is `"config"`.
  322. * @param {string | undefined} providedName The name of the current configuration. Default is the relative path from `cwd` to `filePath`.
  323. * @param {string | undefined} providedFilePath The path to the current configuration. Default is empty string.
  324. * @param {string | undefined} providedMatchBasePath The type of the current configuration. Default is the directory of `filePath` or `cwd`.
  325. * @returns {ConfigArrayFactoryLoadingContext} The created context.
  326. */
  327. function createContext(
  328. { cwd, resolvePluginsRelativeTo },
  329. providedType,
  330. providedName,
  331. providedFilePath,
  332. providedMatchBasePath
  333. ) {
  334. const filePath = providedFilePath
  335. ? path.resolve(cwd, providedFilePath)
  336. : "";
  337. const matchBasePath =
  338. (providedMatchBasePath && path.resolve(cwd, providedMatchBasePath)) ||
  339. (filePath && path.dirname(filePath)) ||
  340. cwd;
  341. const name =
  342. providedName ||
  343. (filePath && path.relative(cwd, filePath)) ||
  344. "";
  345. const pluginBasePath =
  346. resolvePluginsRelativeTo ||
  347. (filePath && path.dirname(filePath)) ||
  348. cwd;
  349. const type = providedType || "config";
  350. return { filePath, matchBasePath, name, pluginBasePath, type };
  351. }
  352. /**
  353. * Normalize a given plugin.
  354. * - Ensure the object to have four properties: configs, environments, processors, and rules.
  355. * - Ensure the object to not have other properties.
  356. * @param {Plugin} plugin The plugin to normalize.
  357. * @returns {Plugin} The normalized plugin.
  358. */
  359. function normalizePlugin(plugin) {
  360. return {
  361. configs: plugin.configs || {},
  362. environments: plugin.environments || {},
  363. processors: plugin.processors || {},
  364. rules: plugin.rules || {}
  365. };
  366. }
  367. //------------------------------------------------------------------------------
  368. // Public Interface
  369. //------------------------------------------------------------------------------
  370. /**
  371. * The factory of `ConfigArray` objects.
  372. */
  373. class ConfigArrayFactory {
  374. /**
  375. * Initialize this instance.
  376. * @param {ConfigArrayFactoryOptions} [options] The map for additional plugins.
  377. */
  378. constructor({
  379. additionalPluginPool = new Map(),
  380. cwd = process.cwd(),
  381. resolvePluginsRelativeTo,
  382. builtInRules,
  383. resolver = ModuleResolver,
  384. eslintAllPath,
  385. eslintRecommendedPath
  386. } = {}) {
  387. internalSlotsMap.set(this, {
  388. additionalPluginPool,
  389. cwd,
  390. resolvePluginsRelativeTo:
  391. resolvePluginsRelativeTo &&
  392. path.resolve(cwd, resolvePluginsRelativeTo),
  393. builtInRules,
  394. resolver,
  395. eslintAllPath,
  396. eslintRecommendedPath
  397. });
  398. }
  399. /**
  400. * Create `ConfigArray` instance from a config data.
  401. * @param {ConfigData|null} configData The config data to create.
  402. * @param {Object} [options] The options.
  403. * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
  404. * @param {string} [options.filePath] The path to this config data.
  405. * @param {string} [options.name] The config name.
  406. * @returns {ConfigArray} Loaded config.
  407. */
  408. create(configData, { basePath, filePath, name } = {}) {
  409. if (!configData) {
  410. return new ConfigArray();
  411. }
  412. const slots = internalSlotsMap.get(this);
  413. const ctx = createContext(slots, "config", name, filePath, basePath);
  414. const elements = this._normalizeConfigData(configData, ctx);
  415. return new ConfigArray(...elements);
  416. }
  417. /**
  418. * Load a config file.
  419. * @param {string} filePath The path to a config file.
  420. * @param {Object} [options] The options.
  421. * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
  422. * @param {string} [options.name] The config name.
  423. * @returns {ConfigArray} Loaded config.
  424. */
  425. loadFile(filePath, { basePath, name } = {}) {
  426. const slots = internalSlotsMap.get(this);
  427. const ctx = createContext(slots, "config", name, filePath, basePath);
  428. return new ConfigArray(...this._loadConfigData(ctx));
  429. }
  430. /**
  431. * Load the config file on a given directory if exists.
  432. * @param {string} directoryPath The path to a directory.
  433. * @param {Object} [options] The options.
  434. * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
  435. * @param {string} [options.name] The config name.
  436. * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
  437. */
  438. loadInDirectory(directoryPath, { basePath, name } = {}) {
  439. const slots = internalSlotsMap.get(this);
  440. for (const filename of configFilenames) {
  441. const ctx = createContext(
  442. slots,
  443. "config",
  444. name,
  445. path.join(directoryPath, filename),
  446. basePath
  447. );
  448. if (fs.existsSync(ctx.filePath)) {
  449. let configData;
  450. try {
  451. configData = loadConfigFile(ctx.filePath);
  452. } catch (error) {
  453. if (!error || error.code !== "ESLINT_CONFIG_FIELD_NOT_FOUND") {
  454. throw error;
  455. }
  456. }
  457. if (configData) {
  458. debug(`Config file found: ${ctx.filePath}`);
  459. return new ConfigArray(
  460. ...this._normalizeConfigData(configData, ctx)
  461. );
  462. }
  463. }
  464. }
  465. debug(`Config file not found on ${directoryPath}`);
  466. return new ConfigArray();
  467. }
  468. /**
  469. * Check if a config file on a given directory exists or not.
  470. * @param {string} directoryPath The path to a directory.
  471. * @returns {string | null} The path to the found config file. If not found then null.
  472. */
  473. static getPathToConfigFileInDirectory(directoryPath) {
  474. for (const filename of configFilenames) {
  475. const filePath = path.join(directoryPath, filename);
  476. if (fs.existsSync(filePath)) {
  477. if (filename === "package.json") {
  478. try {
  479. loadPackageJSONConfigFile(filePath);
  480. return filePath;
  481. } catch { /* ignore */ }
  482. } else {
  483. return filePath;
  484. }
  485. }
  486. }
  487. return null;
  488. }
  489. /**
  490. * Load `.eslintignore` file.
  491. * @param {string} filePath The path to a `.eslintignore` file to load.
  492. * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
  493. */
  494. loadESLintIgnore(filePath) {
  495. const slots = internalSlotsMap.get(this);
  496. const ctx = createContext(
  497. slots,
  498. "ignore",
  499. void 0,
  500. filePath,
  501. slots.cwd
  502. );
  503. const ignorePatterns = loadESLintIgnoreFile(ctx.filePath);
  504. return new ConfigArray(
  505. ...this._normalizeESLintIgnoreData(ignorePatterns, ctx)
  506. );
  507. }
  508. /**
  509. * Load `.eslintignore` file in the current working directory.
  510. * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
  511. */
  512. loadDefaultESLintIgnore() {
  513. const slots = internalSlotsMap.get(this);
  514. const eslintIgnorePath = path.resolve(slots.cwd, ".eslintignore");
  515. const packageJsonPath = path.resolve(slots.cwd, "package.json");
  516. if (fs.existsSync(eslintIgnorePath)) {
  517. return this.loadESLintIgnore(eslintIgnorePath);
  518. }
  519. if (fs.existsSync(packageJsonPath)) {
  520. const data = loadJSONConfigFile(packageJsonPath);
  521. if (Object.hasOwnProperty.call(data, "eslintIgnore")) {
  522. if (!Array.isArray(data.eslintIgnore)) {
  523. throw new Error("Package.json eslintIgnore property requires an array of paths");
  524. }
  525. const ctx = createContext(
  526. slots,
  527. "ignore",
  528. "eslintIgnore in package.json",
  529. packageJsonPath,
  530. slots.cwd
  531. );
  532. return new ConfigArray(
  533. ...this._normalizeESLintIgnoreData(data.eslintIgnore, ctx)
  534. );
  535. }
  536. }
  537. return new ConfigArray();
  538. }
  539. /**
  540. * Load a given config file.
  541. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  542. * @returns {IterableIterator<ConfigArrayElement>} Loaded config.
  543. * @private
  544. */
  545. _loadConfigData(ctx) {
  546. return this._normalizeConfigData(loadConfigFile(ctx.filePath), ctx);
  547. }
  548. /**
  549. * Normalize a given `.eslintignore` data to config array elements.
  550. * @param {string[]} ignorePatterns The patterns to ignore files.
  551. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  552. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  553. * @private
  554. */
  555. *_normalizeESLintIgnoreData(ignorePatterns, ctx) {
  556. const elements = this._normalizeObjectConfigData(
  557. { ignorePatterns },
  558. ctx
  559. );
  560. // Set `ignorePattern.loose` flag for backward compatibility.
  561. for (const element of elements) {
  562. if (element.ignorePattern) {
  563. element.ignorePattern.loose = true;
  564. }
  565. yield element;
  566. }
  567. }
  568. /**
  569. * Normalize a given config to an array.
  570. * @param {ConfigData} configData The config data to normalize.
  571. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  572. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  573. * @private
  574. */
  575. _normalizeConfigData(configData, ctx) {
  576. const validator = new ConfigValidator();
  577. validator.validateConfigSchema(configData, ctx.name || ctx.filePath);
  578. return this._normalizeObjectConfigData(configData, ctx);
  579. }
  580. /**
  581. * Normalize a given config to an array.
  582. * @param {ConfigData|OverrideConfigData} configData The config data to normalize.
  583. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  584. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  585. * @private
  586. */
  587. *_normalizeObjectConfigData(configData, ctx) {
  588. const { files, excludedFiles, ...configBody } = configData;
  589. const criteria = OverrideTester.create(
  590. files,
  591. excludedFiles,
  592. ctx.matchBasePath
  593. );
  594. const elements = this._normalizeObjectConfigDataBody(configBody, ctx);
  595. // Apply the criteria to every element.
  596. for (const element of elements) {
  597. /*
  598. * Merge the criteria.
  599. * This is for the `overrides` entries that came from the
  600. * configurations of `overrides[].extends`.
  601. */
  602. element.criteria = OverrideTester.and(criteria, element.criteria);
  603. /*
  604. * Remove `root` property to ignore `root` settings which came from
  605. * `extends` in `overrides`.
  606. */
  607. if (element.criteria) {
  608. element.root = void 0;
  609. }
  610. yield element;
  611. }
  612. }
  613. /**
  614. * Normalize a given config to an array.
  615. * @param {ConfigData} configData The config data to normalize.
  616. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  617. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  618. * @private
  619. */
  620. *_normalizeObjectConfigDataBody(
  621. {
  622. env,
  623. extends: extend,
  624. globals,
  625. ignorePatterns,
  626. noInlineConfig,
  627. parser: parserName,
  628. parserOptions,
  629. plugins: pluginList,
  630. processor,
  631. reportUnusedDisableDirectives,
  632. root,
  633. rules,
  634. settings,
  635. overrides: overrideList = []
  636. },
  637. ctx
  638. ) {
  639. const extendList = Array.isArray(extend) ? extend : [extend];
  640. const ignorePattern = ignorePatterns && new IgnorePattern(
  641. Array.isArray(ignorePatterns) ? ignorePatterns : [ignorePatterns],
  642. ctx.matchBasePath
  643. );
  644. // Flatten `extends`.
  645. for (const extendName of extendList.filter(Boolean)) {
  646. yield* this._loadExtends(extendName, ctx);
  647. }
  648. // Load parser & plugins.
  649. const parser = parserName && this._loadParser(parserName, ctx);
  650. const plugins = pluginList && this._loadPlugins(pluginList, ctx);
  651. // Yield pseudo config data for file extension processors.
  652. if (plugins) {
  653. yield* this._takeFileExtensionProcessors(plugins, ctx);
  654. }
  655. // Yield the config data except `extends` and `overrides`.
  656. yield {
  657. // Debug information.
  658. type: ctx.type,
  659. name: ctx.name,
  660. filePath: ctx.filePath,
  661. // Config data.
  662. criteria: null,
  663. env,
  664. globals,
  665. ignorePattern,
  666. noInlineConfig,
  667. parser,
  668. parserOptions,
  669. plugins,
  670. processor,
  671. reportUnusedDisableDirectives,
  672. root,
  673. rules,
  674. settings
  675. };
  676. // Flatten `overries`.
  677. for (let i = 0; i < overrideList.length; ++i) {
  678. yield* this._normalizeObjectConfigData(
  679. overrideList[i],
  680. { ...ctx, name: `${ctx.name}#overrides[${i}]` }
  681. );
  682. }
  683. }
  684. /**
  685. * Load configs of an element in `extends`.
  686. * @param {string} extendName The name of a base config.
  687. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  688. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  689. * @private
  690. */
  691. _loadExtends(extendName, ctx) {
  692. debug("Loading {extends:%j} relative to %s", extendName, ctx.filePath);
  693. try {
  694. if (extendName.startsWith("eslint:")) {
  695. return this._loadExtendedBuiltInConfig(extendName, ctx);
  696. }
  697. if (extendName.startsWith("plugin:")) {
  698. return this._loadExtendedPluginConfig(extendName, ctx);
  699. }
  700. return this._loadExtendedShareableConfig(extendName, ctx);
  701. } catch (error) {
  702. error.message += `\nReferenced from: ${ctx.filePath || ctx.name}`;
  703. throw error;
  704. }
  705. }
  706. /**
  707. * Load configs of an element in `extends`.
  708. * @param {string} extendName The name of a base config.
  709. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  710. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  711. * @private
  712. */
  713. _loadExtendedBuiltInConfig(extendName, ctx) {
  714. const { eslintAllPath, eslintRecommendedPath } = internalSlotsMap.get(this);
  715. if (extendName === "eslint:recommended") {
  716. return this._loadConfigData({
  717. ...ctx,
  718. filePath: eslintRecommendedPath,
  719. name: `${ctx.name} » ${extendName}`
  720. });
  721. }
  722. if (extendName === "eslint:all") {
  723. return this._loadConfigData({
  724. ...ctx,
  725. filePath: eslintAllPath,
  726. name: `${ctx.name} » ${extendName}`
  727. });
  728. }
  729. throw configInvalidError(extendName, ctx.name, "extend-config-missing");
  730. }
  731. /**
  732. * Load configs of an element in `extends`.
  733. * @param {string} extendName The name of a base config.
  734. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  735. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  736. * @private
  737. */
  738. _loadExtendedPluginConfig(extendName, ctx) {
  739. const slashIndex = extendName.lastIndexOf("/");
  740. if (slashIndex === -1) {
  741. throw configInvalidError(extendName, ctx.filePath, "plugin-invalid");
  742. }
  743. const pluginName = extendName.slice("plugin:".length, slashIndex);
  744. const configName = extendName.slice(slashIndex + 1);
  745. if (isFilePath(pluginName)) {
  746. throw new Error("'extends' cannot use a file path for plugins.");
  747. }
  748. const plugin = this._loadPlugin(pluginName, ctx);
  749. const configData =
  750. plugin.definition &&
  751. plugin.definition.configs[configName];
  752. if (configData) {
  753. return this._normalizeConfigData(configData, {
  754. ...ctx,
  755. filePath: plugin.filePath || ctx.filePath,
  756. name: `${ctx.name} » plugin:${plugin.id}/${configName}`
  757. });
  758. }
  759. throw plugin.error || configInvalidError(extendName, ctx.filePath, "extend-config-missing");
  760. }
  761. /**
  762. * Load configs of an element in `extends`.
  763. * @param {string} extendName The name of a base config.
  764. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  765. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  766. * @private
  767. */
  768. _loadExtendedShareableConfig(extendName, ctx) {
  769. const { cwd, resolver } = internalSlotsMap.get(this);
  770. const relativeTo = ctx.filePath || path.join(cwd, "__placeholder__.js");
  771. let request;
  772. if (isFilePath(extendName)) {
  773. request = extendName;
  774. } else if (extendName.startsWith(".")) {
  775. request = `./${extendName}`; // For backward compatibility. A ton of tests depended on this behavior.
  776. } else {
  777. request = naming.normalizePackageName(
  778. extendName,
  779. "eslint-config"
  780. );
  781. }
  782. let filePath;
  783. try {
  784. filePath = resolver.resolve(request, relativeTo);
  785. } catch (error) {
  786. /* istanbul ignore else */
  787. if (error && error.code === "MODULE_NOT_FOUND") {
  788. throw configInvalidError(extendName, ctx.filePath, "extend-config-missing");
  789. }
  790. throw error;
  791. }
  792. writeDebugLogForLoading(request, relativeTo, filePath);
  793. return this._loadConfigData({
  794. ...ctx,
  795. filePath,
  796. name: `${ctx.name} » ${request}`
  797. });
  798. }
  799. /**
  800. * Load given plugins.
  801. * @param {string[]} names The plugin names to load.
  802. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  803. * @returns {Record<string,DependentPlugin>} The loaded parser.
  804. * @private
  805. */
  806. _loadPlugins(names, ctx) {
  807. return names.reduce((map, name) => {
  808. if (isFilePath(name)) {
  809. throw new Error("Plugins array cannot includes file paths.");
  810. }
  811. const plugin = this._loadPlugin(name, ctx);
  812. map[plugin.id] = plugin;
  813. return map;
  814. }, {});
  815. }
  816. /**
  817. * Load a given parser.
  818. * @param {string} nameOrPath The package name or the path to a parser file.
  819. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  820. * @returns {DependentParser} The loaded parser.
  821. */
  822. _loadParser(nameOrPath, ctx) {
  823. debug("Loading parser %j from %s", nameOrPath, ctx.filePath);
  824. const { cwd } = internalSlotsMap.get(this);
  825. const relativeTo = ctx.filePath || path.join(cwd, "__placeholder__.js");
  826. try {
  827. const filePath = ModuleResolver.resolve(nameOrPath, relativeTo);
  828. writeDebugLogForLoading(nameOrPath, relativeTo, filePath);
  829. return new ConfigDependency({
  830. definition: require(filePath),
  831. filePath,
  832. id: nameOrPath,
  833. importerName: ctx.name,
  834. importerPath: ctx.filePath
  835. });
  836. } catch (error) {
  837. // If the parser name is "espree", load the espree of ESLint.
  838. if (nameOrPath === "espree") {
  839. debug("Fallback espree.");
  840. return new ConfigDependency({
  841. definition: require("espree"),
  842. filePath: require.resolve("espree"),
  843. id: nameOrPath,
  844. importerName: ctx.name,
  845. importerPath: ctx.filePath
  846. });
  847. }
  848. debug("Failed to load parser '%s' declared in '%s'.", nameOrPath, ctx.name);
  849. error.message = `Failed to load parser '${nameOrPath}' declared in '${ctx.name}': ${error.message}`;
  850. return new ConfigDependency({
  851. error,
  852. id: nameOrPath,
  853. importerName: ctx.name,
  854. importerPath: ctx.filePath
  855. });
  856. }
  857. }
  858. /**
  859. * Load a given plugin.
  860. * @param {string} name The plugin name to load.
  861. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  862. * @returns {DependentPlugin} The loaded plugin.
  863. * @private
  864. */
  865. _loadPlugin(name, ctx) {
  866. debug("Loading plugin %j from %s", name, ctx.filePath);
  867. const { additionalPluginPool } = internalSlotsMap.get(this);
  868. const request = naming.normalizePackageName(name, "eslint-plugin");
  869. const id = naming.getShorthandName(request, "eslint-plugin");
  870. const relativeTo = path.join(ctx.pluginBasePath, "__placeholder__.js");
  871. if (name.match(/\s+/u)) {
  872. const error = Object.assign(
  873. new Error(`Whitespace found in plugin name '${name}'`),
  874. {
  875. messageTemplate: "whitespace-found",
  876. messageData: { pluginName: request }
  877. }
  878. );
  879. return new ConfigDependency({
  880. error,
  881. id,
  882. importerName: ctx.name,
  883. importerPath: ctx.filePath
  884. });
  885. }
  886. // Check for additional pool.
  887. const plugin =
  888. additionalPluginPool.get(request) ||
  889. additionalPluginPool.get(id);
  890. if (plugin) {
  891. return new ConfigDependency({
  892. definition: normalizePlugin(plugin),
  893. filePath: "", // It's unknown where the plugin came from.
  894. id,
  895. importerName: ctx.name,
  896. importerPath: ctx.filePath
  897. });
  898. }
  899. let filePath;
  900. let error;
  901. try {
  902. filePath = ModuleResolver.resolve(request, relativeTo);
  903. } catch (resolveError) {
  904. error = resolveError;
  905. /* istanbul ignore else */
  906. if (error && error.code === "MODULE_NOT_FOUND") {
  907. error.messageTemplate = "plugin-missing";
  908. error.messageData = {
  909. pluginName: request,
  910. resolvePluginsRelativeTo: ctx.pluginBasePath,
  911. importerName: ctx.name
  912. };
  913. }
  914. }
  915. if (filePath) {
  916. try {
  917. writeDebugLogForLoading(request, relativeTo, filePath);
  918. const startTime = Date.now();
  919. const pluginDefinition = require(filePath);
  920. debug(`Plugin ${filePath} loaded in: ${Date.now() - startTime}ms`);
  921. return new ConfigDependency({
  922. definition: normalizePlugin(pluginDefinition),
  923. filePath,
  924. id,
  925. importerName: ctx.name,
  926. importerPath: ctx.filePath
  927. });
  928. } catch (loadError) {
  929. error = loadError;
  930. }
  931. }
  932. debug("Failed to load plugin '%s' declared in '%s'.", name, ctx.name);
  933. error.message = `Failed to load plugin '${name}' declared in '${ctx.name}': ${error.message}`;
  934. return new ConfigDependency({
  935. error,
  936. id,
  937. importerName: ctx.name,
  938. importerPath: ctx.filePath
  939. });
  940. }
  941. /**
  942. * Take file expression processors as config array elements.
  943. * @param {Record<string,DependentPlugin>} plugins The plugin definitions.
  944. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  945. * @returns {IterableIterator<ConfigArrayElement>} The config array elements of file expression processors.
  946. * @private
  947. */
  948. *_takeFileExtensionProcessors(plugins, ctx) {
  949. for (const pluginId of Object.keys(plugins)) {
  950. const processors =
  951. plugins[pluginId] &&
  952. plugins[pluginId].definition &&
  953. plugins[pluginId].definition.processors;
  954. if (!processors) {
  955. continue;
  956. }
  957. for (const processorId of Object.keys(processors)) {
  958. if (processorId.startsWith(".")) {
  959. yield* this._normalizeObjectConfigData(
  960. {
  961. files: [`*${processorId}`],
  962. processor: `${pluginId}/${processorId}`
  963. },
  964. {
  965. ...ctx,
  966. type: "implicit-processor",
  967. name: `${ctx.name}#processors["${pluginId}/${processorId}"]`
  968. }
  969. );
  970. }
  971. }
  972. }
  973. }
  974. }
  975. module.exports = { ConfigArrayFactory, createContext };