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