+ const relativePath = path__default["default"].relative(this.basePath, filePath);
+
+ return this.patterns.every(({ includes, excludes }) => (
+ (!includes || includes.some(m => m.match(relativePath))) &&
+ (!excludes || !excludes.some(m => m.match(relativePath)))
+ ));
+ }
+
+ // eslint-disable-next-line jsdoc/require-description
+ /**
+ * @returns {Object} a JSON compatible object.
+ */
+ toJSON() {
+ if (this.patterns.length === 1) {
+ return {
+ ...patternToJson(this.patterns[0]),
+ basePath: this.basePath
+ };
+ }
+ return {
+ AND: this.patterns.map(patternToJson),
+ basePath: this.basePath
+ };
+ }
+
+ // eslint-disable-next-line jsdoc/require-description
+ /**
+ * @returns {Object} an object to display by `console.log()`.
+ */
+ [util__default["default"].inspect.custom]() {
+ return this.toJSON();
+ }
+}
+
+/**
+ * @fileoverview `ConfigArray` class.
+ * @author Toru Nagashima <https://github.com/mysticatea>
+ */
+
+/**
+ * @fileoverview Config file operations. This file must be usable in the browser,
+ * so no Node-specific code can be here.
+ * @author Nicholas C. Zakas
+ */
+
+//------------------------------------------------------------------------------
+// Private
+//------------------------------------------------------------------------------
+
+const RULE_SEVERITY_STRINGS = ["off", "warn", "error"],
+ RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => {
+ map[value] = index;
+ return map;
+ }, {}),
+ VALID_SEVERITIES = [0, 1, 2, "off", "warn", "error"];
+
+//------------------------------------------------------------------------------
+// Public Interface
+//------------------------------------------------------------------------------
+
+/**
+ * Normalizes the severity value of a rule's configuration to a number
+ * @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally
+ * received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0),
+ * the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array
+ * whose first element is one of the above values. Strings are matched case-insensitively.
+ * @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0.
+ */
+function getRuleSeverity(ruleConfig) {
+ const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
+
+ if (severityValue === 0 || severityValue === 1 || severityValue === 2) {
+ return severityValue;
+ }
+
+ if (typeof severityValue === "string") {
+ return RULE_SEVERITY[severityValue.toLowerCase()] || 0;
+ }
+
+ return 0;
+}
+
+/**
+ * Converts old-style severity settings (0, 1, 2) into new-style
+ * severity settings (off, warn, error) for all rules. Assumption is that severity
+ * values have already been validated as correct.
+ * @param {Object} config The config object to normalize.
+ * @returns {void}
+ */
+function normalizeToStrings(config) {
+
+ if (config.rules) {
+ Object.keys(config.rules).forEach(ruleId => {
+ const ruleConfig = config.rules[ruleId];
+
+ if (typeof ruleConfig === "number") {
+ config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0];
+ } else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === "number") {
+ ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0];
+ }
+ });
+ }
+}
+
+/**
+ * Determines if the severity for the given rule configuration represents an error.
+ * @param {int|string|Array} ruleConfig The configuration for an individual rule.
+ * @returns {boolean} True if the rule represents an error, false if not.
+ */
+function isErrorSeverity(ruleConfig) {
+ return getRuleSeverity(ruleConfig) === 2;
+}
+
+/**
+ * Checks whether a given config has valid severity or not.
+ * @param {number|string|Array} ruleConfig The configuration for an individual rule.
+ * @returns {boolean} `true` if the configuration has valid severity.
+ */
+function isValidSeverity(ruleConfig) {
+ let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
+
+ if (typeof severity === "string") {
+ severity = severity.toLowerCase();
+ }
+ return VALID_SEVERITIES.indexOf(severity) !== -1;
+}
+
+/**
+ * Checks whether every rule of a given config has valid severity or not.
+ * @param {Object} config The configuration for rules.
+ * @returns {boolean} `true` if the configuration has valid severity.
+ */
+function isEverySeverityValid(config) {
+ return Object.keys(config).every(ruleId => isValidSeverity(config[ruleId]));
+}
+
+/**
+ * Normalizes a value for a global in a config
+ * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in
+ * a global directive comment
+ * @returns {("readable"|"writeable"|"off")} The value normalized as a string
+ * @throws Error if global value is invalid
+ */
+function normalizeConfigGlobal(configuredValue) {
+ switch (configuredValue) {
+ case "off":
+ return "off";
+
+ case true:
+ case "true":
+ case "writeable":
+ case "writable":
+ return "writable";
+
+ case null:
+ case false:
+ case "false":
+ case "readable":
+ case "readonly":
+ return "readonly";
+
+ default:
+ throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`);
+ }
+}
+
+var ConfigOps = {
+ __proto__: null,
+ getRuleSeverity: getRuleSeverity,
+ normalizeToStrings: normalizeToStrings,
+ isErrorSeverity: isErrorSeverity,
+ isValidSeverity: isValidSeverity,
+ isEverySeverityValid: isEverySeverityValid,
+ normalizeConfigGlobal: normalizeConfigGlobal
+};
+
+/**
+ * @fileoverview Provide the function that emits deprecation warnings.
+ * @author Toru Nagashima <http://github.com/mysticatea>
+ */
+
+//------------------------------------------------------------------------------
+// Private
+//------------------------------------------------------------------------------
+
+// Defitions for deprecation warnings.
+const deprecationWarningMessages = {
+ ESLINT_LEGACY_ECMAFEATURES:
+ "The 'ecmaFeatures' config file property is deprecated and has no effect.",
+ ESLINT_PERSONAL_CONFIG_LOAD:
+ "'~/.eslintrc.*' config files have been deprecated. " +
+ "Please use a config file per project or the '--config' option.",
+ ESLINT_PERSONAL_CONFIG_SUPPRESS:
+ "'~/.eslintrc.*' config files have been deprecated. " +
+ "Please remove it or add 'root:true' to the config files in your " +
+ "projects in order to avoid loading '~/.eslintrc.*' accidentally."
+};
+
+const sourceFileErrorCache = new Set();
+
+/**
+ * Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted
+ * for each unique file path, but repeated invocations with the same file path have no effect.
+ * No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active.
+ * @param {string} source The name of the configuration source to report the warning for.
+ * @param {string} errorCode The warning message to show.
+ * @returns {void}
+ */
+function emitDeprecationWarning(source, errorCode) {
+ const cacheKey = JSON.stringify({ source, errorCode });
+
+ if (sourceFileErrorCache.has(cacheKey)) {
+ return;
+ }
+ sourceFileErrorCache.add(cacheKey);
+
+ const rel = path__default["default"].relative(process.cwd(), source);
+ const message = deprecationWarningMessages[errorCode];
+
+ process.emitWarning(
+ `${message} (found in "${rel}")`,
+ "DeprecationWarning",
+ errorCode
+ );
+}
+
+/**
+ * @fileoverview The instance of Ajv validator.
+ * @author Evgeny Poberezkin
+ */
+
+//-----------------------------------------------------------------------------
+// Helpers
+//-----------------------------------------------------------------------------
+
+/*
+ * Copied from ajv/lib/refs/json-schema-draft-04.json
+ * The MIT License (MIT)
+ * Copyright (c) 2015-2017 Evgeny Poberezkin
+ */
+const metaSchema = {
+ id: "http://json-schema.org/draft-04/schema#",
+ $schema: "http://json-schema.org/draft-04/schema#",
+ description: "Core schema meta-schema",
+ definitions: {
+ schemaArray: {
+ type: "array",
+ minItems: 1,
+ items: { $ref: "#" }
+ },
+ positiveInteger: {
+ type: "integer",
+ minimum: 0
+ },
+ positiveIntegerDefault0: {
+ allOf: [{ $ref: "#/definitions/positiveInteger" }, { default: 0 }]
+ },
+ simpleTypes: {
+ enum: ["array", "boolean", "integer", "null", "number", "object", "string"]
+ },
+ stringArray: {
+ type: "array",
+ items: { type: "string" },
+ minItems: 1,
+ uniqueItems: true
+ }
+ },
+ type: "object",
+ properties: {
+ id: {
+ type: "string"
+ },
+ $schema: {
+ type: "string"
+ },
+ title: {
+ type: "string"
+ },
+ description: {
+ type: "string"
+ },
+ default: { },
+ multipleOf: {
+ type: "number",
+ minimum: 0,
+ exclusiveMinimum: true
+ },
+ maximum: {
+ type: "number"
+ },
+ exclusiveMaximum: {
+ type: "boolean",
+ default: false
+ },
+ minimum: {
+ type: "number"
+ },
+ exclusiveMinimum: {
+ type: "boolean",
+ default: false
+ },
+ maxLength: { $ref: "#/definitions/positiveInteger" },
+ minLength: { $ref: "#/definitions/positiveIntegerDefault0" },
+ pattern: {
+ type: "string",
+ format: "regex"
+ },
+ additionalItems: {
+ anyOf: [
+ { type: "boolean" },
+ { $ref: "#" }
+ ],
+ default: { }
+ },
+ items: {
+ anyOf: [
+ { $ref: "#" },
+ { $ref: "#/definitions/schemaArray" }
+ ],
+ default: { }
+ },
+ maxItems: { $ref: "#/definitions/positiveInteger" },
+ minItems: { $ref: "#/definitions/positiveIntegerDefault0" },
+ uniqueItems: {
+ type: "boolean",
+ default: false
+ },
+ maxProperties: { $ref: "#/definitions/positiveInteger" },
+ minProperties: { $ref: "#/definitions/positiveIntegerDefault0" },
+ required: { $ref: "#/definitions/stringArray" },
+ additionalProperties: {
+ anyOf: [
+ { type: "boolean" },
+ { $ref: "#" }
+ ],
+ default: { }
+ },
+ definitions: {
+ type: "object",
+ additionalProperties: { $ref: "#" },
+ default: { }
+ },
+ properties: {
+ type: "object",
+ additionalProperties: { $ref: "#" },
+ default: { }
+ },
+ patternProperties: {
+ type: "object",
+ additionalProperties: { $ref: "#" },
+ default: { }
+ },
+ dependencies: {
+ type: "object",
+ additionalProperties: {
+ anyOf: [
+ { $ref: "#" },
+ { $ref: "#/definitions/stringArray" }
+ ]
+ }
+ },
+ enum: {
+ type: "array",
+ minItems: 1,
+ uniqueItems: true
+ },
+ type: {
+ anyOf: [
+ { $ref: "#/definitions/simpleTypes" },
+ {
+ type: "array",
+ items: { $ref: "#/definitions/simpleTypes" },
+ minItems: 1,
+ uniqueItems: true
+ }
+ ]
+ },
+ format: { type: "string" },
+ allOf: { $ref: "#/definitions/schemaArray" },
+ anyOf: { $ref: "#/definitions/schemaArray" },
+ oneOf: { $ref: "#/definitions/schemaArray" },
+ not: { $ref: "#" }
+ },
+ dependencies: {
+ exclusiveMaximum: ["maximum"],
+ exclusiveMinimum: ["minimum"]
+ },
+ default: { }
+};
+
+//------------------------------------------------------------------------------
+// Public Interface
+//------------------------------------------------------------------------------
+
+var ajvOrig = (additionalOptions = {}) => {
+ const ajv = new Ajv__default["default"]({
+ meta: false,
+ useDefaults: true,
+ validateSchema: false,
+ missingRefs: "ignore",
+ verbose: true,
+ schemaId: "auto",
+ ...additionalOptions
+ });
+
+ ajv.addMetaSchema(metaSchema);
+ // eslint-disable-next-line no-underscore-dangle
+ ajv._opts.defaultMeta = metaSchema.id;
+
+ return ajv;
+};
+
+/**
+ * @fileoverview Defines a schema for configs.
+ * @author Sylvan Mably
+ */
+
+const baseConfigProperties = {
+ $schema: { type: "string" },
+ env: { type: "object" },
+ extends: { $ref: "#/definitions/stringOrStrings" },
+ globals: { type: "object" },
+ overrides: {
+ type: "array",
+ items: { $ref: "#/definitions/overrideConfig" },
+ additionalItems: false
+ },
+ parser: { type: ["string", "null"] },
+ parserOptions: { type: "object" },
+ plugins: { type: "array" },
+ processor: { type: "string" },
+ rules: { type: "object" },
+ settings: { type: "object" },
+ noInlineConfig: { type: "boolean" },
+ reportUnusedDisableDirectives: { type: "boolean" },
+
+ ecmaFeatures: { type: "object" } // deprecated; logs a warning when used
+};
+
+const configSchema = {
+ definitions: {
+ stringOrStrings: {
+ oneOf: [
+ { type: "string" },
+ {
+ type: "array",
+ items: { type: "string" },
+ additionalItems: false
+ }
+ ]
+ },
+ stringOrStringsRequired: {
+ oneOf: [
+ { type: "string" },
+ {
+ type: "array",
+ items: { type: "string" },
+ additionalItems: false,
+ minItems: 1
+ }
+ ]
+ },
+
+ // Config at top-level.
+ objectConfig: {
+ type: "object",
+ properties: {
+ root: { type: "boolean" },
+ ignorePatterns: { $ref: "#/definitions/stringOrStrings" },
+ ...baseConfigProperties
+ },
+ additionalProperties: false
+ },
+
+ // Config in `overrides`.
+ overrideConfig: {
+ type: "object",
+ properties: {
+ excludedFiles: { $ref: "#/definitions/stringOrStrings" },
+ files: { $ref: "#/definitions/stringOrStringsRequired" },
+ ...baseConfigProperties
+ },
+ required: ["files"],
+ additionalProperties: false
+ }
+ },
+
+ $ref: "#/definitions/objectConfig"
+};
+
+/**
+ * @fileoverview Defines environment settings and globals.
+ * @author Elan Shanker
+ */
+
+//------------------------------------------------------------------------------
+// Helpers
+//------------------------------------------------------------------------------
+
+/**
+ * Get the object that has difference.
+ * @param {Record<string,boolean>} current The newer object.
+ * @param {Record<string,boolean>} prev The older object.
+ * @returns {Record<string,boolean>} The difference object.
+ */
+function getDiff(current, prev) {
+ const retv = {};
+
+ for (const [key, value] of Object.entries(current)) {
+ if (!Object.hasOwnProperty.call(prev, key)) {
+ retv[key] = value;
+ }
+ }
+
+ return retv;
+}
+
+const newGlobals2015 = getDiff(globals__default["default"].es2015, globals__default["default"].es5); // 19 variables such as Promise, Map, ...
+const newGlobals2017 = {
+ Atomics: false,
+ SharedArrayBuffer: false
+};
+const newGlobals2020 = {
+ BigInt: false,
+ BigInt64Array: false,
+ BigUint64Array: false,
+ globalThis: false
+};
+
+const newGlobals2021 = {
+ AggregateError: false,
+ FinalizationRegistry: false,
+ WeakRef: false
+};
+
+//------------------------------------------------------------------------------
+// Public Interface
+//------------------------------------------------------------------------------
+
+/** @type {Map<string, import("../lib/shared/types").Environment>} */
+var environments = new Map(Object.entries({
+
+ // Language
+ builtin: {
+ globals: globals__default["default"].es5
+ },
+ es6: {
+ globals: newGlobals2015,
+ parserOptions: {
+ ecmaVersion: 6
+ }
+ },
+ es2015: {
+ globals: newGlobals2015,
+ parserOptions: {
+ ecmaVersion: 6
+ }
+ },
+ es2016: {
+ globals: newGlobals2015,
+ parserOptions: {
+ ecmaVersion: 7
+ }
+ },
+ es2017: {
+ globals: { ...newGlobals2015, ...newGlobals2017 },
+ parserOptions: {
+ ecmaVersion: 8
+ }
+ },
+ es2018: {
+ globals: { ...newGlobals2015, ...newGlobals2017 },
+ parserOptions: {
+ ecmaVersion: 9
+ }
+ },
+ es2019: {
+ globals: { ...newGlobals2015, ...newGlobals2017 },
+ parserOptions: {
+ ecmaVersion: 10
+ }
+ },
+ es2020: {
+ globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 },
+ parserOptions: {
+ ecmaVersion: 11
+ }
+ },
+ es2021: {
+ globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
+ parserOptions: {
+ ecmaVersion: 12
+ }
+ },
+ es2022: {
+ globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
+ parserOptions: {
+ ecmaVersion: 13
+ }
+ },
+
+ // Platforms
+ browser: {
+ globals: globals__default["default"].browser
+ },
+ node: {
+ globals: globals__default["default"].node,
+ parserOptions: {
+ ecmaFeatures: {
+ globalReturn: true
+ }
+ }
+ },
+ "shared-node-browser": {
+ globals: globals__default["default"]["shared-node-browser"]
+ },
+ worker: {
+ globals: globals__default["default"].worker
+ },
+ serviceworker: {
+ globals: globals__default["default"].serviceworker
+ },
+
+ // Frameworks
+ commonjs: {
+ globals: globals__default["default"].commonjs,
+ parserOptions: {
+ ecmaFeatures: {
+ globalReturn: true
+ }
+ }
+ },
+ amd: {
+ globals: globals__default["default"].amd
+ },
+ mocha: {
+ globals: globals__default["default"].mocha
+ },
+ jasmine: {
+ globals: globals__default["default"].jasmine
+ },
+ jest: {
+ globals: globals__default["default"].jest
+ },
+ phantomjs: {
+ globals: globals__default["default"].phantomjs
+ },
+ jquery: {
+ globals: globals__default["default"].jquery
+ },
+ qunit: {
+ globals: globals__default["default"].qunit
+ },
+ prototypejs: {
+ globals: globals__default["default"].prototypejs
+ },
+ shelljs: {
+ globals: globals__default["default"].shelljs
+ },
+ meteor: {
+ globals: globals__default["default"].meteor
+ },
+ mongo: {
+ globals: globals__default["default"].mongo
+ },
+ protractor: {
+ globals: globals__default["default"].protractor
+ },
+ applescript: {
+ globals: globals__default["default"].applescript
+ },
+ nashorn: {
+ globals: globals__default["default"].nashorn
+ },
+ atomtest: {
+ globals: globals__default["default"].atomtest
+ },
+ embertest: {
+ globals: globals__default["default"].embertest
+ },
+ webextensions: {
+ globals: globals__default["default"].webextensions
+ },
+ greasemonkey: {
+ globals: globals__default["default"].greasemonkey
+ }
+}));
+
+/**
+ * @fileoverview Validates configs.
+ * @author Brandon Mills
+ */
+
+const ajv = ajvOrig();
+
+const ruleValidators = new WeakMap();
+const noop = Function.prototype;
+
+//------------------------------------------------------------------------------
+// Private
+//------------------------------------------------------------------------------
+let validateSchema;
+const severityMap = {
+ error: 2,
+ warn: 1,
+ off: 0
+};
+
+const validated = new WeakSet();
+
+//-----------------------------------------------------------------------------
+// Exports
+//-----------------------------------------------------------------------------
+
+class ConfigValidator {
+ constructor({ builtInRules = new Map() } = {}) {
+ this.builtInRules = builtInRules;
+ }
+
+ /**
+ * Gets a complete options schema for a rule.
+ * @param {{create: Function, schema: (Array|null)}} rule A new-style rule object
+ * @returns {Object} JSON Schema for the rule's options.
+ */
+ getRuleOptionsSchema(rule) {
+ if (!rule) {
+ return null;
+ }
+
+ const schema = rule.schema || rule.meta && rule.meta.schema;
+
+ // Given a tuple of schemas, insert warning level at the beginning
+ if (Array.isArray(schema)) {
+ if (schema.length) {
+ return {
+ type: "array",
+ items: schema,
+ minItems: 0,
+ maxItems: schema.length
+ };
+ }
+ return {
+ type: "array",
+ minItems: 0,
+ maxItems: 0
+ };
+
+ }
+
+ // Given a full schema, leave it alone
+ return schema || null;
+ }
+
+ /**
+ * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.
+ * @param {options} options The given options for the rule.
+ * @returns {number|string} The rule's severity value
+ */
+ validateRuleSeverity(options) {
+ const severity = Array.isArray(options) ? options[0] : options;
+ const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity;
+
+ if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) {
+ return normSeverity;
+ }
+
+ throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util__default["default"].inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`);
+
+ }
+
+ /**
+ * Validates the non-severity options passed to a rule, based on its schema.
+ * @param {{create: Function}} rule The rule to validate
+ * @param {Array} localOptions The options for the rule, excluding severity
+ * @returns {void}
+ */
+ validateRuleSchema(rule, localOptions) {
+ if (!ruleValidators.has(rule)) {
+ const schema = this.getRuleOptionsSchema(rule);
+
+ if (schema) {
+ ruleValidators.set(rule, ajv.compile(schema));
+ }
+ }
+
+ const validateRule = ruleValidators.get(rule);
+
+ if (validateRule) {
+ validateRule(localOptions);
+ if (validateRule.errors) {
+ throw new Error(validateRule.errors.map(
+ error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`
+ ).join(""));
+ }
+ }
+ }
+
+ /**
+ * Validates a rule's options against its schema.
+ * @param {{create: Function}|null} rule The rule that the config is being validated for
+ * @param {string} ruleId The rule's unique name.
+ * @param {Array|number} options The given options for the rule.
+ * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,
+ * no source is prepended to the message.
+ * @returns {void}
+ */
+ validateRuleOptions(rule, ruleId, options, source = null) {
+ try {
+ const severity = this.validateRuleSeverity(options);
+
+ if (severity !== 0) {
+ this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);
+ }
+ } catch (err) {
+ const enhancedMessage = `Configuration for rule "${ruleId}" is invalid:\n${err.message}`;
+
+ if (typeof source === "string") {
+ throw new Error(`${source}:\n\t${enhancedMessage}`);
+ } else {
+ throw new Error(enhancedMessage);
+ }
+ }
+ }
+
+ /**
+ * Validates an environment object
+ * @param {Object} environment The environment config object to validate.
+ * @param {string} source The name of the configuration source to report in any errors.
+ * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded environments.
+ * @returns {void}
+ */
+ validateEnvironment(
+ environment,
+ source,
+ getAdditionalEnv = noop
+ ) {
+
+ // not having an environment is ok
+ if (!environment) {
+ return;
+ }
+
+ Object.keys(environment).forEach(id => {
+ const env = getAdditionalEnv(id) || environments.get(id) || null;
+
+ if (!env) {
+ const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`;
+
+ throw new Error(message);
+ }
+ });
+ }
+
+ /**
+ * Validates a rules config object
+ * @param {Object} rulesConfig The rules config object to validate.
+ * @param {string} source The name of the configuration source to report in any errors.
+ * @param {function(ruleId:string): Object} getAdditionalRule A map from strings to loaded rules
+ * @returns {void}
+ */
+ validateRules(
+ rulesConfig,
+ source,
+ getAdditionalRule = noop
+ ) {
+ if (!rulesConfig) {
+ return;
+ }
+
+ Object.keys(rulesConfig).forEach(id => {
+ const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null;
+
+ this.validateRuleOptions(rule, id, rulesConfig[id], source);
+ });
+ }
+
+ /**
+ * Validates a `globals` section of a config file
+ * @param {Object} globalsConfig The `globals` section
+ * @param {string|null} source The name of the configuration source to report in the event of an error.
+ * @returns {void}
+ */
+ validateGlobals(globalsConfig, source = null) {
+ if (!globalsConfig) {
+ return;
+ }
+
+ Object.entries(globalsConfig)
+ .forEach(([configuredGlobal, configuredValue]) => {
+ try {
+ normalizeConfigGlobal(configuredValue);
+ } catch (err) {
+ throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`);
+ }
+ });
+ }
+
+ /**
+ * Validate `processor` configuration.
+ * @param {string|undefined} processorName The processor name.
+ * @param {string} source The name of config file.
+ * @param {function(id:string): Processor} getProcessor The getter of defined processors.
+ * @returns {void}
+ */
+ validateProcessor(processorName, source, getProcessor) {
+ if (processorName && !getProcessor(processorName)) {
+ throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`);
+ }
+ }
+
+ /**
+ * Formats an array of schema validation errors.
+ * @param {Array} errors An array of error messages to format.
+ * @returns {string} Formatted error message
+ */
+ formatErrors(errors) {
+ return errors.map(error => {
+ if (error.keyword === "additionalProperties") {
+ const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty;
+
+ return `Unexpected top-level property "${formattedPropertyPath}"`;
+ }
+ if (error.keyword === "type") {
+ const formattedField = error.dataPath.slice(1);
+ const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema;
+ const formattedValue = JSON.stringify(error.data);
+
+ return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`;
+ }
+
+ const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
+
+ return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`;
+ }).map(message => `\t- ${message}.\n`).join("");
+ }
+
+ /**
+ * Validates the top level properties of the config object.
+ * @param {Object} config The config object to validate.
+ * @param {string} source The name of the configuration source to report in any errors.
+ * @returns {void}
+ */
+ validateConfigSchema(config, source = null) {
+ validateSchema = validateSchema || ajv.compile(configSchema);
+
+ if (!validateSchema(config)) {
+ throw new Error(`ESLint configuration in ${source} is invalid:\n${this.formatErrors(validateSchema.errors)}`);
+ }
+
+ if (Object.hasOwnProperty.call(config, "ecmaFeatures")) {
+ emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES");
+ }
+ }
+
+ /**
+ * Validates an entire config object.
+ * @param {Object} config The config object to validate.
+ * @param {string} source The name of the configuration source to report in any errors.
+ * @param {function(ruleId:string): Object} [getAdditionalRule] A map from strings to loaded rules.
+ * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded envs.
+ * @returns {void}
+ */
+ validate(config, source, getAdditionalRule, getAdditionalEnv) {
+ this.validateConfigSchema(config, source);
+ this.validateRules(config.rules, source, getAdditionalRule);
+ this.validateEnvironment(config.env, source, getAdditionalEnv);
+ this.validateGlobals(config.globals, source);
+
+ for (const override of config.overrides || []) {
+ this.validateRules(override.rules, source, getAdditionalRule);
+ this.validateEnvironment(override.env, source, getAdditionalEnv);
+ this.validateGlobals(config.globals, source);
+ }
+ }
+
+ /**
+ * Validate config array object.
+ * @param {ConfigArray} configArray The config array to validate.
+ * @returns {void}
+ */
+ validateConfigArray(configArray) {
+ const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments);
+ const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors);
+ const getPluginRule = Map.prototype.get.bind(configArray.pluginRules);
+
+ // Validate.
+ for (const element of configArray) {
+ if (validated.has(element)) {
+ continue;
+ }
+ validated.add(element);
+
+ this.validateEnvironment(element.env, element.name, getPluginEnv);
+ this.validateGlobals(element.globals, element.name);
+ this.validateProcessor(element.processor, element.name, getPluginProcessor);
+ this.validateRules(element.rules, element.name, getPluginRule);
+ }
+ }
+
+}
+
+/**
+ * @fileoverview Common helpers for naming of plugins, formatters and configs
+ */
+
+const NAMESPACE_REGEX = /^@.*\//iu;
+
+/**
+ * Brings package name to correct format based on prefix
+ * @param {string} name The name of the package.
+ * @param {string} prefix Can be either "eslint-plugin", "eslint-config" or "eslint-formatter"
+ * @returns {string} Normalized name of the package
+ * @private
+ */
+function normalizePackageName(name, prefix) {
+ let normalizedName = name;
+
+ /**
+ * On Windows, name can come in with Windows slashes instead of Unix slashes.
+ * Normalize to Unix first to avoid errors later on.
+ * https://github.com/eslint/eslint/issues/5644
+ */
+ if (normalizedName.includes("\\")) {
+ normalizedName = normalizedName.replace(/\\/gu, "/");
+ }
+
+ if (normalizedName.charAt(0) === "@") {
+
+ /**
+ * it's a scoped package
+ * package name is the prefix, or just a username
+ */
+ const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`, "u"),
+ scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, "u");
+
+ if (scopedPackageShortcutRegex.test(normalizedName)) {
+ normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`);
+ } else if (!scopedPackageNameRegex.test(normalizedName.split("/")[1])) {
+
+ /**
+ * for scoped packages, insert the prefix after the first / unless
+ * the path is already @scope/eslint or @scope/eslint-xxx-yyy
+ */
+ normalizedName = normalizedName.replace(/^@([^/]+)\/(.*)$/u, `@$1/${prefix}-$2`);
+ }
+ } else if (!normalizedName.startsWith(`${prefix}-`)) {
+ normalizedName = `${prefix}-${normalizedName}`;
+ }
+
+ return normalizedName;
+}
+
+/**
+ * Removes the prefix from a fullname.
+ * @param {string} fullname The term which may have the prefix.
+ * @param {string} prefix The prefix to remove.
+ * @returns {string} The term without prefix.
+ */
+function getShorthandName(fullname, prefix) {
+ if (fullname[0] === "@") {
+ let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec(fullname);
+
+ if (matchResult) {
+ return matchResult[1];
+ }
+
+ matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec(fullname);
+ if (matchResult) {
+ return `${matchResult[1]}/${matchResult[2]}`;
+ }
+ } else if (fullname.startsWith(`${prefix}-`)) {
+ return fullname.slice(prefix.length + 1);
+ }
+
+ return fullname;
+}
+
+/**
+ * Gets the scope (namespace) of a term.
+ * @param {string} term The term which may have the namespace.
+ * @returns {string} The namespace of the term if it has one.
+ */
+function getNamespaceFromTerm(term) {
+ const match = term.match(NAMESPACE_REGEX);
+
+ return match ? match[0] : "";
+}
+
+var naming = {
+ __proto__: null,
+ normalizePackageName: normalizePackageName,
+ getShorthandName: getShorthandName,
+ getNamespaceFromTerm: getNamespaceFromTerm
+};
+
+/**
+ * Utility for resolving a module relative to another module
+ * @author Teddy Katz
+ */
+
+/*
+ * `Module.createRequire` is added in v12.2.0. It supports URL as well.
+ * We only support the case where the argument is a filepath, not a URL.
+ */
+const createRequire = Module__default["default"].createRequire;
+
+/**
+ * Resolves a Node module relative to another module
+ * @param {string} moduleName The name of a Node module, or a path to a Node module.
+ * @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be
+ * a file rather than a directory, but the file need not actually exist.
+ * @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath`
+ */
+function resolve(moduleName, relativeToPath) {
+ try {
+ return createRequire(relativeToPath).resolve(moduleName);
+ } catch (error) {
+
+ // This `if` block is for older Node.js than 12.0.0. We can remove this block in the future.
+ if (
+ typeof error === "object" &&
+ error !== null &&
+ error.code === "MODULE_NOT_FOUND" &&
+ !error.requireStack &&
+ error.message.includes(moduleName)
+ ) {
+ error.message += `\nRequire stack:\n- ${relativeToPath}`;
+ }
+ throw error;
+ }
+}
+
+var ModuleResolver = {
+ __proto__: null,
+ resolve: resolve
+};
+
+/**
+ * @fileoverview The factory of `ConfigArray` objects.
+ *
+ * This class provides methods to create `ConfigArray` instance.
+ *
+ * - `create(configData, options)`
+ * Create a `ConfigArray` instance from a config data. This is to handle CLI
+ * options except `--config`.
+ * - `loadFile(filePath, options)`
+ * Create a `ConfigArray` instance from a config file. This is to handle
+ * `--config` option. If the file was not found, throws the following error:
+ * - If the filename was `*.js`, a `MODULE_NOT_FOUND` error.
+ * - If the filename was `package.json`, an IO error or an
+ * `ESLINT_CONFIG_FIELD_NOT_FOUND` error.
+ * - Otherwise, an IO error such as `ENOENT`.
+ * - `loadInDirectory(directoryPath, options)`
+ * Create a `ConfigArray` instance from a config file which is on a given
+ * directory. This tries to load `.eslintrc.*` or `package.json`. If not
+ * found, returns an empty `ConfigArray`.
+ * - `loadESLintIgnore(filePath)`
+ * Create a `ConfigArray` instance from a config file that is `.eslintignore`
+ * format. This is to handle `--ignore-path` option.
+ * - `loadDefaultESLintIgnore()`
+ * Create a `ConfigArray` instance from `.eslintignore` or `package.json` in
+ * the current working directory.
+ *
+ * `ConfigArrayFactory` class has the responsibility that loads configuration
+ * files, including loading `extends`, `parser`, and `plugins`. The created
+ * `ConfigArray` instance has the loaded `extends`, `parser`, and `plugins`.
+ *
+ * But this class doesn't handle cascading. `CascadingConfigArrayFactory` class
+ * handles cascading and hierarchy.
+ *
+ * @author Toru Nagashima <https://github.com/mysticatea>
+ */
+
+const require$1 = Module.createRequire((__webpack_require__(983).pathToFileURL)(__filename).toString());
+
+const debug$2 = debugOrig__default["default"]("eslintrc:config-array-factory");
+
+//------------------------------------------------------------------------------
+// Helpers
+//------------------------------------------------------------------------------
+
+const configFilenames = [
+ ".eslintrc.js",
+ ".eslintrc.cjs",
+ ".eslintrc.yaml",
+ ".eslintrc.yml",
+ ".eslintrc.json",
+ ".eslintrc",
+ "package.json"
+];
+
+// Define types for VSCode IntelliSense.
+/** @typedef {import("./shared/types").ConfigData} ConfigData */
+/** @typedef {import("./shared/types").OverrideConfigData} OverrideConfigData */
+/** @typedef {import("./shared/types").Parser} Parser */
+/** @typedef {import("./shared/types").Plugin} Plugin */
+/** @typedef {import("./shared/types").Rule} Rule */
+/** @typedef {import("./config-array/config-dependency").DependentParser} DependentParser */
+/** @typedef {import("./config-array/config-dependency").DependentPlugin} DependentPlugin */
+/** @typedef {ConfigArray[0]} ConfigArrayElement */
+
+/**
+ * @typedef {Object} ConfigArrayFactoryOptions
+ * @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
+ * @property {string} [cwd] The path to the current working directory.
+ * @property {string} [resolvePluginsRelativeTo] A path to the directory that plugins should be resolved from. Defaults to `cwd`.
+ * @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
+ * @property {Object} [resolver=ModuleResolver] The module resolver object.
+ * @property {string} eslintAllPath The path to the definitions for eslint:all.
+ * @property {Function} getEslintAllConfig Returns the config data for eslint:all.
+ * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
+ * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
+ */
+
+/**
+ * @typedef {Object} ConfigArrayFactoryInternalSlots
+ * @property {Map<string,Plugin>} additionalPluginPool The map for additional plugins.
+ * @property {string} cwd The path to the current working directory.
+ * @property {string | undefined} resolvePluginsRelativeTo An absolute path the the directory that plugins should be resolved from.
+ * @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
+ * @property {Object} [resolver=ModuleResolver] The module resolver object.
+ * @property {string} eslintAllPath The path to the definitions for eslint:all.
+ * @property {Function} getEslintAllConfig Returns the config data for eslint:all.
+ * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
+ * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
+ */
+
+/**
+ * @typedef {Object} ConfigArrayFactoryLoadingContext
+ * @property {string} filePath The path to the current configuration.
+ * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
+ * @property {string} name The name of the current configuration.
+ * @property {string} pluginBasePath The base path to resolve plugins.
+ * @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.
+ */
+
+/**
+ * @typedef {Object} ConfigArrayFactoryLoadingContext
+ * @property {string} filePath The path to the current configuration.
+ * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
+ * @property {string} name The name of the current configuration.
+ * @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.
+ */
+
+/** @type {WeakMap<ConfigArrayFactory, ConfigArrayFactoryInternalSlots>} */
+const internalSlotsMap$1 = new WeakMap();
+
+/** @type {WeakMap<object, Plugin>} */
+const normalizedPlugins = new WeakMap();
+
+/**
+ * Check if a given string is a file path.
+ * @param {string} nameOrPath A module name or file path.
+ * @returns {boolean} `true` if the `nameOrPath` is a file path.
+ */
+function isFilePath(nameOrPath) {
+ return (
+ /^\.{1,2}[/\\]/u.test(nameOrPath) ||
+ path__default["default"].isAbsolute(nameOrPath)
+ );
+}
+
+/**
+ * Convenience wrapper for synchronously reading file contents.
+ * @param {string} filePath The filename to read.
+ * @returns {string} The file contents, with the BOM removed.
+ * @private
+ */
+function readFile(filePath) {
+ return fs__default["default"].readFileSync(filePath, "utf8").replace(/^\ufeff/u, "");
+}
+
+/**
+ * Loads a YAML configuration from a file.
+ * @param {string} filePath The filename to load.
+ * @returns {ConfigData} The configuration object from the file.
+ * @throws {Error} If the file cannot be read.
+ * @private
+ */
+function loadYAMLConfigFile(filePath) {
+ debug$2(`Loading YAML config file: ${filePath}`);
+
+ // lazy load YAML to improve performance when not used
+ const yaml = require$1("js-yaml");
+
+ try {
+
+ // empty YAML file can be null, so always use
+ return yaml.load(readFile(filePath)) || {};
+ } catch (e) {
+ debug$2(`Error reading YAML file: ${filePath}`);
+ e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
+ throw e;
+ }
+}
+
+/**
+ * Loads a JSON configuration from a file.
+ * @param {string} filePath The filename to load.
+ * @returns {ConfigData} The configuration object from the file.
+ * @throws {Error} If the file cannot be read.
+ * @private
+ */
+function loadJSONConfigFile(filePath) {
+ debug$2(`Loading JSON config file: ${filePath}`);
+
+ try {
+ return JSON.parse(stripComments__default["default"](readFile(filePath)));
+ } catch (e) {
+ debug$2(`Error reading JSON file: ${filePath}`);
+ e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
+ e.messageTemplate = "failed-to-read-json";
+ e.messageData = {
+ path: filePath,
+ message: e.message
+ };
+ throw e;
+ }
+}
+
+/**
+ * Loads a legacy (.eslintrc) configuration from a file.
+ * @param {string} filePath The filename to load.
+ * @returns {ConfigData} The configuration object from the file.
+ * @throws {Error} If the file cannot be read.
+ * @private
+ */
+function loadLegacyConfigFile(filePath) {
+ debug$2(`Loading legacy config file: ${filePath}`);
+
+ // lazy load YAML to improve performance when not used
+ const yaml = require$1("js-yaml");
+
+ try {
+ return yaml.load(stripComments__default["default"](readFile(filePath))) || /* istanbul ignore next */ {};
+ } catch (e) {
+ debug$2("Error reading YAML file: %s\n%o", filePath, e);
+ e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
+ throw e;
+ }
+}
+
+/**
+ * Loads a JavaScript configuration from a file.
+ * @param {string} filePath The filename to load.
+ * @returns {ConfigData} The configuration object from the file.
+ * @throws {Error} If the file cannot be read.
+ * @private
+ */
+function loadJSConfigFile(filePath) {
+ debug$2(`Loading JS config file: ${filePath}`);
+ try {
+ return importFresh__default["default"](filePath);
+ } catch (e) {
+ debug$2(`Error reading JavaScript file: ${filePath}`);
+ e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
+ throw e;
+ }
+}
+
+/**
+ * Loads a configuration from a package.json file.
+ * @param {string} filePath The filename to load.
+ * @returns {ConfigData} The configuration object from the file.
+ * @throws {Error} If the file cannot be read.
+ * @private
+ */
+function loadPackageJSONConfigFile(filePath) {
+ debug$2(`Loading package.json config file: ${filePath}`);
+ try {
+ const packageData = loadJSONConfigFile(filePath);
+
+ if (!Object.hasOwnProperty.call(packageData, "eslintConfig")) {
+ throw Object.assign(
+ new Error("package.json file doesn't have 'eslintConfig' field."),
+ { code: "ESLINT_CONFIG_FIELD_NOT_FOUND" }
+ );
+ }
+
+ return packageData.eslintConfig;
+ } catch (e) {
+ debug$2(`Error reading package.json file: ${filePath}`);
+ e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
+ throw e;
+ }
+}
+
+/**
+ * Loads a `.eslintignore` from a file.
+ * @param {string} filePath The filename to load.
+ * @returns {string[]} The ignore patterns from the file.
+ * @private
+ */
+function loadESLintIgnoreFile(filePath) {
+ debug$2(`Loading .eslintignore file: ${filePath}`);
+
+ try {
+ return readFile(filePath)
+ .split(/\r?\n/gu)
+ .filter(line => line.trim() !== "" && !line.startsWith("#"));
+ } catch (e) {
+ debug$2(`Error reading .eslintignore file: ${filePath}`);
+ e.message = `Cannot read .eslintignore file: ${filePath}\nError: ${e.message}`;
+ throw e;
+ }
+}
+
+/**
+ * Creates an error to notify about a missing config to extend from.
+ * @param {string} configName The name of the missing config.
+ * @param {string} importerName The name of the config that imported the missing config
+ * @param {string} messageTemplate The text template to source error strings from.
+ * @returns {Error} The error object to throw
+ * @private
+ */
+function configInvalidError(configName, importerName, messageTemplate) {
+ return Object.assign(
+ new Error(`Failed to load config "${configName}" to extend from.`),
+ {
+ messageTemplate,
+ messageData: { configName, importerName }
+ }
+ );
+}
+
+/**
+ * Loads a configuration file regardless of the source. Inspects the file path
+ * to determine the correctly way to load the config file.
+ * @param {string} filePath The path to the configuration.
+ * @returns {ConfigData|null} The configuration information.
+ * @private
+ */
+function loadConfigFile(filePath) {
+ switch (path__default["default"].extname(filePath)) {
+ case ".js":
+ case ".cjs":
+ return loadJSConfigFile(filePath);
+
+ case ".json":
+ if (path__default["default"].basename(filePath) === "package.json") {
+ return loadPackageJSONConfigFile(filePath);
+ }
+ return loadJSONConfigFile(filePath);
+
+ case ".yaml":
+ case ".yml":
+ return loadYAMLConfigFile(filePath);
+
+ default:
+ return loadLegacyConfigFile(filePath);
+ }
+}
+
+/**
+ * Write debug log.
+ * @param {string} request The requested module name.
+ * @param {string} relativeTo The file path to resolve the request relative to.
+ * @param {string} filePath The resolved file path.
+ * @returns {void}
+ */
+function writeDebugLogForLoading(request, relativeTo, filePath) {
+ /* istanbul ignore next */
+ if (debug$2.enabled) {
+ let nameAndVersion = null;
+
+ try {
+ const packageJsonPath = resolve(
+ `${request}/package.json`,
+ relativeTo
+ );
+ const { version = "unknown" } = require$1(packageJsonPath);
+
+ nameAndVersion = `${request}@${version}`;
+ } catch (error) {
+ debug$2("package.json was not found:", error.message);
+ nameAndVersion = request;
+ }
+
+ debug$2("Loaded: %s (%s)", nameAndVersion, filePath);
+ }
+}
+
+/**
+ * Create a new context with default values.
+ * @param {ConfigArrayFactoryInternalSlots} slots The internal slots.
+ * @param {"config" | "ignore" | "implicit-processor" | undefined} providedType The type of the current configuration. Default is `"config"`.
+ * @param {string | undefined} providedName The name of the current configuration. Default is the relative path from `cwd` to `filePath`.
+ * @param {string | undefined} providedFilePath The path to the current configuration. Default is empty string.
+ * @param {string | undefined} providedMatchBasePath The type of the current configuration. Default is the directory of `filePath` or `cwd`.
+ * @returns {ConfigArrayFactoryLoadingContext} The created context.
+ */
+function createContext(
+ { cwd, resolvePluginsRelativeTo },
+ providedType,
+ providedName,
+ providedFilePath,
+ providedMatchBasePath
+) {
+ const filePath = providedFilePath
+ ? path__default["default"].resolve(cwd, providedFilePath)
+ : "";
+ const matchBasePath =
+ (providedMatchBasePath && path__default["default"].resolve(cwd, providedMatchBasePath)) ||
+ (filePath && path__default["default"].dirname(filePath)) ||
+ cwd;
+ const name =
+ providedName ||
+ (filePath && path__default["default"].relative(cwd, filePath)) ||
+ "";
+ const pluginBasePath =
+ resolvePluginsRelativeTo ||
+ (filePath && path__default["default"].dirname(filePath)) ||
+ cwd;
+ const type = providedType || "config";
+
+ return { filePath, matchBasePath, name, pluginBasePath, type };
+}
+
+/**
+ * Normalize a given plugin.
+ * - Ensure the object to have four properties: configs, environments, processors, and rules.
+ * - Ensure the object to not have other properties.
+ * @param {Plugin} plugin The plugin to normalize.
+ * @returns {Plugin} The normalized plugin.
+ */
+function normalizePlugin(plugin) {
+
+ // first check the cache
+ let normalizedPlugin = normalizedPlugins.get(plugin);
+
+ if (normalizedPlugin) {
+ return normalizedPlugin;
+ }
+
+ normalizedPlugin = {
+ configs: plugin.configs || {},
+ environments: plugin.environments || {},
+ processors: plugin.processors || {},
+ rules: plugin.rules || {}
+ };
+
+ // save the reference for later
+ normalizedPlugins.set(plugin, normalizedPlugin);
+
+ return normalizedPlugin;
+}
+
+//------------------------------------------------------------------------------
+// Public Interface
+//------------------------------------------------------------------------------
+
+/**
+ * The factory of `ConfigArray` objects.
+ */
+class ConfigArrayFactory {
+
+ /**
+ * Initialize this instance.
+ * @param {ConfigArrayFactoryOptions} [options] The map for additional plugins.
+ */
+ constructor({
+ additionalPluginPool = new Map(),
+ cwd = process.cwd(),
+ resolvePluginsRelativeTo,
+ builtInRules,
+ resolver = ModuleResolver,
+ eslintAllPath,
+ getEslintAllConfig,
+ eslintRecommendedPath,
+ getEslintRecommendedConfig
+ } = {}) {
+ internalSlotsMap$1.set(this, {
+ additionalPluginPool,
+ cwd,
+ resolvePluginsRelativeTo:
+ resolvePluginsRelativeTo &&
+ path__default["default"].resolve(cwd, resolvePluginsRelativeTo),
+ builtInRules,
+ resolver,
+ eslintAllPath,
+ getEslintAllConfig,
+ eslintRecommendedPath,
+ getEslintRecommendedConfig
+ });
+ }
+
+ /**
+ * Create `ConfigArray` instance from a config data.
+ * @param {ConfigData|null} configData The config data to create.
+ * @param {Object} [options] The options.
+ * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
+ * @param {string} [options.filePath] The path to this config data.
+ * @param {string} [options.name] The config name.
+ * @returns {ConfigArray} Loaded config.
+ */
+ create(configData, { basePath, filePath, name } = {}) {
+ if (!configData) {
+ return new ConfigArray();
+ }
+
+ const slots = internalSlotsMap$1.get(this);
+ const ctx = createContext(slots, "config", name, filePath, basePath);
+ const elements = this._normalizeConfigData(configData, ctx);
+
+ return new ConfigArray(...elements);
+ }
+
+ /**
+ * Load a config file.
+ * @param {string} filePath The path to a config file.
+ * @param {Object} [options] The options.
+ * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
+ * @param {string} [options.name] The config name.
+ * @returns {ConfigArray} Loaded config.
+ */
+ loadFile(filePath, { basePath, name } = {}) {
+ const slots = internalSlotsMap$1.get(this);
+ const ctx = createContext(slots, "config", name, filePath, basePath);
+
+ return new ConfigArray(...this._loadConfigData(ctx));
+ }
+
+ /**
+ * Load the config file on a given directory if exists.
+ * @param {string} directoryPath The path to a directory.
+ * @param {Object} [options] The options.
+ * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
+ * @param {string} [options.name] The config name.
+ * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
+ */
+ loadInDirectory(directoryPath, { basePath, name } = {}) {
+ const slots = internalSlotsMap$1.get(this);
+
+ for (const filename of configFilenames) {
+ const ctx = createContext(
+ slots,
+ "config",
+ name,
+ path__default["default"].join(directoryPath, filename),
+ basePath
+ );
+
+ if (fs__default["default"].existsSync(ctx.filePath) && fs__default["default"].statSync(ctx.filePath).isFile()) {
+ let configData;
+
+ try {
+ configData = loadConfigFile(ctx.filePath);
+ } catch (error) {
+ if (!error || error.code !== "ESLINT_CONFIG_FIELD_NOT_FOUND") {
+ throw error;
+ }
+ }
+
+ if (configData) {
+ debug$2(`Config file found: ${ctx.filePath}`);
+ return new ConfigArray(
+ ...this._normalizeConfigData(configData, ctx)
+ );
+ }
+ }
+ }
+
+ debug$2(`Config file not found on ${directoryPath}`);
+ return new ConfigArray();
+ }
+
+ /**
+ * Check if a config file on a given directory exists or not.
+ * @param {string} directoryPath The path to a directory.
+ * @returns {string | null} The path to the found config file. If not found then null.
+ */
+ static getPathToConfigFileInDirectory(directoryPath) {
+ for (const filename of configFilenames) {
+ const filePath = path__default["default"].join(directoryPath, filename);
+
+ if (fs__default["default"].existsSync(filePath)) {
+ if (filename === "package.json") {
+ try {
+ loadPackageJSONConfigFile(filePath);
+ return filePath;
+ } catch { /* ignore */ }
+ } else {
+ return filePath;
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Load `.eslintignore` file.
+ * @param {string} filePath The path to a `.eslintignore` file to load.
+ * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
+ */
+ loadESLintIgnore(filePath) {
+ const slots = internalSlotsMap$1.get(this);
+ const ctx = createContext(
+ slots,
+ "ignore",
+ void 0,
+ filePath,
+ slots.cwd
+ );
+ const ignorePatterns = loadESLintIgnoreFile(ctx.filePath);
+
+ return new ConfigArray(
+ ...this._normalizeESLintIgnoreData(ignorePatterns, ctx)
+ );
+ }
+
+ /**
+ * Load `.eslintignore` file in the current working directory.
+ * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
+ */
+ loadDefaultESLintIgnore() {
+ const slots = internalSlotsMap$1.get(this);
+ const eslintIgnorePath = path__default["default"].resolve(slots.cwd, ".eslintignore");
+ const packageJsonPath = path__default["default"].resolve(slots.cwd, "package.json");
+
+ if (fs__default["default"].existsSync(eslintIgnorePath)) {
+ return this.loadESLintIgnore(eslintIgnorePath);
+ }
+ if (fs__default["default"].existsSync(packageJsonPath)) {
+ const data = loadJSONConfigFile(packageJsonPath);
+
+ if (Object.hasOwnProperty.call(data, "eslintIgnore")) {
+ if (!Array.isArray(data.eslintIgnore)) {
+ throw new Error("Package.json eslintIgnore property requires an array of paths");
+ }
+ const ctx = createContext(
+ slots,
+ "ignore",
+ "eslintIgnore in package.json",
+ packageJsonPath,
+ slots.cwd
+ );
+
+ return new ConfigArray(
+ ...this._normalizeESLintIgnoreData(data.eslintIgnore, ctx)
+ );
+ }
+ }
+
+ return new ConfigArray();
+ }
+
+ /**
+ * Load a given config file.
+ * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
+ * @returns {IterableIterator<ConfigArrayElement>} Loaded config.
+ * @private
+ */
+ _loadConfigData(ctx) {
+ return this._normalizeConfigData(loadConfigFile(ctx.filePath), ctx);
+ }
+
+ /**
+ * Normalize a given `.eslintignore` data to config array elements.
+ * @param {string[]} ignorePatterns The patterns to ignore files.
+ * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
+ * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
+ * @private
+ */
+ *_normalizeESLintIgnoreData(ignorePatterns, ctx) {
+ const elements = this._normalizeObjectConfigData(
+ { ignorePatterns },
+ ctx
+ );
+
+ // Set `ignorePattern.loose` flag for backward compatibility.
+ for (const element of elements) {
+ if (element.ignorePattern) {
+ element.ignorePattern.loose = true;
+ }
+ yield element;
+ }
+ }
+
+ /**
+ * Normalize a given config to an array.
+ * @param {ConfigData} configData The config data to normalize.
+ * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
+ * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
+ * @private
+ */
+ _normalizeConfigData(configData, ctx) {
+ const validator = new ConfigValidator();
+
+ validator.validateConfigSchema(configData, ctx.name || ctx.filePath);
+ return this._normalizeObjectConfigData(configData, ctx);
+ }
+
+ /**
+ * Normalize a given config to an array.
+ * @param {ConfigData|OverrideConfigData} configData The config data to normalize.
+ * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
+ * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
+ * @private
+ */
+ *_normalizeObjectConfigData(configData, ctx) {
+ const { files, excludedFiles, ...configBody } = configData;
+ const criteria = OverrideTester.create(
+ files,
+ excludedFiles,
+ ctx.matchBasePath
+ );
+ const elements = this._normalizeObjectConfigDataBody(configBody, ctx);
+
+ // Apply the criteria to every element.
+ for (const element of elements) {
+
+ /*
+ * Merge the criteria.
+ * This is for the `overrides` entries that came from the
+ * configurations of `overrides[].extends`.
+ */
+ element.criteria = OverrideTester.and(criteria, element.criteria);
+
+ /*
+ * Remove `root` property to ignore `root` settings which came from
+ * `extends` in `overrides`.
+ */
+ if (element.criteria) {
+ element.root = void 0;
+ }
+
+ yield element;
+ }
+ }
+
+ /**
+ * Normalize a given config to an array.
+ * @param {ConfigData} configData The config data to normalize.
+ * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
+ * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
+ * @private
+ */
+ *_normalizeObjectConfigDataBody(
+ {
+ env,
+ extends: extend,
+ globals,
+ ignorePatterns,
+ noInlineConfig,
+ parser: parserName,
+ parserOptions,
+ plugins: pluginList,
+ processor,
+ reportUnusedDisableDirectives,
+ root,
+ rules,
+ settings,
+ overrides: overrideList = []
+ },
+ ctx
+ ) {
+ const extendList = Array.isArray(extend) ? extend : [extend];
+ const ignorePattern = ignorePatterns && new IgnorePattern(
+ Array.isArray(ignorePatterns) ? ignorePatterns : [ignorePatterns],
+ ctx.matchBasePath
+ );
+
+ // Flatten `extends`.
+ for (const extendName of extendList.filter(Boolean)) {
+ yield* this._loadExtends(extendName, ctx);
+ }
+
+ // Load parser & plugins.
+ const parser = parserName && this._loadParser(parserName, ctx);
+ const plugins = pluginList && this._loadPlugins(pluginList, ctx);
+
+ // Yield pseudo config data for file extension processors.
+ if (plugins) {
+ yield* this._takeFileExtensionProcessors(plugins, ctx);
+ }
+
+ // Yield the config data except `extends` and `overrides`.
+ yield {
+
+ // Debug information.
+ type: ctx.type,
+ name: ctx.name,
+ filePath: ctx.filePath,
+
+ // Config data.
+ criteria: null,
+ env,
+ globals,
+ ignorePattern,
+ noInlineConfig,
+ parser,
+ parserOptions,
+ plugins,
+ processor,
+ reportUnusedDisableDirectives,
+ root,
+ rules,
+ settings
+ };
+
+ // Flatten `overries`.
+ for (let i = 0; i < overrideList.length; ++i) {
+ yield* this._normalizeObjectConfigData(
+ overrideList[i],
+ { ...ctx, name: `${ctx.name}#overrides[${i}]` }
+ );
+ }
+ }
+
+ /**
+ * Load configs of an element in `extends`.
+ * @param {string} extendName The name of a base config.
+ * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
+ * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
+ * @private
+ */
+ _loadExtends(extendName, ctx) {
+ debug$2("Loading {extends:%j} relative to %s", extendName, ctx.filePath);
+ try {
+ if (extendName.startsWith("eslint:")) {
+ return this._loadExtendedBuiltInConfig(extendName, ctx);
+ }
+ if (extendName.startsWith("plugin:")) {
+ return this._loadExtendedPluginConfig(extendName, ctx);
+ }
+ return this._loadExtendedShareableConfig(extendName, ctx);
+ } catch (error) {
+ error.message += `\nReferenced from: ${ctx.filePath || ctx.name}`;
+ throw error;
+ }
+ }
+
+ /**
+ * Load configs of an element in `extends`.
+ * @param {string} extendName The name of a base config.
+ * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
+ * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
+ * @private
+ */
+ _loadExtendedBuiltInConfig(extendName, ctx) {
+ const {
+ eslintAllPath,
+ getEslintAllConfig,
+ eslintRecommendedPath,
+ getEslintRecommendedConfig
+ } = internalSlotsMap$1.get(this);
+
+ if (extendName === "eslint:recommended") {
+ const name = `${ctx.name} » ${extendName}`;
+
+ if (getEslintRecommendedConfig) {
+ if (typeof getEslintRecommendedConfig !== "function") {
+ throw new Error(`getEslintRecommendedConfig must be a function instead of '${getEslintRecommendedConfig}'`);
+ }
+ return this._normalizeConfigData(getEslintRecommendedConfig(), { ...ctx, name, filePath: "" });
+ }
+ return this._loadConfigData({
+ ...ctx,
+ name,
+ filePath: eslintRecommendedPath
+ });
+ }
+ if (extendName === "eslint:all") {
+ const name = `${ctx.name} » ${extendName}`;
+
+ if (getEslintAllConfig) {
+ if (typeof getEslintAllConfig !== "function") {
+ throw new Error(`getEslintAllConfig must be a function instead of '${getEslintAllConfig}'`);
+ }
+ return this._normalizeConfigData(getEslintAllConfig(), { ...ctx, name, filePath: "" });
+ }
+ return this._loadConfigData({
+ ...ctx,
+ name,
+ filePath: eslintAllPath
+ });
+ }
+
+ throw configInvalidError(extendName, ctx.name, "extend-config-missing");
+ }
+
+ /**
+ * Load configs of an element in `extends`.
+ * @param {string} extendName The name of a base config.
+ * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
+ * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
+ * @private
+ */
+ _loadExtendedPluginConfig(extendName, ctx) {
+ const slashIndex = extendName.lastIndexOf("/");
+
+ if (slashIndex === -1) {
+ throw configInvalidError(extendName, ctx.filePath, "plugin-invalid");
+ }
+
+ const pluginName = extendName.slice("plugin:".length, slashIndex);
+ const configName = extendName.slice(slashIndex + 1);
+
+ if (isFilePath(pluginName)) {
+ throw new Error("'extends' cannot use a file path for plugins.");
+ }
+
+ const plugin = this._loadPlugin(pluginName, ctx);
+ const configData =
+ plugin.definition &&
+ plugin.definition.configs[configName];
+
+ if (configData) {
+ return this._normalizeConfigData(configData, {
+ ...ctx,
+ filePath: plugin.filePath || ctx.filePath,
+ name: `${ctx.name} » plugin:${plugin.id}/${configName}`
+ });
+ }
+
+ throw plugin.error || configInvalidError(extendName, ctx.filePath, "extend-config-missing");
+ }
+
+ /**
+ * Load configs of an element in `extends`.
+ * @param {string} extendName The name of a base config.
+ * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
+ * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
+ * @private
+ */
+ _loadExtendedShareableConfig(extendName, ctx) {
+ const { cwd, resolver } = internalSlotsMap$1.get(this);
+ const relativeTo = ctx.filePath || path__default["default"].join(cwd, "__placeholder__.js");
+ let request;
+
+ if (isFilePath(extendName)) {
+ request = extendName;
+ } else if (extendName.startsWith(".")) {
+ request = `./${extendName}`; // For backward compatibility. A ton of tests depended on this behavior.
+ } else {
+ request = normalizePackageName(
+ extendName,
+ "eslint-config"
+ );
+ }
+
+ let filePath;
+
+ try {
+ filePath = resolver.resolve(request, relativeTo);
+ } catch (error) {
+ /* istanbul ignore else */
+ if (error && error.code === "MODULE_NOT_FOUND") {
+ throw configInvalidError(extendName, ctx.filePath, "extend-config-missing");
+ }
+ throw error;
+ }
+
+ writeDebugLogForLoading(request, relativeTo, filePath);
+ return this._loadConfigData({
+ ...ctx,
+ filePath,
+ name: `${ctx.name} » ${request}`
+ });
+ }
+
+ /**
+ * Load given plugins.
+ * @param {string[]} names The plugin names to load.
+ * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
+ * @returns {Record<string,DependentPlugin>} The loaded parser.
+ * @private
+ */
+ _loadPlugins(names, ctx) {
+ return names.reduce((map, name) => {
+ if (isFilePath(name)) {
+ throw new Error("Plugins array cannot includes file paths.");
+ }
+ const plugin = this._loadPlugin(name, ctx);
+
+ map[plugin.id] = plugin;
+
+ return map;
+ }, {});
+ }
+
+ /**
+ * Load a given parser.
+ * @param {string} nameOrPath The package name or the path to a parser file.
+ * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
+ * @returns {DependentParser} The loaded parser.
+ */
+ _loadParser(nameOrPath, ctx) {
+ debug$2("Loading parser %j from %s", nameOrPath, ctx.filePath);
+
+ const { cwd, resolver } = internalSlotsMap$1.get(this);
+ const relativeTo = ctx.filePath || path__default["default"].join(cwd, "__placeholder__.js");
+
+ try {
+ const filePath = resolver.resolve(nameOrPath, relativeTo);
+
+ writeDebugLogForLoading(nameOrPath, relativeTo, filePath);
+
+ return new ConfigDependency({
+ definition: require$1(filePath),
+ filePath,
+ id: nameOrPath,
+ importerName: ctx.name,
+ importerPath: ctx.filePath
+ });
+ } catch (error) {
+
+ // If the parser name is "espree", load the espree of ESLint.
+ if (nameOrPath === "espree") {
+ debug$2("Fallback espree.");
+ return new ConfigDependency({
+ definition: require$1("espree"),
+ filePath: require$1.resolve("espree"),
+ id: nameOrPath,
+ importerName: ctx.name,
+ importerPath: ctx.filePath
+ });
+ }
+
+ debug$2("Failed to load parser '%s' declared in '%s'.", nameOrPath, ctx.name);
+ error.message = `Failed to load parser '${nameOrPath}' declared in '${ctx.name}': ${error.message}`;
+
+ return new ConfigDependency({
+ error,
+ id: nameOrPath,
+ importerName: ctx.name,
+ importerPath: ctx.filePath
+ });
+ }
+ }
+
+ /**
+ * Load a given plugin.
+ * @param {string} name The plugin name to load.
+ * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
+ * @returns {DependentPlugin} The loaded plugin.
+ * @private
+ */
+ _loadPlugin(name, ctx) {
+ debug$2("Loading plugin %j from %s", name, ctx.filePath);
+
+ const { additionalPluginPool, resolver } = internalSlotsMap$1.get(this);
+ const request = normalizePackageName(name, "eslint-plugin");
+ const id = getShorthandName(request, "eslint-plugin");
+ const relativeTo = path__default["default"].join(ctx.pluginBasePath, "__placeholder__.js");
+
+ if (name.match(/\s+/u)) {
+ const error = Object.assign(
+ new Error(`Whitespace found in plugin name '${name}'`),
+ {
+ messageTemplate: "whitespace-found",
+ messageData: { pluginName: request }
+ }
+ );
+
+ return new ConfigDependency({
+ error,
+ id,
+ importerName: ctx.name,
+ importerPath: ctx.filePath
+ });
+ }
+
+ // Check for additional pool.
+ const plugin =
+ additionalPluginPool.get(request) ||
+ additionalPluginPool.get(id);
+
+ if (plugin) {
+ return new ConfigDependency({
+ definition: normalizePlugin(plugin),
+ filePath: "", // It's unknown where the plugin came from.
+ id,
+ importerName: ctx.name,
+ importerPath: ctx.filePath
+ });
+ }
+
+ let filePath;
+ let error;
+
+ try {
+ filePath = resolver.resolve(request, relativeTo);
+ } catch (resolveError) {
+ error = resolveError;
+ /* istanbul ignore else */
+ if (error && error.code === "MODULE_NOT_FOUND") {
+ error.messageTemplate = "plugin-missing";
+ error.messageData = {
+ pluginName: request,
+ resolvePluginsRelativeTo: ctx.pluginBasePath,
+ importerName: ctx.name
+ };
+ }
+ }
+
+ if (filePath) {
+ try {
+ writeDebugLogForLoading(request, relativeTo, filePath);
+
+ const startTime = Date.now();
+ const pluginDefinition = require$1(filePath);
+
+ debug$2(`Plugin ${filePath} loaded in: ${Date.now() - startTime}ms`);
+
+ return new ConfigDependency({
+ definition: normalizePlugin(pluginDefinition),
+ filePath,
+ id,
+ importerName: ctx.name,
+ importerPath: ctx.filePath
+ });
+ } catch (loadError) {
+ error = loadError;
+ }
+ }
+
+ debug$2("Failed to load plugin '%s' declared in '%s'.", name, ctx.name);
+ error.message = `Failed to load plugin '${name}' declared in '${ctx.name}': ${error.message}`;
+ return new ConfigDependency({
+ error,
+ id,
+ importerName: ctx.name,
+ importerPath: ctx.filePath
+ });
+ }
+
+ /**
+ * Take file expression processors as config array elements.
+ * @param {Record<string,DependentPlugin>} plugins The plugin definitions.
+ * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
+ * @returns {IterableIterator<ConfigArrayElement>} The config array elements of file expression processors.
+ * @private
+ */
+ *_takeFileExtensionProcessors(plugins, ctx) {
+ for (const pluginId of Object.keys(plugins)) {
+ const processors =
+ plugins[pluginId] &&
+ plugins[pluginId].definition &&
+ plugins[pluginId].definition.processors;
+
+ if (!processors) {
+ continue;
+ }
+
+ for (const processorId of Object.keys(processors)) {
+ if (processorId.startsWith(".")) {
+ yield* this._normalizeObjectConfigData(
+ {
+ files: [`*${processorId}`],
+ processor: `${pluginId}/${processorId}`
+ },
+ {
+ ...ctx,
+ type: "implicit-processor",
+ name: `${ctx.name}#processors["${pluginId}/${processorId}"]`
+ }
+ );
+ }
+ }
+ }
+ }
+}
+
+/**
+ * @fileoverview `CascadingConfigArrayFactory` class.
+ *
+ * `CascadingConfigArrayFactory` class has a responsibility:
+ *
+ * 1. Handles cascading of config files.
+ *
+ * It provides two methods:
+ *
+ * - `getConfigArrayForFile(filePath)`
+ * Get the corresponded configuration of a given file. This method doesn't
+ * throw even if the given file didn't exist.
+ * - `clearCache()`
+ * Clear the internal cache. You have to call this method when
+ * `additionalPluginPool` was updated if `baseConfig` or `cliConfig` depends
+ * on the additional plugins. (`CLIEngine#addPlugin()` method calls this.)
+ *
+ * @author Toru Nagashima <https://github.com/mysticatea>
+ */
+
+const debug$1 = debugOrig__default["default"]("eslintrc:cascading-config-array-factory");
+
+//------------------------------------------------------------------------------
+// Helpers
+//------------------------------------------------------------------------------
+
+// Define types for VSCode IntelliSense.
+/** @typedef {import("./shared/types").ConfigData} ConfigData */
+/** @typedef {import("./shared/types").Parser} Parser */
+/** @typedef {import("./shared/types").Plugin} Plugin */
+/** @typedef {import("./shared/types").Rule} Rule */
+/** @typedef {ReturnType<ConfigArrayFactory["create"]>} ConfigArray */
+
+/**
+ * @typedef {Object} CascadingConfigArrayFactoryOptions
+ * @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
+ * @property {ConfigData} [baseConfig] The config by `baseConfig` option.
+ * @property {ConfigData} [cliConfig] The config by CLI options (`--env`, `--global`, `--ignore-pattern`, `--parser`, `--parser-options`, `--plugin`, and `--rule`). CLI options overwrite the setting in config files.
+ * @property {string} [cwd] The base directory to start lookup.
+ * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
+ * @property {string[]} [rulePaths] The value of `--rulesdir` option.
+ * @property {string} [specificConfigPath] The value of `--config` option.
+ * @property {boolean} [useEslintrc] if `false` then it doesn't load config files.
+ * @property {Function} loadRules The function to use to load rules.
+ * @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
+ * @property {Object} [resolver=ModuleResolver] The module resolver object.
+ * @property {string} eslintAllPath The path to the definitions for eslint:all.
+ * @property {Function} getEslintAllConfig Returns the config data for eslint:all.
+ * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
+ * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
+ */
+
+/**
+ * @typedef {Object} CascadingConfigArrayFactoryInternalSlots
+ * @property {ConfigArray} baseConfigArray The config array of `baseConfig` option.
+ * @property {ConfigData} baseConfigData The config data of `baseConfig` option. This is used to reset `baseConfigArray`.
+ * @property {ConfigArray} cliConfigArray The config array of CLI options.
+ * @property {ConfigData} cliConfigData The config data of CLI options. This is used to reset `cliConfigArray`.
+ * @property {ConfigArrayFactory} configArrayFactory The factory for config arrays.
+ * @property {Map<string, ConfigArray>} configCache The cache from directory paths to config arrays.
+ * @property {string} cwd The base directory to start lookup.
+ * @property {WeakMap<ConfigArray, ConfigArray>} finalizeCache The cache from config arrays to finalized config arrays.
+ * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
+ * @property {string[]|null} rulePaths The value of `--rulesdir` option. This is used to reset `baseConfigArray`.
+ * @property {string|null} specificConfigPath The value of `--config` option. This is used to reset `cliConfigArray`.
+ * @property {boolean} useEslintrc if `false` then it doesn't load config files.
+ * @property {Function} loadRules The function to use to load rules.
+ * @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
+ * @property {Object} [resolver=ModuleResolver] The module resolver object.
+ * @property {string} eslintAllPath The path to the definitions for eslint:all.
+ * @property {Function} getEslintAllConfig Returns the config data for eslint:all.
+ * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
+ * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
+ */
+
+/** @type {WeakMap<CascadingConfigArrayFactory, CascadingConfigArrayFactoryInternalSlots>} */
+const internalSlotsMap = new WeakMap();
+
+/**
+ * Create the config array from `baseConfig` and `rulePaths`.
+ * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
+ * @returns {ConfigArray} The config array of the base configs.
+ */
+function createBaseConfigArray({
+ configArrayFactory,
+ baseConfigData,
+ rulePaths,
+ cwd,
+ loadRules
+}) {
+ const baseConfigArray = configArrayFactory.create(
+ baseConfigData,
+ { name: "BaseConfig" }
+ );
+
+ /*
+ * Create the config array element for the default ignore patterns.
+ * This element has `ignorePattern` property that ignores the default
+ * patterns in the current working directory.
+ */
+ baseConfigArray.unshift(configArrayFactory.create(
+ { ignorePatterns: IgnorePattern.DefaultPatterns },
+ { name: "DefaultIgnorePattern" }
+ )[0]);
+
+ /*
+ * Load rules `--rulesdir` option as a pseudo plugin.
+ * Use a pseudo plugin to define rules of `--rulesdir`, so we can validate
+ * the rule's options with only information in the config array.
+ */
+ if (rulePaths && rulePaths.length > 0) {
+ baseConfigArray.push({
+ type: "config",
+ name: "--rulesdir",
+ filePath: "",
+ plugins: {
+ "": new ConfigDependency({
+ definition: {
+ rules: rulePaths.reduce(
+ (map, rulesPath) => Object.assign(
+ map,
+ loadRules(rulesPath, cwd)
+ ),
+ {}
+ )
+ },
+ filePath: "",
+ id: "",
+ importerName: "--rulesdir",
+ importerPath: ""
+ })
+ }
+ });
+ }
+
+ return baseConfigArray;
+}
+
+/**
+ * Create the config array from CLI options.
+ * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
+ * @returns {ConfigArray} The config array of the base configs.
+ */
+function createCLIConfigArray({
+ cliConfigData,
+ configArrayFactory,
+ cwd,
+ ignorePath,
+ specificConfigPath
+}) {
+ const cliConfigArray = configArrayFactory.create(
+ cliConfigData,
+ { name: "CLIOptions" }
+ );
+
+ cliConfigArray.unshift(
+ ...(ignorePath
+ ? configArrayFactory.loadESLintIgnore(ignorePath)
+ : configArrayFactory.loadDefaultESLintIgnore())
+ );
+
+ if (specificConfigPath) {
+ cliConfigArray.unshift(
+ ...configArrayFactory.loadFile(
+ specificConfigPath,
+ { name: "--config", basePath: cwd }
+ )
+ );
+ }
+
+ return cliConfigArray;
+}
+
+/**
+ * The error type when there are files matched by a glob, but all of them have been ignored.
+ */
+class ConfigurationNotFoundError extends Error {
+
+ // eslint-disable-next-line jsdoc/require-description
+ /**
+ * @param {string} directoryPath The directory path.
+ */
+ constructor(directoryPath) {
+ super(`No ESLint configuration found in ${directoryPath}.`);
+ this.messageTemplate = "no-config-found";
+ this.messageData = { directoryPath };
+ }
+}
+
+/**
+ * This class provides the functionality that enumerates every file which is
+ * matched by given glob patterns and that configuration.
+ */
+class CascadingConfigArrayFactory {
+
+ /**
+ * Initialize this enumerator.
+ * @param {CascadingConfigArrayFactoryOptions} options The options.
+ */
+ constructor({
+ additionalPluginPool = new Map(),
+ baseConfig: baseConfigData = null,
+ cliConfig: cliConfigData = null,
+ cwd = process.cwd(),
+ ignorePath,
+ resolvePluginsRelativeTo,
+ rulePaths = [],
+ specificConfigPath = null,
+ useEslintrc = true,
+ builtInRules = new Map(),
+ loadRules,
+ resolver,
+ eslintRecommendedPath,
+ getEslintRecommendedConfig,
+ eslintAllPath,
+ getEslintAllConfig
+ } = {}) {
+ const configArrayFactory = new ConfigArrayFactory({
+ additionalPluginPool,
+ cwd,
+ resolvePluginsRelativeTo,
+ builtInRules,
+ resolver,
+ eslintRecommendedPath,
+ getEslintRecommendedConfig,
+ eslintAllPath,
+ getEslintAllConfig
+ });
+
+ internalSlotsMap.set(this, {
+ baseConfigArray: createBaseConfigArray({
+ baseConfigData,
+ configArrayFactory,
+ cwd,
+ rulePaths,
+ loadRules,
+ resolver
+ }),
+ baseConfigData,
+ cliConfigArray: createCLIConfigArray({
+ cliConfigData,
+ configArrayFactory,
+ cwd,
+ ignorePath,
+ specificConfigPath
+ }),
+ cliConfigData,
+ configArrayFactory,
+ configCache: new Map(),
+ cwd,
+ finalizeCache: new WeakMap(),
+ ignorePath,
+ rulePaths,
+ specificConfigPath,
+ useEslintrc,
+ builtInRules,
+ loadRules
+ });
+ }
+
+ /**
+ * The path to the current working directory.
+ * This is used by tests.
+ * @type {string}
+ */
+ get cwd() {
+ const { cwd } = internalSlotsMap.get(this);
+
+ return cwd;
+ }
+
+ /**
+ * Get the config array of a given file.
+ * If `filePath` was not given, it returns the config which contains only
+ * `baseConfigData` and `cliConfigData`.
+ * @param {string} [filePath] The file path to a file.
+ * @param {Object} [options] The options.
+ * @param {boolean} [options.ignoreNotFoundError] If `true` then it doesn't throw `ConfigurationNotFoundError`.
+ * @returns {ConfigArray} The config array of the file.
+ */
+ getConfigArrayForFile(filePath, { ignoreNotFoundError = false } = {}) {
+ const {
+ baseConfigArray,
+ cliConfigArray,
+ cwd
+ } = internalSlotsMap.get(this);
+
+ if (!filePath) {
+ return new ConfigArray(...baseConfigArray, ...cliConfigArray);
+ }
+
+ const directoryPath = path__default["default"].dirname(path__default["default"].resolve(cwd, filePath));
+
+ debug$1(`Load config files for ${directoryPath}.`);
+
+ return this._finalizeConfigArray(
+ this._loadConfigInAncestors(directoryPath),
+ directoryPath,
+ ignoreNotFoundError
+ );
+ }
+
+ /**
+ * Set the config data to override all configs.
+ * Require to call `clearCache()` method after this method is called.
+ * @param {ConfigData} configData The config data to override all configs.
+ * @returns {void}
+ */
+ setOverrideConfig(configData) {
+ const slots = internalSlotsMap.get(this);
+
+ slots.cliConfigData = configData;
+ }
+
+ /**
+ * Clear config cache.
+ * @returns {void}
+ */
+ clearCache() {
+ const slots = internalSlotsMap.get(this);
+
+ slots.baseConfigArray = createBaseConfigArray(slots);
+ slots.cliConfigArray = createCLIConfigArray(slots);
+ slots.configCache.clear();
+ }
+
+ /**
+ * Load and normalize config files from the ancestor directories.
+ * @param {string} directoryPath The path to a leaf directory.
+ * @param {boolean} configsExistInSubdirs `true` if configurations exist in subdirectories.
+ * @returns {ConfigArray} The loaded config.
+ * @private
+ */
+ _loadConfigInAncestors(directoryPath, configsExistInSubdirs = false) {
+ const {
+ baseConfigArray,
+ configArrayFactory,
+ configCache,
+ cwd,
+ useEslintrc
+ } = internalSlotsMap.get(this);
+
+ if (!useEslintrc) {
+ return baseConfigArray;
+ }
+
+ let configArray = configCache.get(directoryPath);
+
+ // Hit cache.
+ if (configArray) {
+ debug$1(`Cache hit: ${directoryPath}.`);
+ return configArray;
+ }
+ debug$1(`No cache found: ${directoryPath}.`);
+
+ const homePath = os__default["default"].homedir();
+
+ // Consider this is root.
+ if (directoryPath === homePath && cwd !== homePath) {
+ debug$1("Stop traversing because of considered root.");
+ if (configsExistInSubdirs) {
+ const filePath = ConfigArrayFactory.getPathToConfigFileInDirectory(directoryPath);
+
+ if (filePath) {
+ emitDeprecationWarning(
+ filePath,
+ "ESLINT_PERSONAL_CONFIG_SUPPRESS"
+ );
+ }
+ }
+ return this._cacheConfig(directoryPath, baseConfigArray);
+ }
+
+ // Load the config on this directory.
+ try {
+ configArray = configArrayFactory.loadInDirectory(directoryPath);
+ } catch (error) {
+ /* istanbul ignore next */
+ if (error.code === "EACCES") {
+ debug$1("Stop traversing because of 'EACCES' error.");
+ return this._cacheConfig(directoryPath, baseConfigArray);
+ }
+ throw error;
+ }
+
+ if (configArray.length > 0 && configArray.isRoot()) {
+ debug$1("Stop traversing because of 'root:true'.");
+ configArray.unshift(...baseConfigArray);
+ return this._cacheConfig(directoryPath, configArray);
+ }
+
+ // Load from the ancestors and merge it.
+ const parentPath = path__default["default"].dirname(directoryPath);
+ const parentConfigArray = parentPath && parentPath !== directoryPath
+ ? this._loadConfigInAncestors(
+ parentPath,
+ configsExistInSubdirs || configArray.length > 0
+ )
+ : baseConfigArray;
+
+ if (configArray.length > 0) {
+ configArray.unshift(...parentConfigArray);
+ } else {
+ configArray = parentConfigArray;
+ }
+
+ // Cache and return.
+ return this._cacheConfig(directoryPath, configArray);
+ }
+
+ /**
+ * Freeze and cache a given config.
+ * @param {string} directoryPath The path to a directory as a cache key.
+ * @param {ConfigArray} configArray The config array as a cache value.
+ * @returns {ConfigArray} The `configArray` (frozen).
+ */
+ _cacheConfig(directoryPath, configArray) {
+ const { configCache } = internalSlotsMap.get(this);
+
+ Object.freeze(configArray);
+ configCache.set(directoryPath, configArray);
+
+ return configArray;
+ }
+
+ /**
+ * Finalize a given config array.
+ * Concatenate `--config` and other CLI options.
+ * @param {ConfigArray} configArray The parent config array.
+ * @param {string} directoryPath The path to the leaf directory to find config files.
+ * @param {boolean} ignoreNotFoundError If `true` then it doesn't throw `ConfigurationNotFoundError`.
+ * @returns {ConfigArray} The loaded config.
+ * @private
+ */
+ _finalizeConfigArray(configArray, directoryPath, ignoreNotFoundError) {
+ const {
+ cliConfigArray,
+ configArrayFactory,
+ finalizeCache,
+ useEslintrc,
+ builtInRules
+ } = internalSlotsMap.get(this);
+
+ let finalConfigArray = finalizeCache.get(configArray);
+
+ if (!finalConfigArray) {
+ finalConfigArray = configArray;
+
+ // Load the personal config if there are no regular config files.
+ if (
+ useEslintrc &&
+ configArray.every(c => !c.filePath) &&
+ cliConfigArray.every(c => !c.filePath) // `--config` option can be a file.
+ ) {
+ const homePath = os__default["default"].homedir();
+
+ debug$1("Loading the config file of the home directory:", homePath);
+
+ const personalConfigArray = configArrayFactory.loadInDirectory(
+ homePath,
+ { name: "PersonalConfig" }
+ );
+
+ if (
+ personalConfigArray.length > 0 &&
+ !directoryPath.startsWith(homePath)
+ ) {
+ const lastElement =
+ personalConfigArray[personalConfigArray.length - 1];
+
+ emitDeprecationWarning(
+ lastElement.filePath,
+ "ESLINT_PERSONAL_CONFIG_LOAD"
+ );
+ }
+
+ finalConfigArray = finalConfigArray.concat(personalConfigArray);
+ }
+
+ // Apply CLI options.
+ if (cliConfigArray.length > 0) {
+ finalConfigArray = finalConfigArray.concat(cliConfigArray);
+ }
+
+ // Validate rule settings and environments.
+ const validator = new ConfigValidator({
+ builtInRules
+ });
+
+ validator.validateConfigArray(finalConfigArray);
+
+ // Cache it.
+ Object.freeze(finalConfigArray);
+ finalizeCache.set(configArray, finalConfigArray);
+
+ debug$1(
+ "Configuration was determined: %o on %s",
+ finalConfigArray,
+ directoryPath
+ );
+ }
+
+ // At least one element (the default ignore patterns) exists.
+ if (!ignoreNotFoundError && useEslintrc && finalConfigArray.length <= 1) {
+ throw new ConfigurationNotFoundError(directoryPath);
+ }
+
+ return finalConfigArray;
+ }
+}
+
+/**
+ * @fileoverview Compatibility class for flat config.
+ * @author Nicholas C. Zakas
+ */
+
+//-----------------------------------------------------------------------------
+// Helpers
+//-----------------------------------------------------------------------------
+
+/** @typedef {import("../../shared/types").Environment} Environment */
+/** @typedef {import("../../shared/types").Processor} Processor */
+
+const debug = debugOrig__default["default"]("eslintrc:flat-compat");
+const cafactory = Symbol("cafactory");
+
+/**
+ * Translates an ESLintRC-style config object into a flag-config-style config
+ * object.
+ * @param {Object} eslintrcConfig An ESLintRC-style config object.
+ * @param {Object} options Options to help translate the config.
+ * @param {string} options.resolveConfigRelativeTo To the directory to resolve
+ * configs from.
+ * @param {string} options.resolvePluginsRelativeTo The directory to resolve
+ * plugins from.
+ * @param {ReadOnlyMap<string,Environment>} options.pluginEnvironments A map of plugin environment
+ * names to objects.
+ * @param {ReadOnlyMap<string,Processor>} options.pluginProcessors A map of plugin processor
+ * names to objects.
+ * @returns {Object} A flag-config-style config object.
+ */
+function translateESLintRC(eslintrcConfig, {
+ resolveConfigRelativeTo,
+ resolvePluginsRelativeTo,
+ pluginEnvironments,
+ pluginProcessors
+}) {
+
+ const flatConfig = {};
+ const configs = [];
+ const languageOptions = {};
+ const linterOptions = {};
+ const keysToCopy = ["settings", "rules", "processor"];
+ const languageOptionsKeysToCopy = ["globals", "parser", "parserOptions"];
+ const linterOptionsKeysToCopy = ["noInlineConfig", "reportUnusedDisableDirectives"];
+
+ // check for special settings for eslint:all and eslint:recommended:
+ if (eslintrcConfig.settings) {
+ if (eslintrcConfig.settings["eslint:all"] === true) {
+ return ["eslint:all"];
+ }
+
+ if (eslintrcConfig.settings["eslint:recommended"] === true) {
+ return ["eslint:recommended"];
+ }
+ }
+
+ // copy over simple translations
+ for (const key of keysToCopy) {
+ if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
+ flatConfig[key] = eslintrcConfig[key];
+ }
+ }
+
+ // copy over languageOptions
+ for (const key of languageOptionsKeysToCopy) {
+ if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
+
+ // create the languageOptions key in the flat config
+ flatConfig.languageOptions = languageOptions;
+
+ if (key === "parser") {
+ debug(`Resolving parser '${languageOptions[key]}' relative to ${resolveConfigRelativeTo}`);
+
+ if (eslintrcConfig[key].error) {
+ throw eslintrcConfig[key].error;
+ }
+
+ languageOptions[key] = eslintrcConfig[key].definition;
+ continue;
+ }
+
+ // clone any object values that are in the eslintrc config
+ if (eslintrcConfig[key] && typeof eslintrcConfig[key] === "object") {
+ languageOptions[key] = {
+ ...eslintrcConfig[key]
+ };
+ } else {
+ languageOptions[key] = eslintrcConfig[key];
+ }
+ }
+ }
+
+ // copy over linterOptions
+ for (const key of linterOptionsKeysToCopy) {
+ if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
+ flatConfig.linterOptions = linterOptions;
+ linterOptions[key] = eslintrcConfig[key];
+ }
+ }
+
+ // move ecmaVersion a level up
+ if (languageOptions.parserOptions) {
+
+ if ("ecmaVersion" in languageOptions.parserOptions) {
+ languageOptions.ecmaVersion = languageOptions.parserOptions.ecmaVersion;
+ delete languageOptions.parserOptions.ecmaVersion;
+ }
+
+ if ("sourceType" in languageOptions.parserOptions) {
+ languageOptions.sourceType = languageOptions.parserOptions.sourceType;
+ delete languageOptions.parserOptions.sourceType;
+ }
+
+ // check to see if we even need parserOptions anymore and remove it if not
+ if (Object.keys(languageOptions.parserOptions).length === 0) {
+ delete languageOptions.parserOptions;
+ }
+ }
+
+ // overrides
+ if (eslintrcConfig.criteria) {
+ flatConfig.files = [absoluteFilePath => eslintrcConfig.criteria.test(absoluteFilePath)];
+ }
+
+ // translate plugins
+ if (eslintrcConfig.plugins && typeof eslintrcConfig.plugins === "object") {
+ debug(`Translating plugins: ${eslintrcConfig.plugins}`);
+
+ flatConfig.plugins = {};
+
+ for (const pluginName of Object.keys(eslintrcConfig.plugins)) {
+
+ debug(`Translating plugin: ${pluginName}`);
+ debug(`Resolving plugin '${pluginName} relative to ${resolvePluginsRelativeTo}`);
+
+ const { definition: plugin, error } = eslintrcConfig.plugins[pluginName];
+
+ if (error) {
+ throw error;
+ }
+
+ flatConfig.plugins[pluginName] = plugin;
+
+ // create a config for any processors
+ if (plugin.processors) {
+ for (const processorName of Object.keys(plugin.processors)) {
+ if (processorName.startsWith(".")) {
+ debug(`Assigning processor: ${pluginName}/${processorName}`);
+
+ configs.unshift({
+ files: [`**/*${processorName}`],
+ processor: pluginProcessors.get(`${pluginName}/${processorName}`)
+ });
+ }
+
+ }
+ }
+ }
+ }
+
+ // translate env - must come after plugins
+ if (eslintrcConfig.env && typeof eslintrcConfig.env === "object") {
+ for (const envName of Object.keys(eslintrcConfig.env)) {
+
+ // only add environments that are true
+ if (eslintrcConfig.env[envName]) {
+ debug(`Translating environment: ${envName}`);
+
+ if (environments.has(envName)) {
+
+ // built-in environments should be defined first
+ configs.unshift(...translateESLintRC(environments.get(envName), {
+ resolveConfigRelativeTo,
+ resolvePluginsRelativeTo
+ }));
+ } else if (pluginEnvironments.has(envName)) {
+
+ // if the environment comes from a plugin, it should come after the plugin config
+ configs.push(...translateESLintRC(pluginEnvironments.get(envName), {
+ resolveConfigRelativeTo,
+ resolvePluginsRelativeTo
+ }));
+ }
+ }
+ }
+ }
+
+ // only add if there are actually keys in the config
+ if (Object.keys(flatConfig).length > 0) {
+ configs.push(flatConfig);
+ }
+
+ return configs;
+}
+
+
+//-----------------------------------------------------------------------------
+// Exports
+//-----------------------------------------------------------------------------
+
+/**
+ * A compatibility class for working with configs.
+ */
+class FlatCompat {
+
+ constructor({
+ baseDirectory = process.cwd(),
+ resolvePluginsRelativeTo = baseDirectory
+ } = {}) {
+ this.baseDirectory = baseDirectory;
+ this.resolvePluginsRelativeTo = resolvePluginsRelativeTo;
+ this[cafactory] = new ConfigArrayFactory({
+ cwd: baseDirectory,
+ resolvePluginsRelativeTo,
+ getEslintAllConfig: () => ({ settings: { "eslint:all": true } }),
+ getEslintRecommendedConfig: () => ({ settings: { "eslint:recommended": true } })
+ });
+ }
+
+ /**
+ * Translates an ESLintRC-style config into a flag-config-style config.
+ * @param {Object} eslintrcConfig The ESLintRC-style config object.
+ * @returns {Object} A flag-config-style config object.
+ */
+ config(eslintrcConfig) {
+ const eslintrcArray = this[cafactory].create(eslintrcConfig, {
+ basePath: this.baseDirectory
+ });
+
+ const flatArray = [];
+ let hasIgnorePatterns = false;
+
+ eslintrcArray.forEach(configData => {
+ if (configData.type === "config") {
+ hasIgnorePatterns = hasIgnorePatterns || configData.ignorePattern;
+ flatArray.push(...translateESLintRC(configData, {
+ resolveConfigRelativeTo: path__default["default"].join(this.baseDirectory, "__placeholder.js"),
+ resolvePluginsRelativeTo: path__default["default"].join(this.resolvePluginsRelativeTo, "__placeholder.js"),
+ pluginEnvironments: eslintrcArray.pluginEnvironments,
+ pluginProcessors: eslintrcArray.pluginProcessors
+ }));
+ }
+ });
+
+ // combine ignorePatterns to emulate ESLintRC behavior better
+ if (hasIgnorePatterns) {
+ flatArray.unshift({
+ ignores: [filePath => {
+
+ // Compute the final config for this file.
+ // This filters config array elements by `files`/`excludedFiles` then merges the elements.
+ const finalConfig = eslintrcArray.extractConfig(filePath);
+
+ // Test the `ignorePattern` properties of the final config.
+ return Boolean(finalConfig.ignores) && finalConfig.ignores(filePath);
+ }]
+ });
+ }
+
+ return flatArray;
+ }
+
+ /**
+ * Translates the `env` section of an ESLintRC-style config.
+ * @param {Object} envConfig The `env` section of an ESLintRC config.
+ * @returns {Object} A flag-config object representing the environments.
+ */
+ env(envConfig) {
+ return this.config({
+ env: envConfig
+ });
+ }
+
+ /**
+ * Translates the `extends` section of an ESLintRC-style config.
+ * @param {...string} configsToExtend The names of the configs to load.
+ * @returns {Object} A flag-config object representing the config.
+ */
+ extends(...configsToExtend) {
+ return this.config({
+ extends: configsToExtend
+ });
+ }
+
+ /**
+ * Translates the `plugins` section of an ESLintRC-style config.
+ * @param {...string} plugins The names of the plugins to load.
+ * @returns {Object} A flag-config object representing the plugins.
+ */
+ plugins(...plugins) {
+ return this.config({
+ plugins
+ });
+ }
+}
+
+/**
+ * @fileoverview Package exports for @eslint/eslintrc
+ * @author Nicholas C. Zakas
+ */
+
+//-----------------------------------------------------------------------------
+// Exports
+//-----------------------------------------------------------------------------
+
+const Legacy = {
+ ConfigArray,
+ createConfigArrayFactoryContext: createContext,
+ CascadingConfigArrayFactory,
+ ConfigArrayFactory,
+ ConfigDependency,
+ ExtractedConfig,
+ IgnorePattern,
+ OverrideTester,
+ getUsedExtractedConfigs,
+ environments,
+
+ // shared
+ ConfigOps,
+ ConfigValidator,
+ ModuleResolver,
+ naming
+};
+
+exports.FlatCompat = FlatCompat;
+exports.Legacy = Legacy;
+//# sourceMappingURL=eslintrc.cjs.map
+
+
+/***/ }),
+/* 975 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+
+
+const path = __webpack_require__(501);
+
+const resolveFrom = __webpack_require__(976);
+
+const parentModule = __webpack_require__(978);
+
+module.exports = moduleId => {
+ if (typeof moduleId !== 'string') {
+ throw new TypeError('Expected a string');
+ }
+
+ const parentPath = parentModule(__filename);
+ const cwd = parentPath ? path.dirname(parentPath) : __dirname;
+ const filePath = resolveFrom(cwd, moduleId);
+ const oldModule = __webpack_require__.c[filePath]; // Delete itself from module parent
+
+ if (oldModule && oldModule.parent) {
+ let i = oldModule.parent.children.length;
+
+ while (i--) {
+ if (oldModule.parent.children[i].id === filePath) {
+ oldModule.parent.children.splice(i, 1);
+ }
+ }
+ }
+
+ delete __webpack_require__.c[filePath]; // Delete module from cache
+
+ const parent = __webpack_require__.c[parentPath]; // If `filePath` and `parentPath` are the same, cache will already be deleted so we won't get a memory leak in next step
+
+ return parent === undefined ? __webpack_require__(980)(filePath) : parent.require(filePath); // In case cache doesn't have parent, fall back to normal require
+};
+
+/***/ }),
+/* 976 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+
+
+const path = __webpack_require__(501);
+
+const Module = __webpack_require__(977);
+
+const fs = __webpack_require__(971);
+
+const resolveFrom = (fromDir, moduleId, silent) => {
+ if (typeof fromDir !== 'string') {
+ throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDir}\``);
+ }
+
+ if (typeof moduleId !== 'string') {
+ throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``);
+ }
+
+ try {
+ fromDir = fs.realpathSync(fromDir);
+ } catch (err) {
+ if (err.code === 'ENOENT') {
+ fromDir = path.resolve(fromDir);
+ } else if (silent) {
+ return null;
+ } else {
+ throw err;
+ }
+ }
+
+ const fromFile = path.join(fromDir, 'noop.js');
+
+ const resolveFileName = () => Module._resolveFilename(moduleId, {
+ id: fromFile,
+ filename: fromFile,
+ paths: Module._nodeModulePaths(fromDir)
+ });
+
+ if (silent) {
+ try {
+ return resolveFileName();
+ } catch (err) {
+ return null;
+ }
+ }
+
+ return resolveFileName();
+};
+
+module.exports = (fromDir, moduleId) => resolveFrom(fromDir, moduleId);
+
+module.exports.silent = (fromDir, moduleId) => resolveFrom(fromDir, moduleId, true);
+
+/***/ }),
+/* 977 */
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("module");
+
+/***/ }),
+/* 978 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+
+
+const callsites = __webpack_require__(979);
+
+module.exports = filepath => {
+ const stacks = callsites();
+
+ if (!filepath) {
+ return stacks[2].getFileName();
+ }
+
+ let seenVal = false; // Skip the first stack as it's this function
+
+ stacks.shift();
+
+ for (const stack of stacks) {
+ const parentFilepath = stack.getFileName();
+
+ if (typeof parentFilepath !== 'string') {
+ continue;
+ }
+
+ if (parentFilepath === filepath) {
+ seenVal = true;
+ continue;
+ } // Skip native modules
+
+
+ if (parentFilepath === 'module.js') {
+ continue;
+ }
+
+ if (seenVal && parentFilepath !== filepath) {
+ return parentFilepath;
+ }
+ }
+};
+
+/***/ }),
+/* 979 */
+/***/ ((module) => {
+
+"use strict";
+
+
+const callsites = () => {
+ const _prepareStackTrace = Error.prepareStackTrace;
+
+ Error.prepareStackTrace = (_, stack) => stack;
+
+ const stack = new Error().stack.slice(1);
+ Error.prepareStackTrace = _prepareStackTrace;
+ return stack;
+};
+
+module.exports = callsites; // TODO: Remove this for the next major release
+
+module.exports["default"] = callsites;
+
+/***/ }),
+/* 980 */
+/***/ ((module) => {
+
+function webpackEmptyContext(req) {
+ var e = new Error("Cannot find module '" + req + "'");
+ e.code = 'MODULE_NOT_FOUND';
+ throw e;
+}
+webpackEmptyContext.keys = () => ([]);
+webpackEmptyContext.resolve = webpackEmptyContext;
+webpackEmptyContext.id = 980;
+module.exports = webpackEmptyContext;
+
+/***/ }),
+/* 981 */
+/***/ ((module) => {
+
+"use strict";
+
+
+const singleComment = Symbol('singleComment');
+const multiComment = Symbol('multiComment');
+
+const stripWithoutWhitespace = () => '';
+
+const stripWithWhitespace = (string, start, end) => string.slice(start, end).replace(/\S/g, ' ');
+
+const isEscaped = (jsonString, quotePosition) => {
+ let index = quotePosition - 1;
+ let backslashCount = 0;
+
+ while (jsonString[index] === '\\') {
+ index -= 1;
+ backslashCount += 1;
+ }
+
+ return Boolean(backslashCount % 2);
+};
+
+module.exports = function (jsonString) {
+ let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+
+ if (typeof jsonString !== 'string') {
+ throw new TypeError(`Expected argument \`jsonString\` to be a \`string\`, got \`${typeof jsonString}\``);
+ }
+
+ const strip = options.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace;
+ let insideString = false;
+ let insideComment = false;
+ let offset = 0;
+ let result = '';
+
+ for (let i = 0; i < jsonString.length; i++) {
+ const currentCharacter = jsonString[i];
+ const nextCharacter = jsonString[i + 1];
+
+ if (!insideComment && currentCharacter === '"') {
+ const escaped = isEscaped(jsonString, i);
+
+ if (!escaped) {
+ insideString = !insideString;
+ }
+ }
+
+ if (insideString) {
+ continue;
+ }
+
+ if (!insideComment && currentCharacter + nextCharacter === '//') {
+ result += jsonString.slice(offset, i);
+ offset = i;
+ insideComment = singleComment;
+ i++;
+ } else if (insideComment === singleComment && currentCharacter + nextCharacter === '\r\n') {
+ i++;
+ insideComment = false;
+ result += strip(jsonString, offset, i);
+ offset = i;
+ continue;
+ } else if (insideComment === singleComment && currentCharacter === '\n') {
+ insideComment = false;
+ result += strip(jsonString, offset, i);
+ offset = i;
+ } else if (!insideComment && currentCharacter + nextCharacter === '/*') {
+ result += jsonString.slice(offset, i);
+ offset = i;
+ insideComment = multiComment;
+ i++;
+ continue;
+ } else if (insideComment === multiComment && currentCharacter + nextCharacter === '*/') {
+ i++;
+ insideComment = false;
+ result += strip(jsonString, offset, i + 1);
+ offset = i + 1;
+ continue;
+ }
+ }
+
+ return result + (insideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
+};
+
+/***/ }),
+/* 982 */
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("os");
+
+/***/ }),
+/* 983 */
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("url");
+
+/***/ }),
+/* 984 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+/**
+ * @fileoverview `FileEnumerator` class.
+ *
+ * `FileEnumerator` class has two responsibilities:
+ *
+ * 1. Find target files by processing glob patterns.
+ * 2. Tie each target file and appropriate configuration.
+ *
+ * It provides a method:
+ *
+ * - `iterateFiles(patterns)`
+ * Iterate files which are matched by given patterns together with the
+ * corresponded configuration. This is for `CLIEngine#executeOnFiles()`.
+ * While iterating files, it loads the configuration file of each directory
+ * before iterate files on the directory, so we can use the configuration
+ * files to determine target files.
+ *
+ * @example
+ * const enumerator = new FileEnumerator();
+ * const linter = new Linter();
+ *
+ * for (const { config, filePath } of enumerator.iterateFiles(["*.js"])) {
+ * const code = fs.readFileSync(filePath, "utf8");
+ * const messages = linter.verify(code, config, filePath);
+ *
+ * console.log(messages);
+ * }
+ *
+ * @author Toru Nagashima <https://github.com/mysticatea>
+ */
+ //------------------------------------------------------------------------------
+// Requirements
+//------------------------------------------------------------------------------
+
+const fs = __webpack_require__(971);
+
+const path = __webpack_require__(501);
+
+const getGlobParent = __webpack_require__(985);
+
+const isGlob = __webpack_require__(986);
+
+const escapeRegExp = __webpack_require__(595);
+
+const {
+ Minimatch
+} = __webpack_require__(953);
+
+const {
+ Legacy: {
+ IgnorePattern,
+ CascadingConfigArrayFactory
+ }
+} = __webpack_require__(974);
+
+const debug = __webpack_require__(566)("eslint:file-enumerator"); //------------------------------------------------------------------------------
+// Helpers
+//------------------------------------------------------------------------------
+
+
+const minimatchOpts = {
+ dot: true,
+ matchBase: true
+};
+const dotfilesPattern = /(?:(?:^\.)|(?:[/\\]\.))[^/\\.].*/u;
+const NONE = 0;
+const IGNORED_SILENTLY = 1;
+const IGNORED = 2; // For VSCode intellisense
+
+/** @typedef {ReturnType<CascadingConfigArrayFactory.getConfigArrayForFile>} ConfigArray */
+
+/**
+ * @typedef {Object} FileEnumeratorOptions
+ * @property {CascadingConfigArrayFactory} [configArrayFactory] The factory for config arrays.
+ * @property {string} [cwd] The base directory to start lookup.
+ * @property {string[]} [extensions] The extensions to match files for directory patterns.
+ * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file.
+ * @property {boolean} [ignore] The flag to check ignored files.
+ * @property {string[]} [rulePaths] The value of `--rulesdir` option.
+ */
+
+/**
+ * @typedef {Object} FileAndConfig
+ * @property {string} filePath The path to a target file.
+ * @property {ConfigArray} config The config entries of that file.
+ * @property {boolean} ignored If `true` then this file should be ignored and warned because it was directly specified.
+ */
+
+/**
+ * @typedef {Object} FileEntry
+ * @property {string} filePath The path to a target file.
+ * @property {ConfigArray} config The config entries of that file.
+ * @property {NONE|IGNORED_SILENTLY|IGNORED} flag The flag.
+ * - `NONE` means the file is a target file.
+ * - `IGNORED_SILENTLY` means the file should be ignored silently.
+ * - `IGNORED` means the file should be ignored and warned because it was directly specified.
+ */
+
+/**
+ * @typedef {Object} FileEnumeratorInternalSlots
+ * @property {CascadingConfigArrayFactory} configArrayFactory The factory for config arrays.
+ * @property {string} cwd The base directory to start lookup.
+ * @property {RegExp|null} extensionRegExp The RegExp to test if a string ends with specific file extensions.
+ * @property {boolean} globInputPaths Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file.
+ * @property {boolean} ignoreFlag The flag to check ignored files.
+ * @property {(filePath:string, dot:boolean) => boolean} defaultIgnores The default predicate function to ignore files.
+ */
+
+/** @type {WeakMap<FileEnumerator, FileEnumeratorInternalSlots>} */
+
+const internalSlotsMap = new WeakMap();
+/**
+ * Check if a string is a glob pattern or not.
+ * @param {string} pattern A glob pattern.
+ * @returns {boolean} `true` if the string is a glob pattern.
+ */
+
+function isGlobPattern(pattern) {
+ return isGlob(path.sep === "\\" ? pattern.replace(/\\/gu, "/") : pattern);
+}
+/**
+ * Get stats of a given path.
+ * @param {string} filePath The path to target file.
+ * @throws {Error} As may be thrown by `fs.statSync`.
+ * @returns {fs.Stats|null} The stats.
+ * @private
+ */
+
+
+function statSafeSync(filePath) {
+ try {
+ return fs.statSync(filePath);
+ } catch (error) {
+ /* c8 ignore next */
+ if (error.code !== "ENOENT") {
+ throw error;
+ }
+
+ return null;
+ }
+}
+/**
+ * Get filenames in a given path to a directory.
+ * @param {string} directoryPath The path to target directory.
+ * @throws {Error} As may be thrown by `fs.readdirSync`.
+ * @returns {import("fs").Dirent[]} The filenames.
+ * @private
+ */
+
+
+function readdirSafeSync(directoryPath) {
+ try {
+ return fs.readdirSync(directoryPath, {
+ withFileTypes: true
+ });
+ } catch (error) {
+ /* c8 ignore next */
+ if (error.code !== "ENOENT") {
+ throw error;
+ }
+
+ return [];
+ }
+}
+/**
+ * Create a `RegExp` object to detect extensions.
+ * @param {string[] | null} extensions The extensions to create.
+ * @returns {RegExp | null} The created `RegExp` object or null.
+ */
+
+
+function createExtensionRegExp(extensions) {
+ if (extensions) {
+ const normalizedExts = extensions.map(ext => escapeRegExp(ext.startsWith(".") ? ext.slice(1) : ext));
+ return new RegExp(`.\\.(?:${normalizedExts.join("|")})$`, "u");
+ }
+
+ return null;
+}
+/**
+ * The error type when no files match a glob.
+ */
+
+
+class NoFilesFoundError extends Error {
+ /**
+ * @param {string} pattern The glob pattern which was not found.
+ * @param {boolean} globDisabled If `true` then the pattern was a glob pattern, but glob was disabled.
+ */
+ constructor(pattern, globDisabled) {
+ super(`No files matching '${pattern}' were found${globDisabled ? " (glob was disabled)" : ""}.`);
+ this.messageTemplate = "file-not-found";
+ this.messageData = {
+ pattern,
+ globDisabled
+ };
+ }
+
+}
+/**
+ * The error type when there are files matched by a glob, but all of them have been ignored.
+ */
+
+
+class AllFilesIgnoredError extends Error {
+ /**
+ * @param {string} pattern The glob pattern which was not found.
+ */
+ constructor(pattern) {
+ super(`All files matched by '${pattern}' are ignored.`);
+ this.messageTemplate = "all-files-ignored";
+ this.messageData = {
+ pattern
+ };
+ }
+
+}
+/**
+ * This class provides the functionality that enumerates every file which is
+ * matched by given glob patterns and that configuration.
+ */
+
+
+class FileEnumerator {
+ /**
+ * Initialize this enumerator.
+ * @param {FileEnumeratorOptions} options The options.
+ */
+ constructor() {
+ let {
+ cwd = process.cwd(),
+ configArrayFactory = new CascadingConfigArrayFactory({
+ cwd,
+ getEslintRecommendedConfig: () => __webpack_require__(966),
+ getEslintAllConfig: () => __webpack_require__(967)
+ }),
+ extensions = null,
+ globInputPaths = true,
+ errorOnUnmatchedPattern = true,
+ ignore = true
+ } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+ internalSlotsMap.set(this, {
+ configArrayFactory,
+ cwd,
+ defaultIgnores: IgnorePattern.createDefaultIgnore(cwd),
+ extensionRegExp: createExtensionRegExp(extensions),
+ globInputPaths,
+ errorOnUnmatchedPattern,
+ ignoreFlag: ignore
+ });
+ }
+ /**
+ * Check if a given file is target or not.
+ * @param {string} filePath The path to a candidate file.
+ * @param {ConfigArray} [providedConfig] Optional. The configuration for the file.
+ * @returns {boolean} `true` if the file is a target.
+ */
+
+
+ isTargetPath(filePath, providedConfig) {
+ const {
+ configArrayFactory,
+ extensionRegExp
+ } = internalSlotsMap.get(this); // If `--ext` option is present, use it.
+
+ if (extensionRegExp) {
+ return extensionRegExp.test(filePath);
+ } // `.js` file is target by default.
+
+
+ if (filePath.endsWith(".js")) {
+ return true;
+ } // use `overrides[].files` to check additional targets.
+
+
+ const config = providedConfig || configArrayFactory.getConfigArrayForFile(filePath, {
+ ignoreNotFoundError: true
+ });
+ return config.isAdditionalTargetPath(filePath);
+ }
+ /**
+ * Iterate files which are matched by given glob patterns.
+ * @param {string|string[]} patternOrPatterns The glob patterns to iterate files.
+ * @throws {NoFilesFoundError|AllFilesIgnoredError} On an unmatched pattern.
+ * @returns {IterableIterator<FileAndConfig>} The found files.
+ */
+
+
+ *iterateFiles(patternOrPatterns) {
+ const {
+ globInputPaths,
+ errorOnUnmatchedPattern
+ } = internalSlotsMap.get(this);
+ const patterns = Array.isArray(patternOrPatterns) ? patternOrPatterns : [patternOrPatterns];
+ debug("Start to iterate files: %o", patterns); // The set of paths to remove duplicate.
+
+ const set = new Set();
+
+ for (const pattern of patterns) {
+ let foundRegardlessOfIgnored = false;
+ let found = false; // Skip empty string.
+
+ if (!pattern) {
+ continue;
+ } // Iterate files of this pattern.
+
+
+ for (const {
+ config,
+ filePath,
+ flag
+ } of this._iterateFiles(pattern)) {
+ foundRegardlessOfIgnored = true;
+
+ if (flag === IGNORED_SILENTLY) {
+ continue;
+ }
+
+ found = true; // Remove duplicate paths while yielding paths.
+
+ if (!set.has(filePath)) {
+ set.add(filePath);
+ yield {
+ config,
+ filePath,
+ ignored: flag === IGNORED
+ };
+ }
+ } // Raise an error if any files were not found.
+
+
+ if (errorOnUnmatchedPattern) {
+ if (!foundRegardlessOfIgnored) {
+ throw new NoFilesFoundError(pattern, !globInputPaths && isGlob(pattern));
+ }
+
+ if (!found) {
+ throw new AllFilesIgnoredError(pattern);
+ }
+ }
+ }
+
+ debug(`Complete iterating files: ${JSON.stringify(patterns)}`);
+ }
+ /**
+ * Iterate files which are matched by a given glob pattern.
+ * @param {string} pattern The glob pattern to iterate files.
+ * @returns {IterableIterator<FileEntry>} The found files.
+ */
+
+
+ _iterateFiles(pattern) {
+ const {
+ cwd,
+ globInputPaths
+ } = internalSlotsMap.get(this);
+ const absolutePath = path.resolve(cwd, pattern);
+ const isDot = dotfilesPattern.test(pattern);
+ const stat = statSafeSync(absolutePath);
+
+ if (stat && stat.isDirectory()) {
+ return this._iterateFilesWithDirectory(absolutePath, isDot);
+ }
+
+ if (stat && stat.isFile()) {
+ return this._iterateFilesWithFile(absolutePath);
+ }
+
+ if (globInputPaths && isGlobPattern(pattern)) {
+ return this._iterateFilesWithGlob(absolutePath, isDot);
+ }
+
+ return [];
+ }
+ /**
+ * Iterate a file which is matched by a given path.
+ * @param {string} filePath The path to the target file.
+ * @returns {IterableIterator<FileEntry>} The found files.
+ * @private
+ */
+
+
+ _iterateFilesWithFile(filePath) {
+ debug(`File: ${filePath}`);
+ const {
+ configArrayFactory
+ } = internalSlotsMap.get(this);
+ const config = configArrayFactory.getConfigArrayForFile(filePath);
+
+ const ignored = this._isIgnoredFile(filePath, {
+ config,
+ direct: true
+ });
+
+ const flag = ignored ? IGNORED : NONE;
+ return [{
+ config,
+ filePath,
+ flag
+ }];
+ }
+ /**
+ * Iterate files in a given path.
+ * @param {string} directoryPath The path to the target directory.
+ * @param {boolean} dotfiles If `true` then it doesn't skip dot files by default.
+ * @returns {IterableIterator<FileEntry>} The found files.
+ * @private
+ */
+
+
+ _iterateFilesWithDirectory(directoryPath, dotfiles) {
+ debug(`Directory: ${directoryPath}`);
+ return this._iterateFilesRecursive(directoryPath, {
+ dotfiles,
+ recursive: true,
+ selector: null
+ });
+ }
+ /**
+ * Iterate files which are matched by a given glob pattern.
+ * @param {string} pattern The glob pattern to iterate files.
+ * @param {boolean} dotfiles If `true` then it doesn't skip dot files by default.
+ * @returns {IterableIterator<FileEntry>} The found files.
+ * @private
+ */
+
+
+ _iterateFilesWithGlob(pattern, dotfiles) {
+ debug(`Glob: ${pattern}`);
+ const directoryPath = path.resolve(getGlobParent(pattern));
+ const globPart = pattern.slice(directoryPath.length + 1);
+ /*
+ * recursive if there are `**` or path separators in the glob part.
+ * Otherwise, patterns such as `src/*.js`, it doesn't need recursive.
+ */
+
+ const recursive = /\*\*|\/|\\/u.test(globPart);
+ const selector = new Minimatch(pattern, minimatchOpts);
+ debug(`recursive? ${recursive}`);
+ return this._iterateFilesRecursive(directoryPath, {
+ dotfiles,
+ recursive,
+ selector
+ });
+ }
+ /**
+ * Iterate files in a given path.
+ * @param {string} directoryPath The path to the target directory.
+ * @param {Object} options The options to iterate files.
+ * @param {boolean} [options.dotfiles] If `true` then it doesn't skip dot files by default.
+ * @param {boolean} [options.recursive] If `true` then it dives into sub directories.
+ * @param {InstanceType<Minimatch>} [options.selector] The matcher to choose files.
+ * @returns {IterableIterator<FileEntry>} The found files.
+ * @private
+ */
+
+
+ *_iterateFilesRecursive(directoryPath, options) {
+ debug(`Enter the directory: ${directoryPath}`);
+ const {
+ configArrayFactory
+ } = internalSlotsMap.get(this);
+ /** @type {ConfigArray|null} */
+
+ let config = null; // Enumerate the files of this directory.
+
+ for (const entry of readdirSafeSync(directoryPath)) {
+ const filePath = path.join(directoryPath, entry.name);
+ const fileInfo = entry.isSymbolicLink() ? statSafeSync(filePath) : entry;
+
+ if (!fileInfo) {
+ continue;
+ } // Check if the file is matched.
+
+
+ if (fileInfo.isFile()) {
+ if (!config) {
+ config = configArrayFactory.getConfigArrayForFile(filePath,
+ /*
+ * We must ignore `ConfigurationNotFoundError` at this
+ * point because we don't know if target files exist in
+ * this directory.
+ */
+ {
+ ignoreNotFoundError: true
+ });
+ }
+
+ const matched = options.selector // Started with a glob pattern; choose by the pattern.
+ ? options.selector.match(filePath) // Started with a directory path; choose by file extensions.
+ : this.isTargetPath(filePath, config);
+
+ if (matched) {
+ const ignored = this._isIgnoredFile(filePath, { ...options,
+ config
+ });
+
+ const flag = ignored ? IGNORED_SILENTLY : NONE;
+ debug(`Yield: ${entry.name}${ignored ? " but ignored" : ""}`);
+ yield {
+ config: configArrayFactory.getConfigArrayForFile(filePath),
+ filePath,
+ flag
+ };
+ } else {
+ debug(`Didn't match: ${entry.name}`);
+ } // Dive into the sub directory.
+
+ } else if (options.recursive && fileInfo.isDirectory()) {
+ if (!config) {
+ config = configArrayFactory.getConfigArrayForFile(filePath, {
+ ignoreNotFoundError: true
+ });
+ }
+
+ const ignored = this._isIgnoredFile(filePath + path.sep, { ...options,
+ config
+ });
+
+ if (!ignored) {
+ yield* this._iterateFilesRecursive(filePath, options);
+ }
+ }
+ }
+
+ debug(`Leave the directory: ${directoryPath}`);
+ }
+ /**
+ * Check if a given file should be ignored.
+ * @param {string} filePath The path to a file to check.
+ * @param {Object} options Options
+ * @param {ConfigArray} [options.config] The config for this file.
+ * @param {boolean} [options.dotfiles] If `true` then this is not ignore dot files by default.
+ * @param {boolean} [options.direct] If `true` then this is a direct specified file.
+ * @returns {boolean} `true` if the file should be ignored.
+ * @private
+ */
+
+
+ _isIgnoredFile(filePath, _ref) {
+ let {
+ config: providedConfig,
+ dotfiles = false,
+ direct = false
+ } = _ref;
+ const {
+ configArrayFactory,
+ defaultIgnores,
+ ignoreFlag
+ } = internalSlotsMap.get(this);
+
+ if (ignoreFlag) {
+ const config = providedConfig || configArrayFactory.getConfigArrayForFile(filePath, {
+ ignoreNotFoundError: true
+ });
+ const ignores = config.extractConfig(filePath).ignores || defaultIgnores;
+ return ignores(filePath, dotfiles);
+ }
+
+ return !direct && defaultIgnores(filePath, dotfiles);
+ }
+
+} //------------------------------------------------------------------------------
+// Public Interface
+//------------------------------------------------------------------------------
+
+
+module.exports = {
+ FileEnumerator
+};
+
+/***/ }),
+/* 985 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+
+
+var isGlob = __webpack_require__(986);
+
+var pathPosixDirname = (__webpack_require__(501).posix.dirname);
+
+var isWin32 = (__webpack_require__(982).platform)() === 'win32';
+var slash = '/';
+var backslash = /\\/g;
+var escaped = /\\([!*?|[\](){}])/g;
+/**
+ * @param {string} str
+ * @param {Object} opts
+ * @param {boolean} [opts.flipBackslashes=true]
+ */
+
+module.exports = function globParent(str, opts) {
+ var options = Object.assign({
+ flipBackslashes: true
+ }, opts); // flip windows path separators
+
+ if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
+ str = str.replace(backslash, slash);
+ } // special case for strings ending in enclosure containing path separator
+
+
+ if (isEnclosure(str)) {
+ str += slash;
+ } // preserves full path in case of trailing path separator
+
+
+ str += 'a'; // remove path parts that are globby
+
+ do {
+ str = pathPosixDirname(str);
+ } while (isGlobby(str)); // remove escape chars and return result
+
+
+ return str.replace(escaped, '$1');
+};
+
+function isEnclosure(str) {
+ var lastChar = str.slice(-1);
+ var enclosureStart;
+
+ switch (lastChar) {
+ case '}':
+ enclosureStart = '{';
+ break;
+
+ case ']':
+ enclosureStart = '[';
+ break;
+
+ default:
+ return false;
+ }
+
+ var foundIndex = str.indexOf(enclosureStart);
+
+ if (foundIndex < 0) {
+ return false;
+ }
+
+ return str.slice(foundIndex + 1, -1).includes(slash);
+}
+
+function isGlobby(str) {
+ if (/\([^()]+$/.test(str)) {
+ return true;
+ }
+
+ if (str[0] === '{' || str[0] === '[') {
+ return true;
+ }
+
+ if (/[^\\][{[]/.test(str)) {
+ return true;
+ }
+
+ return isGlob(str);
+}
+
+/***/ }),
+/* 986 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+/*!
+ * is-glob <https://github.com/jonschlinkert/is-glob>
+ *
+ * Copyright (c) 2014-2017, Jon Schlinkert.
+ * Released under the MIT License.
+ */
+var isExtglob = __webpack_require__(987);
+
+var chars = {
+ '{': '}',
+ '(': ')',
+ '[': ']'
+};
+
+var strictCheck = function (str) {
+ if (str[0] === '!') {
+ return true;
+ }
+
+ var index = 0;
+ var pipeIndex = -2;
+ var closeSquareIndex = -2;
+ var closeCurlyIndex = -2;
+ var closeParenIndex = -2;
+ var backSlashIndex = -2;
+
+ while (index < str.length) {
+ if (str[index] === '*') {
+ return true;
+ }
+
+ if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) {
+ return true;
+ }
+
+ if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') {
+ if (closeSquareIndex < index) {
+ closeSquareIndex = str.indexOf(']', index);
+ }
+
+ if (closeSquareIndex > index) {
+ if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
+ return true;
+ }
+
+ backSlashIndex = str.indexOf('\\', index);
+
+ if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
+ return true;
+ }
+ }
+ }
+
+ if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') {
+ closeCurlyIndex = str.indexOf('}', index);
+
+ if (closeCurlyIndex > index) {
+ backSlashIndex = str.indexOf('\\', index);
+
+ if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {
+ return true;
+ }
+ }
+ }
+
+ if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') {
+ closeParenIndex = str.indexOf(')', index);
+
+ if (closeParenIndex > index) {
+ backSlashIndex = str.indexOf('\\', index);
+
+ if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
+ return true;
+ }
+ }
+ }
+
+ if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {
+ if (pipeIndex < index) {
+ pipeIndex = str.indexOf('|', index);
+ }
+
+ if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {
+ closeParenIndex = str.indexOf(')', pipeIndex);
+
+ if (closeParenIndex > pipeIndex) {
+ backSlashIndex = str.indexOf('\\', pipeIndex);
+
+ if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
+ return true;
+ }
+ }
+ }
+ }
+
+ if (str[index] === '\\') {
+ var open = str[index + 1];
+ index += 2;
+ var close = chars[open];
+
+ if (close) {
+ var n = str.indexOf(close, index);
+
+ if (n !== -1) {
+ index = n + 1;
+ }
+ }
+
+ if (str[index] === '!') {
+ return true;
+ }
+ } else {
+ index++;
+ }
+ }
+
+ return false;
+};
+
+var relaxedCheck = function (str) {
+ if (str[0] === '!') {
+ return true;
+ }
+
+ var index = 0;
+
+ while (index < str.length) {
+ if (/[*?{}()[\]]/.test(str[index])) {
+ return true;
+ }
+
+ if (str[index] === '\\') {
+ var open = str[index + 1];
+ index += 2;
+ var close = chars[open];
+
+ if (close) {
+ var n = str.indexOf(close, index);
+
+ if (n !== -1) {
+ index = n + 1;
+ }
+ }
+
+ if (str[index] === '!') {
+ return true;
+ }
+ } else {
+ index++;
+ }
+ }
+
+ return false;
+};
+
+module.exports = function isGlob(str, options) {
+ if (typeof str !== 'string' || str === '') {
+ return false;
+ }
+
+ if (isExtglob(str)) {
+ return true;
+ }
+
+ var check = strictCheck; // optionally relax check
+
+ if (options && options.strict === false) {
+ check = relaxedCheck;
+ }
+
+ return check(str);
+};
+
+/***/ }),
+/* 987 */
+/***/ ((module) => {
+
+/*!
+ * is-extglob <https://github.com/jonschlinkert/is-extglob>
+ *
+ * Copyright (c) 2014-2016, Jon Schlinkert.
+ * Licensed under the MIT License.
+ */
+module.exports = function isExtglob(str) {
+ if (typeof str !== 'string' || str === '') {
+ return false;
+ }
+
+ var match;
+
+ while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) {
+ if (match[2]) return true;
+ str = str.slice(match.index + match[0].length);
+ }
+
+ return false;
+};
+
+/***/ }),
+/* 988 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+
+
+const {
+ Linter
+} = __webpack_require__(500);
+
+const interpolate = __webpack_require__(613);
+
+const SourceCodeFixer = __webpack_require__(947);
+
+module.exports = {
+ Linter,
+ // For testers.
+ SourceCodeFixer,
+ interpolate
+};
+
+/***/ }),
+/* 989 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+/**
+ * @fileoverview Module for loading rules from files and directories.
+ * @author Michael Ficarra
+ */
+ //------------------------------------------------------------------------------
+// Requirements
+//------------------------------------------------------------------------------
+
+const fs = __webpack_require__(971),
+ path = __webpack_require__(501);
+
+const rulesDirCache = {}; //------------------------------------------------------------------------------
+// Public Interface
+//------------------------------------------------------------------------------
+
+/**
+ * Load all rule modules from specified directory.
+ * @param {string} relativeRulesDir Path to rules directory, may be relative.
+ * @param {string} cwd Current working directory
+ * @returns {Object} Loaded rule modules.
+ */
+
+module.exports = function (relativeRulesDir, cwd) {
+ const rulesDir = path.resolve(cwd, relativeRulesDir); // cache will help performance as IO operation are expensive
+
+ if (rulesDirCache[rulesDir]) {
+ return rulesDirCache[rulesDir];
+ }
+
+ const rules = Object.create(null);
+ fs.readdirSync(rulesDir).forEach(file => {
+ if (path.extname(file) !== ".js") {
+ return;
+ }
+
+ rules[file.slice(0, -3)] = __webpack_require__(990)(path.join(rulesDir, file));
+ });
+ rulesDirCache[rulesDir] = rules;
+ return rules;
+};
+
+/***/ }),
+/* 990 */
+/***/ ((module) => {
+
+function webpackEmptyContext(req) {
+ var e = new Error("Cannot find module '" + req + "'");
+ e.code = 'MODULE_NOT_FOUND';
+ throw e;
+}
+webpackEmptyContext.keys = () => ([]);
+webpackEmptyContext.resolve = webpackEmptyContext;
+webpackEmptyContext.id = 990;
+module.exports = webpackEmptyContext;
+
+/***/ }),
+/* 991 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+/**
+ * @fileoverview Defining the hashing function in one place.
+ * @author Michael Ficarra
+ */
+ //------------------------------------------------------------------------------
+// Requirements
+//------------------------------------------------------------------------------
+
+const murmur = __webpack_require__(992); //------------------------------------------------------------------------------
+// Helpers
+//------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
+// Private
+//------------------------------------------------------------------------------
+
+/**
+ * hash the given string
+ * @param {string} str the string to hash
+ * @returns {string} the hash
+ */
+
+
+function hash(str) {
+ return murmur(str).result().toString(36);
+} //------------------------------------------------------------------------------
+// Public Interface
+//------------------------------------------------------------------------------
+
+
+module.exports = hash;
+
+/***/ }),
+/* 992 */
+/***/ ((module) => {
+
+/**
+ * @preserve
+ * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013)
+ *
+ * @author <a href="mailto:jensyt@gmail.com">Jens Taylor</a>
+ * @see http://github.com/homebrewing/brauhaus-diff
+ * @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
+ * @see http://github.com/garycourt/murmurhash-js
+ * @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a>
+ * @see http://sites.google.com/site/murmurhash/
+ */
+(function () {
+ var cache; // Call this function without `new` to use the cached object (good for
+ // single-threaded environments), or with `new` to create a new object.
+ //
+ // @param {string} key A UTF-16 or ASCII string
+ // @param {number} seed An optional positive integer
+ // @return {object} A MurmurHash3 object for incremental hashing
+
+ function MurmurHash3(key, seed) {
+ var m = this instanceof MurmurHash3 ? this : cache;
+ m.reset(seed);
+
+ if (typeof key === 'string' && key.length > 0) {
+ m.hash(key);
+ }
+
+ if (m !== this) {
+ return m;
+ }
+ }
+
+ ; // Incrementally add a string to this hash
+ //
+ // @param {string} key A UTF-16 or ASCII string
+ // @return {object} this
+
+ MurmurHash3.prototype.hash = function (key) {
+ var h1, k1, i, top, len;
+ len = key.length;
+ this.len += len;
+ k1 = this.k1;
+ i = 0;
+
+ switch (this.rem) {
+ case 0:
+ k1 ^= len > i ? key.charCodeAt(i++) & 0xffff : 0;
+
+ case 1:
+ k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 8 : 0;
+
+ case 2:
+ k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 16 : 0;
+
+ case 3:
+ k1 ^= len > i ? (key.charCodeAt(i) & 0xff) << 24 : 0;
+ k1 ^= len > i ? (key.charCodeAt(i++) & 0xff00) >> 8 : 0;
+ }
+
+ this.rem = len + this.rem & 3; // & 3 is same as % 4
+
+ len -= this.rem;
+
+ if (len > 0) {
+ h1 = this.h1;
+
+ while (1) {
+ k1 = k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000 & 0xffffffff;
+ k1 = k1 << 15 | k1 >>> 17;
+ k1 = k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000 & 0xffffffff;
+ h1 ^= k1;
+ h1 = h1 << 13 | h1 >>> 19;
+ h1 = h1 * 5 + 0xe6546b64 & 0xffffffff;
+
+ if (i >= len) {
+ break;
+ }
+
+ k1 = key.charCodeAt(i++) & 0xffff ^ (key.charCodeAt(i++) & 0xffff) << 8 ^ (key.charCodeAt(i++) & 0xffff) << 16;
+ top = key.charCodeAt(i++);
+ k1 ^= (top & 0xff) << 24 ^ (top & 0xff00) >> 8;
+ }
+
+ k1 = 0;
+
+ switch (this.rem) {
+ case 3:
+ k1 ^= (key.charCodeAt(i + 2) & 0xffff) << 16;
+
+ case 2:
+ k1 ^= (key.charCodeAt(i + 1) & 0xffff) << 8;
+
+ case 1:
+ k1 ^= key.charCodeAt(i) & 0xffff;
+ }
+
+ this.h1 = h1;
+ }
+
+ this.k1 = k1;
+ return this;
+ }; // Get the result of this hash
+ //
+ // @return {number} The 32-bit hash
+
+
+ MurmurHash3.prototype.result = function () {
+ var k1, h1;
+ k1 = this.k1;
+ h1 = this.h1;
+
+ if (k1 > 0) {
+ k1 = k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000 & 0xffffffff;
+ k1 = k1 << 15 | k1 >>> 17;
+ k1 = k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000 & 0xffffffff;
+ h1 ^= k1;
+ }
+
+ h1 ^= this.len;
+ h1 ^= h1 >>> 16;
+ h1 = h1 * 0xca6b + (h1 & 0xffff) * 0x85eb0000 & 0xffffffff;
+ h1 ^= h1 >>> 13;
+ h1 = h1 * 0xae35 + (h1 & 0xffff) * 0xc2b20000 & 0xffffffff;
+ h1 ^= h1 >>> 16;
+ return h1 >>> 0;
+ }; // Reset the hash object for reuse
+ //
+ // @param {number} seed An optional positive integer
+
+
+ MurmurHash3.prototype.reset = function (seed) {
+ this.h1 = typeof seed === 'number' ? seed : 0;
+ this.rem = this.k1 = this.len = 0;
+ return this;
+ }; // A cached object to use. This can be safely used if you're in a single-
+ // threaded environment, otherwise you need to create new hashes to use.
+
+
+ cache = new MurmurHash3();
+
+ if (true) {
+ module.exports = MurmurHash3;
+ } else {}
+})();
+
+/***/ }),
+/* 993 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+/**
+ * @fileoverview Utility for caching lint results.
+ * @author Kevin Partington
+ */
+ //-----------------------------------------------------------------------------
+// Requirements
+//-----------------------------------------------------------------------------
+
+const assert = __webpack_require__(503);
+
+const fs = __webpack_require__(971);
+
+const fileEntryCache = __webpack_require__(994);
+
+const stringify = __webpack_require__(1012);
+
+const pkg = __webpack_require__(513);
+
+const hash = __webpack_require__(991);
+
+const debug = __webpack_require__(566)("eslint:lint-result-cache"); //-----------------------------------------------------------------------------
+// Helpers
+//-----------------------------------------------------------------------------
+
+
+const configHashCache = new WeakMap();
+const nodeVersion = process && process.version;
+const validCacheStrategies = ["metadata", "content"];
+const invalidCacheStrategyErrorMessage = `Cache strategy must be one of: ${validCacheStrategies.map(strategy => `"${strategy}"`).join(", ")}`;
+/**
+ * Tests whether a provided cacheStrategy is valid
+ * @param {string} cacheStrategy The cache strategy to use
+ * @returns {boolean} true if `cacheStrategy` is one of `validCacheStrategies`; false otherwise
+ */
+
+function isValidCacheStrategy(cacheStrategy) {
+ return validCacheStrategies.includes(cacheStrategy);
+}
+/**
+ * Calculates the hash of the config
+ * @param {ConfigArray} config The config.
+ * @returns {string} The hash of the config
+ */
+
+
+function hashOfConfigFor(config) {
+ if (!configHashCache.has(config)) {
+ configHashCache.set(config, hash(`${pkg.version}_${nodeVersion}_${stringify(config)}`));
+ }
+
+ return configHashCache.get(config);
+} //-----------------------------------------------------------------------------
+// Public Interface
+//-----------------------------------------------------------------------------
+
+/**
+ * Lint result cache. This wraps around the file-entry-cache module,
+ * transparently removing properties that are difficult or expensive to
+ * serialize and adding them back in on retrieval.
+ */
+
+
+class LintResultCache {
+ /**
+ * Creates a new LintResultCache instance.
+ * @param {string} cacheFileLocation The cache file location.
+ * @param {"metadata" | "content"} cacheStrategy The cache strategy to use.
+ */
+ constructor(cacheFileLocation, cacheStrategy) {
+ assert(cacheFileLocation, "Cache file location is required");
+ assert(cacheStrategy, "Cache strategy is required");
+ assert(isValidCacheStrategy(cacheStrategy), invalidCacheStrategyErrorMessage);
+ debug(`Caching results to ${cacheFileLocation}`);
+ const useChecksum = cacheStrategy === "content";
+ debug(`Using "${cacheStrategy}" strategy to detect changes`);
+ this.fileEntryCache = fileEntryCache.create(cacheFileLocation, void 0, useChecksum);
+ this.cacheFileLocation = cacheFileLocation;
+ }
+ /**
+ * Retrieve cached lint results for a given file path, if present in the
+ * cache. If the file is present and has not been changed, rebuild any
+ * missing result information.
+ * @param {string} filePath The file for which to retrieve lint results.
+ * @param {ConfigArray} config The config of the file.
+ * @returns {Object|null} The rebuilt lint results, or null if the file is
+ * changed or not in the filesystem.
+ */
+
+
+ getCachedLintResults(filePath, config) {
+ /*
+ * Cached lint results are valid if and only if:
+ * 1. The file is present in the filesystem
+ * 2. The file has not changed since the time it was previously linted
+ * 3. The ESLint configuration has not changed since the time the file
+ * was previously linted
+ * If any of these are not true, we will not reuse the lint results.
+ */
+ const fileDescriptor = this.fileEntryCache.getFileDescriptor(filePath);
+ const hashOfConfig = hashOfConfigFor(config);
+ const changed = fileDescriptor.changed || fileDescriptor.meta.hashOfConfig !== hashOfConfig;
+
+ if (fileDescriptor.notFound) {
+ debug(`File not found on the file system: ${filePath}`);
+ return null;
+ }
+
+ if (changed) {
+ debug(`Cache entry not found or no longer valid: ${filePath}`);
+ return null;
+ } // If source is present but null, need to reread the file from the filesystem.
+
+
+ if (fileDescriptor.meta.results && fileDescriptor.meta.results.source === null) {
+ debug(`Rereading cached result source from filesystem: ${filePath}`);
+ fileDescriptor.meta.results.source = fs.readFileSync(filePath, "utf-8");
+ }
+
+ return fileDescriptor.meta.results;
+ }
+ /**
+ * Set the cached lint results for a given file path, after removing any
+ * information that will be both unnecessary and difficult to serialize.
+ * Avoids caching results with an "output" property (meaning fixes were
+ * applied), to prevent potentially incorrect results if fixes are not
+ * written to disk.
+ * @param {string} filePath The file for which to set lint results.
+ * @param {ConfigArray} config The config of the file.
+ * @param {Object} result The lint result to be set for the file.
+ * @returns {void}
+ */
+
+
+ setCachedLintResults(filePath, config, result) {
+ if (result && Object.prototype.hasOwnProperty.call(result, "output")) {
+ return;
+ }
+
+ const fileDescriptor = this.fileEntryCache.getFileDescriptor(filePath);
+
+ if (fileDescriptor && !fileDescriptor.notFound) {
+ debug(`Updating cached result: ${filePath}`); // Serialize the result, except that we want to remove the file source if present.
+
+ const resultToSerialize = Object.assign({}, result);
+ /*
+ * Set result.source to null.
+ * In `getCachedLintResults`, if source is explicitly null, we will
+ * read the file from the filesystem to set the value again.
+ */
+
+ if (Object.prototype.hasOwnProperty.call(resultToSerialize, "source")) {
+ resultToSerialize.source = null;
+ }
+
+ fileDescriptor.meta.results = resultToSerialize;
+ fileDescriptor.meta.hashOfConfig = hashOfConfigFor(config);
+ }
+ }
+ /**
+ * Persists the in-memory cache to disk.
+ * @returns {void}
+ */
+
+
+ reconcile() {
+ debug(`Persisting cached results: ${this.cacheFileLocation}`);
+ this.fileEntryCache.reconcile();
+ }
+
+}
+
+module.exports = LintResultCache;
+
+/***/ }),
+/* 994 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+var path = __webpack_require__(501);
+
+var crypto = __webpack_require__(995);
+
+module.exports = {
+ createFromFile: function (filePath, useChecksum) {
+ var fname = path.basename(filePath);
+ var dir = path.dirname(filePath);
+ return this.create(fname, dir, useChecksum);
+ },
+ create: function (cacheId, _path, useChecksum) {
+ var fs = __webpack_require__(971);
+
+ var flatCache = __webpack_require__(996);
+
+ var cache = flatCache.load(cacheId, _path);
+ var normalizedEntries = {};
+
+ var removeNotFoundFiles = function removeNotFoundFiles() {
+ const cachedEntries = cache.keys(); // remove not found entries
+
+ cachedEntries.forEach(function remover(fPath) {
+ try {
+ fs.statSync(fPath);
+ } catch (err) {
+ if (err.code === 'ENOENT') {
+ cache.removeKey(fPath);
+ }
+ }
+ });
+ };
+
+ removeNotFoundFiles();
+ return {
+ /**
+ * the flat cache storage used to persist the metadata of the `files
+ * @type {Object}
+ */
+ cache: cache,
+
+ /**
+ * Given a buffer, calculate md5 hash of its content.
+ * @method getHash
+ * @param {Buffer} buffer buffer to calculate hash on
+ * @return {String} content hash digest
+ */
+ getHash: function (buffer) {
+ return crypto.createHash('md5').update(buffer).digest('hex');
+ },
+
+ /**
+ * Return whether or not a file has changed since last time reconcile was called.
+ * @method hasFileChanged
+ * @param {String} file the filepath to check
+ * @return {Boolean} wheter or not the file has changed
+ */
+ hasFileChanged: function (file) {
+ return this.getFileDescriptor(file).changed;
+ },
+
+ /**
+ * given an array of file paths it return and object with three arrays:
+ * - changedFiles: Files that changed since previous run
+ * - notChangedFiles: Files that haven't change
+ * - notFoundFiles: Files that were not found, probably deleted
+ *
+ * @param {Array} files the files to analyze and compare to the previous seen files
+ * @return {[type]} [description]
+ */
+ analyzeFiles: function (files) {
+ var me = this;
+ files = files || [];
+ var res = {
+ changedFiles: [],
+ notFoundFiles: [],
+ notChangedFiles: []
+ };
+ me.normalizeEntries(files).forEach(function (entry) {
+ if (entry.changed) {
+ res.changedFiles.push(entry.key);
+ return;
+ }
+
+ if (entry.notFound) {
+ res.notFoundFiles.push(entry.key);
+ return;
+ }
+
+ res.notChangedFiles.push(entry.key);
+ });
+ return res;
+ },
+ getFileDescriptor: function (file) {
+ var fstat;
+
+ try {
+ fstat = fs.statSync(file);
+ } catch (ex) {
+ this.removeEntry(file);
+ return {
+ key: file,
+ notFound: true,
+ err: ex
+ };
+ }
+
+ if (useChecksum) {
+ return this._getFileDescriptorUsingChecksum(file);
+ }
+
+ return this._getFileDescriptorUsingMtimeAndSize(file, fstat);
+ },
+ _getFileDescriptorUsingMtimeAndSize: function (file, fstat) {
+ var meta = cache.getKey(file);
+ var cacheExists = !!meta;
+ var cSize = fstat.size;
+ var cTime = fstat.mtime.getTime();
+ var isDifferentDate;
+ var isDifferentSize;
+
+ if (!meta) {
+ meta = {
+ size: cSize,
+ mtime: cTime
+ };
+ } else {
+ isDifferentDate = cTime !== meta.mtime;
+ isDifferentSize = cSize !== meta.size;
+ }
+
+ var nEntry = normalizedEntries[file] = {
+ key: file,
+ changed: !cacheExists || isDifferentDate || isDifferentSize,
+ meta: meta
+ };
+ return nEntry;
+ },
+ _getFileDescriptorUsingChecksum: function (file) {
+ var meta = cache.getKey(file);
+ var cacheExists = !!meta;
+ var contentBuffer;
+
+ try {
+ contentBuffer = fs.readFileSync(file);
+ } catch (ex) {
+ contentBuffer = '';
+ }
+
+ var isDifferent = true;
+ var hash = this.getHash(contentBuffer);
+
+ if (!meta) {
+ meta = {
+ hash: hash
+ };
+ } else {
+ isDifferent = hash !== meta.hash;
+ }
+
+ var nEntry = normalizedEntries[file] = {
+ key: file,
+ changed: !cacheExists || isDifferent,
+ meta: meta
+ };
+ return nEntry;
+ },
+
+ /**
+ * Return the list o the files that changed compared
+ * against the ones stored in the cache
+ *
+ * @method getUpdated
+ * @param files {Array} the array of files to compare against the ones in the cache
+ * @returns {Array}
+ */
+ getUpdatedFiles: function (files) {
+ var me = this;
+ files = files || [];
+ return me.normalizeEntries(files).filter(function (entry) {
+ return entry.changed;
+ }).map(function (entry) {
+ return entry.key;
+ });
+ },
+
+ /**
+ * return the list of files
+ * @method normalizeEntries
+ * @param files
+ * @returns {*}
+ */
+ normalizeEntries: function (files) {
+ files = files || [];
+ var me = this;
+ var nEntries = files.map(function (file) {
+ return me.getFileDescriptor(file);
+ }); //normalizeEntries = nEntries;
+
+ return nEntries;
+ },
+
+ /**
+ * Remove an entry from the file-entry-cache. Useful to force the file to still be considered
+ * modified the next time the process is run
+ *
+ * @method removeEntry
+ * @param entryName
+ */
+ removeEntry: function (entryName) {
+ delete normalizedEntries[entryName];
+ cache.removeKey(entryName);
+ },
+
+ /**
+ * Delete the cache file from the disk
+ * @method deleteCacheFile
+ */
+ deleteCacheFile: function () {
+ cache.removeCacheFile();
+ },
+
+ /**
+ * remove the cache from the file and clear the memory cache
+ */
+ destroy: function () {
+ normalizedEntries = {};
+ cache.destroy();
+ },
+ _getMetaForFileUsingCheckSum: function (cacheEntry) {
+ var contentBuffer = fs.readFileSync(cacheEntry.key);
+ var hash = this.getHash(contentBuffer);
+ var meta = Object.assign(cacheEntry.meta, {
+ hash: hash
+ });
+ delete meta.size;
+ delete meta.mtime;
+ return meta;
+ },
+ _getMetaForFileUsingMtimeAndSize: function (cacheEntry) {
+ var stat = fs.statSync(cacheEntry.key);
+ var meta = Object.assign(cacheEntry.meta, {
+ size: stat.size,
+ mtime: stat.mtime.getTime()
+ });
+ delete meta.hash;
+ return meta;
+ },
+
+ /**
+ * Sync the files and persist them to the cache
+ * @method reconcile
+ */
+ reconcile: function (noPrune) {
+ removeNotFoundFiles();
+ noPrune = typeof noPrune === 'undefined' ? true : noPrune;
+ var entries = normalizedEntries;
+ var keys = Object.keys(entries);
+
+ if (keys.length === 0) {
+ return;
+ }
+
+ var me = this;
+ keys.forEach(function (entryName) {
+ var cacheEntry = entries[entryName];
+
+ try {
+ var meta = useChecksum ? me._getMetaForFileUsingCheckSum(cacheEntry) : me._getMetaForFileUsingMtimeAndSize(cacheEntry);
+ cache.setKey(entryName, meta);
+ } catch (err) {
+ // if the file does not exists we don't save it
+ // other errors are just thrown
+ if (err.code !== 'ENOENT') {
+ throw err;
+ }
+ }
+ });
+ cache.save(noPrune);
+ }
+ };
+ }
+};
+
+/***/ }),
+/* 995 */
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("crypto");
+
+/***/ }),
+/* 996 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+var path = __webpack_require__(501);
+
+var fs = __webpack_require__(971);
+
+var utils = __webpack_require__(997);
+
+var del = __webpack_require__(999);
+
+var writeJSON = utils.writeJSON;
+var cache = {
+ /**
+ * Load a cache identified by the given Id. If the element does not exists, then initialize an empty
+ * cache storage. If specified `cacheDir` will be used as the directory to persist the data to. If omitted
+ * then the cache module directory `./cache` will be used instead
+ *
+ * @method load
+ * @param docId {String} the id of the cache, would also be used as the name of the file cache
+ * @param [cacheDir] {String} directory for the cache entry
+ */
+ load: function (docId, cacheDir) {
+ var me = this;
+ me._visited = {};
+ me._persisted = {};
+ me._pathToFile = cacheDir ? path.resolve(cacheDir, docId) : path.resolve(__dirname, '../.cache/', docId);
+
+ if (fs.existsSync(me._pathToFile)) {
+ me._persisted = utils.tryParse(me._pathToFile, {});
+ }
+ },
+
+ /**
+ * Load the cache from the provided file
+ * @method loadFile
+ * @param {String} pathToFile the path to the file containing the info for the cache
+ */
+ loadFile: function (pathToFile) {
+ var me = this;
+ var dir = path.dirname(pathToFile);
+ var fName = path.basename(pathToFile);
+ me.load(fName, dir);
+ },
+
+ /**
+ * Returns the entire persisted object
+ * @method all
+ * @returns {*}
+ */
+ all: function () {
+ return this._persisted;
+ },
+ keys: function () {
+ return Object.keys(this._persisted);
+ },
+
+ /**
+ * sets a key to a given value
+ * @method setKey
+ * @param key {string} the key to set
+ * @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify
+ */
+ setKey: function (key, value) {
+ this._visited[key] = true;
+ this._persisted[key] = value;
+ },
+
+ /**
+ * remove a given key from the cache
+ * @method removeKey
+ * @param key {String} the key to remove from the object
+ */
+ removeKey: function (key) {
+ delete this._visited[key]; // esfmt-ignore-line
+
+ delete this._persisted[key]; // esfmt-ignore-line
+ },
+
+ /**
+ * Return the value of the provided key
+ * @method getKey
+ * @param key {String} the name of the key to retrieve
+ * @returns {*} the value from the key
+ */
+ getKey: function (key) {
+ this._visited[key] = true;
+ return this._persisted[key];
+ },
+
+ /**
+ * Remove keys that were not accessed/set since the
+ * last time the `prune` method was called.
+ * @method _prune
+ * @private
+ */
+ _prune: function () {
+ var me = this;
+ var obj = {};
+ var keys = Object.keys(me._visited); // no keys visited for either get or set value
+
+ if (keys.length === 0) {
+ return;
+ }
+
+ keys.forEach(function (key) {
+ obj[key] = me._persisted[key];
+ });
+ me._visited = {};
+ me._persisted = obj;
+ },
+
+ /**
+ * Save the state of the cache identified by the docId to disk
+ * as a JSON structure
+ * @param [noPrune=false] {Boolean} whether to remove from cache the non visited files
+ * @method save
+ */
+ save: function (noPrune) {
+ var me = this;
+ !noPrune && me._prune();
+ writeJSON(me._pathToFile, me._persisted);
+ },
+
+ /**
+ * remove the file where the cache is persisted
+ * @method removeCacheFile
+ * @return {Boolean} true or false if the file was successfully deleted
+ */
+ removeCacheFile: function () {
+ return del(this._pathToFile);
+ },
+
+ /**
+ * Destroy the file cache and cache content.
+ * @method destroy
+ */
+ destroy: function () {
+ var me = this;
+ me._visited = {};
+ me._persisted = {};
+ me.removeCacheFile();
+ }
+};
+module.exports = {
+ /**
+ * Alias for create. Should be considered depreacted. Will be removed in next releases
+ *
+ * @method load
+ * @param docId {String} the id of the cache, would also be used as the name of the file cache
+ * @param [cacheDir] {String} directory for the cache entry
+ * @returns {cache} cache instance
+ */
+ load: function (docId, cacheDir) {
+ return this.create(docId, cacheDir);
+ },
+
+ /**
+ * Load a cache identified by the given Id. If the element does not exists, then initialize an empty
+ * cache storage.
+ *
+ * @method create
+ * @param docId {String} the id of the cache, would also be used as the name of the file cache
+ * @param [cacheDir] {String} directory for the cache entry
+ * @returns {cache} cache instance
+ */
+ create: function (docId, cacheDir) {
+ var obj = Object.create(cache);
+ obj.load(docId, cacheDir);
+ return obj;
+ },
+ createFromFile: function (filePath) {
+ var obj = Object.create(cache);
+ obj.loadFile(filePath);
+ return obj;
+ },
+
+ /**
+ * Clear the cache identified by the given id. Caches stored in a different cache directory can be deleted directly
+ *
+ * @method clearCache
+ * @param docId {String} the id of the cache, would also be used as the name of the file cache
+ * @param cacheDir {String} the directory where the cache file was written
+ * @returns {Boolean} true if the cache folder was deleted. False otherwise
+ */
+ clearCacheById: function (docId, cacheDir) {
+ var filePath = cacheDir ? path.resolve(cacheDir, docId) : path.resolve(__dirname, '../.cache/', docId);
+ return del(filePath);
+ },
+
+ /**
+ * Remove all cache stored in the cache directory
+ * @method clearAll
+ * @returns {Boolean} true if the cache folder was deleted. False otherwise
+ */
+ clearAll: function (cacheDir) {
+ var filePath = cacheDir ? path.resolve(cacheDir) : path.resolve(__dirname, '../.cache/');
+ return del(filePath);
+ }
+};
+
+/***/ }),
+/* 997 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+var fs = __webpack_require__(971);
+
+var path = __webpack_require__(501);
+
+var flatted = __webpack_require__(998);
+
+module.exports = {
+ tryParse: function (filePath, defaultValue) {
+ var result;
+
+ try {
+ result = this.readJSON(filePath);
+ } catch (ex) {
+ result = defaultValue;
+ }
+
+ return result;
+ },
+
+ /**
+ * Read json file synchronously using flatted
+ *
+ * @method readJSON
+ * @param {String} filePath Json filepath
+ * @returns {*} parse result
+ */
+ readJSON: function (filePath) {
+ return flatted.parse(fs.readFileSync(filePath, {
+ encoding: 'utf8'
+ }));
+ },
+
+ /**
+ * Write json file synchronously using circular-json
+ *
+ * @method writeJSON
+ * @param {String} filePath Json filepath
+ * @param {*} data Object to serialize
+ */
+ writeJSON: function (filePath, data) {
+ fs.mkdirSync(path.dirname(filePath), {
+ recursive: true
+ });
+ fs.writeFileSync(filePath, flatted.stringify(data));
+ }
+};
+
+/***/ }),
+/* 998 */
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+/*! (c) 2020 Andrea Giammarchi */
+
+const {
+ parse: $parse,
+ stringify: $stringify
+} = JSON;
+const {
+ keys
+} = Object;
+const Primitive = String; // it could be Number
+
+const primitive = 'string'; // it could be 'number'
+
+const ignore = {};
+const object = 'object';
+
+const noop = (_, value) => value;
+
+const primitives = value => value instanceof Primitive ? Primitive(value) : value;
+
+const Primitives = (_, value) => typeof value === primitive ? new Primitive(value) : value;
+
+const revive = (input, parsed, output, $) => {
+ const lazy = [];
+
+ for (let ke = keys(output), {
+ length
+ } = ke, y = 0; y < length; y++) {
+ const k = ke[y];
+ const value = output[k];
+
+ if (value instanceof Primitive) {
+ const tmp = input[value];
+
+ if (typeof tmp === object && !parsed.has(tmp)) {
+ parsed.add(tmp);
+ output[k] = ignore;
+ lazy.push({
+ k,
+ a: [input, parsed, tmp, $]
+ });
+ } else output[k] = $.call(output, k, tmp);
+ } else if (output[k] !== ignore) output[k] = $.call(output, k, value);
+ }
+
+ for (let {
+ length
+ } = lazy, i = 0; i < length; i++) {
+ const {
+ k,
+ a
+ } = lazy[i];
+ output[k] = $.call(output, k, revive.apply(null, a));
+ }
+
+ return output;
+};
+
+const set = (known, input, value) => {
+ const index = Primitive(input.push(value) - 1);
+ known.set(value, index);
+ return index;
+};
+
+const parse = (text, reviver) => {
+ const input = $parse(text, Primitives).map(primitives);
+ const value = input[0];
+ const $ = reviver || noop;
+ const tmp = typeof value === object && value ? revive(input, new Set(), value, $) : value;
+ return $.call({
+ '': tmp
+ }, '', tmp);
+};
+
+exports.parse = parse;
+
+const stringify = (value, replacer, space) => {
+ const $ = replacer && typeof replacer === object ? (k, v) => k === '' || -1 < replacer.indexOf(k) ? v : void 0 : replacer || noop;
+ const known = new Map();
+ const input = [];
+ const output = [];
+ let i = +set(known, input, $.call({
+ '': value
+ }, '', value));
+ let firstRun = !i;
+
+ while (i < input.length) {
+ firstRun = true;
+ output[i] = $stringify(input[i++], replace, space);
+ }
+
+ return '[' + output.join(',') + ']';
+
+ function replace(key, value) {
+ if (firstRun) {
+ firstRun = !firstRun;
+ return value;
+ }
+
+ const after = $.call(this, key, value);
+
+ switch (typeof after) {
+ case object:
+ if (after === null) return after;
+
+ case primitive:
+ return known.get(after) || set(known, input, after);
+ }
+
+ return after;
+ }
+};
+
+exports.stringify = stringify;
+
+const toJSON = any => $parse(stringify(any));
+
+exports.toJSON = toJSON;
+
+const fromJSON = any => parse($stringify(any));
+
+exports.fromJSON = fromJSON;
+
+/***/ }),
+/* 999 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+var rimraf = (__webpack_require__(1000).sync);
+
+var fs = __webpack_require__(971);
+
+module.exports = function del(file) {
+ if (fs.existsSync(file)) {
+ //if rimraf doesn't throw then the file has been deleted or didn't exist
+ rimraf(file, {
+ glob: false
+ });
+ return true;
+ }
+
+ return false;
+};
+
+/***/ }),
+/* 1000 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+const assert = __webpack_require__(503);
+
+const path = __webpack_require__(501);
+
+const fs = __webpack_require__(971);
+
+let glob = undefined;
+
+try {
+ glob = __webpack_require__(1001);
+} catch (_err) {// treat glob as optional.
+}
+
+const defaultGlobOpts = {
+ nosort: true,
+ silent: true
+}; // for EMFILE handling
+
+let timeout = 0;
+const isWindows = process.platform === "win32";
+
+const defaults = options => {
+ const methods = ['unlink', 'chmod', 'stat', 'lstat', 'rmdir', 'readdir'];
+ methods.forEach(m => {
+ options[m] = options[m] || fs[m];
+ m = m + 'Sync';
+ options[m] = options[m] || fs[m];
+ });
+ options.maxBusyTries = options.maxBusyTries || 3;
+ options.emfileWait = options.emfileWait || 1000;
+
+ if (options.glob === false) {
+ options.disableGlob = true;
+ }
+
+ if (options.disableGlob !== true && glob === undefined) {
+ throw Error('glob dependency not found, set `options.disableGlob = true` if intentional');
+ }
+
+ options.disableGlob = options.disableGlob || false;
+ options.glob = options.glob || defaultGlobOpts;
+};
+
+const rimraf = (p, options, cb) => {
+ if (typeof options === 'function') {
+ cb = options;
+ options = {};
+ }
+
+ assert(p, 'rimraf: missing path');
+ assert.equal(typeof p, 'string', 'rimraf: path should be a string');
+ assert.equal(typeof cb, 'function', 'rimraf: callback function required');
+ assert(options, 'rimraf: invalid options argument provided');
+ assert.equal(typeof options, 'object', 'rimraf: options should be object');
+ defaults(options);
+ let busyTries = 0;
+ let errState = null;
+ let n = 0;
+
+ const next = er => {
+ errState = errState || er;
+ if (--n === 0) cb(errState);
+ };
+
+ const afterGlob = (er, results) => {
+ if (er) return cb(er);
+ n = results.length;
+ if (n === 0) return cb();
+ results.forEach(p => {
+ const CB = er => {
+ if (er) {
+ if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && busyTries < options.maxBusyTries) {
+ busyTries++; // try again, with the same exact callback as this one.
+
+ return setTimeout(() => rimraf_(p, options, CB), busyTries * 100);
+ } // this one won't happen if graceful-fs is used.
+
+
+ if (er.code === "EMFILE" && timeout < options.emfileWait) {
+ return setTimeout(() => rimraf_(p, options, CB), timeout++);
+ } // already gone
+
+
+ if (er.code === "ENOENT") er = null;
+ }
+
+ timeout = 0;
+ next(er);
+ };
+
+ rimraf_(p, options, CB);
+ });
+ };
+
+ if (options.disableGlob || !glob.hasMagic(p)) return afterGlob(null, [p]);
+ options.lstat(p, (er, stat) => {
+ if (!er) return afterGlob(null, [p]);
+ glob(p, options.glob, afterGlob);
+ });
+}; // Two possible strategies.
+// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR
+// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR
+//
+// Both result in an extra syscall when you guess wrong. However, there
+// are likely far more normal files in the world than directories. This
+// is based on the assumption that a the average number of files per
+// directory is >= 1.
+//
+// If anyone ever complains about this, then I guess the strategy could
+// be made configurable somehow. But until then, YAGNI.
+
+
+const rimraf_ = (p, options, cb) => {
+ assert(p);
+ assert(options);
+ assert(typeof cb === 'function'); // sunos lets the root user unlink directories, which is... weird.
+ // so we have to lstat here and make sure it's not a dir.
+
+ options.lstat(p, (er, st) => {
+ if (er && er.code === "ENOENT") return cb(null); // Windows can EPERM on stat. Life is suffering.
+
+ if (er && er.code === "EPERM" && isWindows) fixWinEPERM(p, options, er, cb);
+ if (st && st.isDirectory()) return rmdir(p, options, er, cb);
+ options.unlink(p, er => {
+ if (er) {
+ if (er.code === "ENOENT") return cb(null);
+ if (er.code === "EPERM") return isWindows ? fixWinEPERM(p, options, er, cb) : rmdir(p, options, er, cb);
+ if (er.code === "EISDIR") return rmdir(p, options, er, cb);
+ }
+
+ return cb(er);
+ });
+ });
+};
+
+const fixWinEPERM = (p, options, er, cb) => {
+ assert(p);
+ assert(options);
+ assert(typeof cb === 'function');
+ options.chmod(p, 0o666, er2 => {
+ if (er2) cb(er2.code === "ENOENT" ? null : er);else options.stat(p, (er3, stats) => {
+ if (er3) cb(er3.code === "ENOENT" ? null : er);else if (stats.isDirectory()) rmdir(p, options, er, cb);else options.unlink(p, cb);
+ });
+ });
+};
+
+const fixWinEPERMSync = (p, options, er) => {
+ assert(p);
+ assert(options);
+
+ try {
+ options.chmodSync(p, 0o666);
+ } catch (er2) {
+ if (er2.code === "ENOENT") return;else throw er;
+ }
+
+ let stats;
+
+ try {
+ stats = options.statSync(p);
+ } catch (er3) {
+ if (er3.code === "ENOENT") return;else throw er;
+ }
+
+ if (stats.isDirectory()) rmdirSync(p, options, er);else options.unlinkSync(p);
+};
+
+const rmdir = (p, options, originalEr, cb) => {
+ assert(p);
+ assert(options);
+ assert(typeof cb === 'function'); // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
+ // if we guessed wrong, and it's not a directory, then
+ // raise the original error.
+
+ options.rmdir(p, er => {
+ if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) rmkids(p, options, cb);else if (er && er.code === "ENOTDIR") cb(originalEr);else cb(er);
+ });
+};
+
+const rmkids = (p, options, cb) => {
+ assert(p);
+ assert(options);
+ assert(typeof cb === 'function');
+ options.readdir(p, (er, files) => {
+ if (er) return cb(er);
+ let n = files.length;
+ if (n === 0) return options.rmdir(p, cb);
+ let errState;
+ files.forEach(f => {
+ rimraf(path.join(p, f), options, er => {
+ if (errState) return;
+ if (er) return cb(errState = er);
+ if (--n === 0) options.rmdir(p, cb);
+ });
+ });
+ });
+}; // this looks simpler, and is strictly *faster*, but will
+// tie up the JavaScript thread and fail on excessively
+// deep directory trees.
+
+
+const rimrafSync = (p, options) => {
+ options = options || {};
+ defaults(options);
+ assert(p, 'rimraf: missing path');
+ assert.equal(typeof p, 'string', 'rimraf: path should be a string');
+ assert(options, 'rimraf: missing options');
+ assert.equal(typeof options, 'object', 'rimraf: options should be object');
+ let results;
+
+ if (options.disableGlob || !glob.hasMagic(p)) {
+ results = [p];
+ } else {
+ try {
+ options.lstatSync(p);
+ results = [p];
+ } catch (er) {
+ results = glob.sync(p, options.glob);
+ }
+ }
+
+ if (!results.length) return;
+
+ for (let i = 0; i < results.length; i++) {
+ const p = results[i];
+ let st;
+
+ try {
+ st = options.lstatSync(p);
+ } catch (er) {
+ if (er.code === "ENOENT") return; // Windows can EPERM on stat. Life is suffering.
+
+ if (er.code === "EPERM" && isWindows) fixWinEPERMSync(p, options, er);
+ }
+
+ try {
+ // sunos lets the root user unlink directories, which is... weird.
+ if (st && st.isDirectory()) rmdirSync(p, options, null);else options.unlinkSync(p);
+ } catch (er) {
+ if (er.code === "ENOENT") return;
+ if (er.code === "EPERM") return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er);
+ if (er.code !== "EISDIR") throw er;
+ rmdirSync(p, options, er);
+ }
+ }
+};
+
+const rmdirSync = (p, options, originalEr) => {
+ assert(p);
+ assert(options);
+
+ try {
+ options.rmdirSync(p);
+ } catch (er) {
+ if (er.code === "ENOENT") return;
+ if (er.code === "ENOTDIR") throw originalEr;
+ if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") rmkidsSync(p, options);
+ }
+};
+
+const rmkidsSync = (p, options) => {
+ assert(p);
+ assert(options);
+ options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)); // We only end up here once we got ENOTEMPTY at least once, and
+ // at this point, we are guaranteed to have removed all the kids.
+ // So, we know that it won't be ENOENT or ENOTDIR or anything else.
+ // try really hard to delete stuff on windows, because it has a
+ // PROFOUNDLY annoying habit of not closing handles promptly when
+ // files are deleted, resulting in spurious ENOTEMPTY errors.
+
+ const retries = isWindows ? 100 : 1;
+ let i = 0;
+
+ do {
+ let threw = true;
+
+ try {
+ const ret = options.rmdirSync(p, options);
+ threw = false;
+ return ret;
+ } finally {
+ if (++i < retries && threw) continue;
+ }
+ } while (true);
+};
+
+module.exports = rimraf;
+rimraf.sync = rimrafSync;
+
+/***/ }),
+/* 1001 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+// Approach:
+//
+// 1. Get the minimatch set
+// 2. For each pattern in the set, PROCESS(pattern, false)
+// 3. Store matches per-set, then uniq them
+//
+// PROCESS(pattern, inGlobStar)
+// Get the first [n] items from pattern that are all strings
+// Join these together. This is PREFIX.
+// If there is no more remaining, then stat(PREFIX) and
+// add to matches if it succeeds. END.
+//
+// If inGlobStar and PREFIX is symlink and points to dir
+// set ENTRIES = []
+// else readdir(PREFIX) as ENTRIES
+// If fail, END
+//
+// with ENTRIES
+// If pattern[n] is GLOBSTAR
+// // handle the case where the globstar match is empty
+// // by pruning it out, and testing the resulting pattern
+// PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
+// // handle other cases.
+// for ENTRY in ENTRIES (not dotfiles)
+// // attach globstar + tail onto the entry
+// // Mark that this entry is a globstar match
+// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
+//
+// else // not globstar
+// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
+// Test ENTRY against pattern[n]
+// If fails, continue
+// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
+//
+// Caveat:
+// Cache all stats and readdirs results to minimize syscall. Since all
+// we ever care about is existence and directory-ness, we can just keep
+// `true` for files, and [children,...] for directories, or `false` for
+// things that don't exist.
+module.exports = glob;
+
+var rp = __webpack_require__(1002);
+
+var minimatch = __webpack_require__(953);
+
+var Minimatch = minimatch.Minimatch;
+
+var inherits = __webpack_require__(1004);
+
+var EE = (__webpack_require__(1005).EventEmitter);
+
+var path = __webpack_require__(501);
+
+var assert = __webpack_require__(503);
+
+var isAbsolute = __webpack_require__(1006);
+
+var globSync = __webpack_require__(1007);
+
+var common = __webpack_require__(1008);
+
+var setopts = common.setopts;
+var ownProp = common.ownProp;
+
+var inflight = __webpack_require__(1009);
+
+var util = __webpack_require__(516);
+
+var childrenIgnored = common.childrenIgnored;
+var isIgnored = common.isIgnored;
+
+var once = __webpack_require__(1011);
+
+function glob(pattern, options, cb) {
+ if (typeof options === 'function') cb = options, options = {};
+ if (!options) options = {};
+
+ if (options.sync) {
+ if (cb) throw new TypeError('callback provided to sync glob');
+ return globSync(pattern, options);
+ }
+
+ return new Glob(pattern, options, cb);
+}
+
+glob.sync = globSync;
+var GlobSync = glob.GlobSync = globSync.GlobSync; // old api surface
+
+glob.glob = glob;
+
+function extend(origin, add) {
+ if (add === null || typeof add !== 'object') {
+ return origin;
+ }
+
+ var keys = Object.keys(add);
+ var i = keys.length;
+
+ while (i--) {
+ origin[keys[i]] = add[keys[i]];
+ }
+
+ return origin;
+}
+
+glob.hasMagic = function (pattern, options_) {
+ var options = extend({}, options_);
+ options.noprocess = true;
+ var g = new Glob(pattern, options);
+ var set = g.minimatch.set;
+ if (!pattern) return false;
+ if (set.length > 1) return true;
+
+ for (var j = 0; j < set[0].length; j++) {
+ if (typeof set[0][j] !== 'string') return true;
+ }
+
+ return false;
+};
+
+glob.Glob = Glob;
+inherits(Glob, EE);
+
+function Glob(pattern, options, cb) {
+ if (typeof options === 'function') {
+ cb = options;
+ options = null;
+ }
+
+ if (options && options.sync) {
+ if (cb) throw new TypeError('callback provided to sync glob');
+ return new GlobSync(pattern, options);
+ }
+
+ if (!(this instanceof Glob)) return new Glob(pattern, options, cb);
+ setopts(this, pattern, options);
+ this._didRealPath = false; // process each pattern in the minimatch set
+
+ var n = this.minimatch.set.length; // The matches are stored as {<filename>: true,...} so that
+ // duplicates are automagically pruned.
+ // Later, we do an Object.keys() on these.
+ // Keep them as a list so we can fill in when nonull is set.
+
+ this.matches = new Array(n);
+
+ if (typeof cb === 'function') {
+ cb = once(cb);
+ this.on('error', cb);
+ this.on('end', function (matches) {
+ cb(null, matches);
+ });
+ }
+
+ var self = this;
+ this._processing = 0;
+ this._emitQueue = [];
+ this._processQueue = [];
+ this.paused = false;
+ if (this.noprocess) return this;
+ if (n === 0) return done();
+ var sync = true;
+
+ for (var i = 0; i < n; i++) {
+ this._process(this.minimatch.set[i], i, false, done);
+ }
+
+ sync = false;
+
+ function done() {
+ --self._processing;
+
+ if (self._processing <= 0) {
+ if (sync) {
+ process.nextTick(function () {
+ self._finish();
+ });
+ } else {
+ self._finish();
+ }
+ }
+ }
+}
+
+Glob.prototype._finish = function () {
+ assert(this instanceof Glob);
+ if (this.aborted) return;
+ if (this.realpath && !this._didRealpath) return this._realpath();
+ common.finish(this);
+ this.emit('end', this.found);
+};
+
+Glob.prototype._realpath = function () {
+ if (this._didRealpath) return;
+ this._didRealpath = true;
+ var n = this.matches.length;
+ if (n === 0) return this._finish();
+ var self = this;
+
+ for (var i = 0; i < this.matches.length; i++) this._realpathSet(i, next);
+
+ function next() {
+ if (--n === 0) self._finish();
+ }
+};
+
+Glob.prototype._realpathSet = function (index, cb) {
+ var matchset = this.matches[index];
+ if (!matchset) return cb();
+ var found = Object.keys(matchset);
+ var self = this;
+ var n = found.length;
+ if (n === 0) return cb();
+ var set = this.matches[index] = Object.create(null);
+ found.forEach(function (p, i) {
+ // If there's a problem with the stat, then it means that
+ // one or more of the links in the realpath couldn't be
+ // resolved. just return the abs value in that case.
+ p = self._makeAbs(p);
+ rp.realpath(p, self.realpathCache, function (er, real) {
+ if (!er) set[real] = true;else if (er.syscall === 'stat') set[p] = true;else self.emit('error', er); // srsly wtf right here
+
+ if (--n === 0) {
+ self.matches[index] = set;
+ cb();
+ }
+ });
+ });
+};
+
+Glob.prototype._mark = function (p) {
+ return common.mark(this, p);
+};
+
+Glob.prototype._makeAbs = function (f) {
+ return common.makeAbs(this, f);
+};
+
+Glob.prototype.abort = function () {
+ this.aborted = true;
+ this.emit('abort');
+};
+
+Glob.prototype.pause = function () {
+ if (!this.paused) {
+ this.paused = true;
+ this.emit('pause');
+ }
+};
+
+Glob.prototype.resume = function () {
+ if (this.paused) {
+ this.emit('resume');
+ this.paused = false;
+
+ if (this._emitQueue.length) {
+ var eq = this._emitQueue.slice(0);
+
+ this._emitQueue.length = 0;
+
+ for (var i = 0; i < eq.length; i++) {
+ var e = eq[i];
+
+ this._emitMatch(e[0], e[1]);
+ }
+ }
+
+ if (this._processQueue.length) {
+ var pq = this._processQueue.slice(0);
+
+ this._processQueue.length = 0;
+
+ for (var i = 0; i < pq.length; i++) {
+ var p = pq[i];
+ this._processing--;
+
+ this._process(p[0], p[1], p[2], p[3]);
+ }
+ }
+ }
+};
+
+Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
+ assert(this instanceof Glob);
+ assert(typeof cb === 'function');
+ if (this.aborted) return;
+ this._processing++;
+
+ if (this.paused) {
+ this._processQueue.push([pattern, index, inGlobStar, cb]);
+
+ return;
+ } //console.error('PROCESS %d', this._processing, pattern)
+ // Get the first [n] parts of pattern that are all strings.
+
+
+ var n = 0;
+
+ while (typeof pattern[n] === 'string') {
+ n++;
+ } // now n is the index of the first one that is *not* a string.
+ // see if there's anything else
+
+
+ var prefix;
+
+ switch (n) {
+ // if not, then this is rather simple
+ case pattern.length:
+ this._processSimple(pattern.join('/'), index, cb);
+
+ return;
+
+ case 0:
+ // pattern *starts* with some non-trivial item.
+ // going to readdir(cwd), but not include the prefix in matches.
+ prefix = null;
+ break;
+
+ default:
+ // pattern has some string bits in the front.
+ // whatever it starts with, whether that's 'absolute' like /foo/bar,
+ // or 'relative' like '../baz'
+ prefix = pattern.slice(0, n).join('/');
+ break;
+ }
+
+ var remain = pattern.slice(n); // get the list of entries.
+
+ var read;
+ if (prefix === null) read = '.';else if (isAbsolute(prefix) || isAbsolute(pattern.map(function (p) {
+ return typeof p === 'string' ? p : '[*]';
+ }).join('/'))) {
+ if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix;
+ read = prefix;
+ } else read = prefix;
+
+ var abs = this._makeAbs(read); //if ignored, skip _processing
+
+
+ if (childrenIgnored(this, read)) return cb();
+ var isGlobStar = remain[0] === minimatch.GLOBSTAR;
+ if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
+};
+
+Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
+ var self = this;
+
+ this._readdir(abs, inGlobStar, function (er, entries) {
+ return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
+ });
+};
+
+Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
+ // if the abs isn't a dir, then nothing can match!
+ if (!entries) return cb(); // It will only match dot entries if it starts with a dot, or if
+ // dot is set. Stuff like @(.foo|.bar) isn't allowed.
+
+ var pn = remain[0];
+ var negate = !!this.minimatch.negate;
+ var rawGlob = pn._glob;
+ var dotOk = this.dot || rawGlob.charAt(0) === '.';
+ var matchedEntries = [];
+
+ for (var i = 0; i < entries.length; i++) {
+ var e = entries[i];
+
+ if (e.charAt(0) !== '.' || dotOk) {
+ var m;
+
+ if (negate && !prefix) {
+ m = !e.match(pn);
+ } else {
+ m = e.match(pn);
+ }
+
+ if (m) matchedEntries.push(e);
+ }
+ } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
+
+
+ var len = matchedEntries.length; // If there are no matched entries, then nothing matches.
+
+ if (len === 0) return cb(); // if this is the last remaining pattern bit, then no need for
+ // an additional stat *unless* the user has specified mark or
+ // stat explicitly. We know they exist, since readdir returned
+ // them.
+
+ if (remain.length === 1 && !this.mark && !this.stat) {
+ if (!this.matches[index]) this.matches[index] = Object.create(null);
+
+ for (var i = 0; i < len; i++) {
+ var e = matchedEntries[i];
+
+ if (prefix) {
+ if (prefix !== '/') e = prefix + '/' + e;else e = prefix + e;
+ }
+
+ if (e.charAt(0) === '/' && !this.nomount) {
+ e = path.join(this.root, e);
+ }
+
+ this._emitMatch(index, e);
+ } // This was the last one, and no stats were needed
+
+
+ return cb();
+ } // now test all matched entries as stand-ins for that part
+ // of the pattern.
+
+
+ remain.shift();
+
+ for (var i = 0; i < len; i++) {
+ var e = matchedEntries[i];
+ var newPattern;
+
+ if (prefix) {
+ if (prefix !== '/') e = prefix + '/' + e;else e = prefix + e;
+ }
+
+ this._process([e].concat(remain), index, inGlobStar, cb);
+ }
+
+ cb();
+};
+
+Glob.prototype._emitMatch = function (index, e) {
+ if (this.aborted) return;
+ if (isIgnored(this, e)) return;
+
+ if (this.paused) {
+ this._emitQueue.push([index, e]);
+
+ return;
+ }
+
+ var abs = isAbsolute(e) ? e : this._makeAbs(e);
+ if (this.mark) e = this._mark(e);
+ if (this.absolute) e = abs;
+ if (this.matches[index][e]) return;
+
+ if (this.nodir) {
+ var c = this.cache[abs];
+ if (c === 'DIR' || Array.isArray(c)) return;
+ }
+
+ this.matches[index][e] = true;
+ var st = this.statCache[abs];
+ if (st) this.emit('stat', e, st);
+ this.emit('match', e);
+};
+
+Glob.prototype._readdirInGlobStar = function (abs, cb) {
+ if (this.aborted) return; // follow all symlinked directories forever
+ // just proceed as if this is a non-globstar situation
+
+ if (this.follow) return this._readdir(abs, false, cb);
+ var lstatkey = 'lstat\0' + abs;
+ var self = this;
+ var lstatcb = inflight(lstatkey, lstatcb_);
+ if (lstatcb) self.fs.lstat(abs, lstatcb);
+
+ function lstatcb_(er, lstat) {
+ if (er && er.code === 'ENOENT') return cb();
+ var isSym = lstat && lstat.isSymbolicLink();
+ self.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file.
+ // don't bother doing a readdir in that case.
+
+ if (!isSym && lstat && !lstat.isDirectory()) {
+ self.cache[abs] = 'FILE';
+ cb();
+ } else self._readdir(abs, false, cb);
+ }
+};
+
+Glob.prototype._readdir = function (abs, inGlobStar, cb) {
+ if (this.aborted) return;
+ cb = inflight('readdir\0' + abs + '\0' + inGlobStar, cb);
+ if (!cb) return; //console.error('RD %j %j', +inGlobStar, abs)
+
+ if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb);
+
+ if (ownProp(this.cache, abs)) {
+ var c = this.cache[abs];
+ if (!c || c === 'FILE') return cb();
+ if (Array.isArray(c)) return cb(null, c);
+ }
+
+ var self = this;
+ self.fs.readdir(abs, readdirCb(this, abs, cb));
+};
+
+function readdirCb(self, abs, cb) {
+ return function (er, entries) {
+ if (er) self._readdirError(abs, er, cb);else self._readdirEntries(abs, entries, cb);
+ };
+}
+
+Glob.prototype._readdirEntries = function (abs, entries, cb) {
+ if (this.aborted) return; // if we haven't asked to stat everything, then just
+ // assume that everything in there exists, so we can avoid
+ // having to stat it a second time.
+
+ if (!this.mark && !this.stat) {
+ for (var i = 0; i < entries.length; i++) {
+ var e = entries[i];
+ if (abs === '/') e = abs + e;else e = abs + '/' + e;
+ this.cache[e] = true;
+ }
+ }
+
+ this.cache[abs] = entries;
+ return cb(null, entries);
+};
+
+Glob.prototype._readdirError = function (f, er, cb) {
+ if (this.aborted) return; // handle errors, and cache the information
+
+ switch (er.code) {
+ case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
+
+ case 'ENOTDIR':
+ // totally normal. means it *does* exist.
+ var abs = this._makeAbs(f);
+
+ this.cache[abs] = 'FILE';
+
+ if (abs === this.cwdAbs) {
+ var error = new Error(er.code + ' invalid cwd ' + this.cwd);
+ error.path = this.cwd;
+ error.code = er.code;
+ this.emit('error', error);
+ this.abort();
+ }
+
+ break;
+
+ case 'ENOENT': // not terribly unusual
+
+ case 'ELOOP':
+ case 'ENAMETOOLONG':
+ case 'UNKNOWN':
+ this.cache[this._makeAbs(f)] = false;
+ break;
+
+ default:
+ // some unusual error. Treat as failure.
+ this.cache[this._makeAbs(f)] = false;
+
+ if (this.strict) {
+ this.emit('error', er); // If the error is handled, then we abort
+ // if not, we threw out of here
+
+ this.abort();
+ }
+
+ if (!this.silent) console.error('glob error', er);
+ break;
+ }
+
+ return cb();
+};
+
+Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
+ var self = this;
+
+ this._readdir(abs, inGlobStar, function (er, entries) {
+ self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
+ });
+};
+
+Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
+ //console.error('pgs2', prefix, remain[0], entries)
+ // no entries means not a dir, so it can never have matches
+ // foo.txt/** doesn't match foo.txt
+ if (!entries) return cb(); // test without the globstar, and with every child both below
+ // and replacing the globstar.
+
+ var remainWithoutGlobStar = remain.slice(1);
+ var gspref = prefix ? [prefix] : [];
+ var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state
+
+ this._process(noGlobStar, index, false, cb);
+
+ var isSym = this.symlinks[abs];
+ var len = entries.length; // If it's a symlink, and we're in a globstar, then stop
+
+ if (isSym && inGlobStar) return cb();
+
+ for (var i = 0; i < len; i++) {
+ var e = entries[i];
+ if (e.charAt(0) === '.' && !this.dot) continue; // these two cases enter the inGlobStar state
+
+ var instead = gspref.concat(entries[i], remainWithoutGlobStar);
+
+ this._process(instead, index, true, cb);
+
+ var below = gspref.concat(entries[i], remain);
+
+ this._process(below, index, true, cb);
+ }
+
+ cb();
+};
+
+Glob.prototype._processSimple = function (prefix, index, cb) {
+ // XXX review this. Shouldn't it be doing the mounting etc
+ // before doing stat? kinda weird?
+ var self = this;
+
+ this._stat(prefix, function (er, exists) {
+ self._processSimple2(prefix, index, er, exists, cb);
+ });
+};
+
+Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
+ //console.error('ps2', prefix, exists)
+ if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results
+
+ if (!exists) return cb();
+
+ if (prefix && isAbsolute(prefix) && !this.nomount) {
+ var trail = /[\/\\]$/.test(prefix);
+
+ if (prefix.charAt(0) === '/') {
+ prefix = path.join(this.root, prefix);
+ } else {
+ prefix = path.resolve(this.root, prefix);
+ if (trail) prefix += '/';
+ }
+ }
+
+ if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match
+
+ this._emitMatch(index, prefix);
+
+ cb();
+}; // Returns either 'DIR', 'FILE', or false
+
+
+Glob.prototype._stat = function (f, cb) {
+ var abs = this._makeAbs(f);
+
+ var needDir = f.slice(-1) === '/';
+ if (f.length > this.maxLength) return cb();
+
+ if (!this.stat && ownProp(this.cache, abs)) {
+ var c = this.cache[abs];
+ if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it
+
+ if (!needDir || c === 'DIR') return cb(null, c);
+ if (needDir && c === 'FILE') return cb(); // otherwise we have to stat, because maybe c=true
+ // if we know it exists, but not what it is.
+ }
+
+ var exists;
+ var stat = this.statCache[abs];
+
+ if (stat !== undefined) {
+ if (stat === false) return cb(null, stat);else {
+ var type = stat.isDirectory() ? 'DIR' : 'FILE';
+ if (needDir && type === 'FILE') return cb();else return cb(null, type, stat);
+ }
+ }
+
+ var self = this;
+ var statcb = inflight('stat\0' + abs, lstatcb_);
+ if (statcb) self.fs.lstat(abs, statcb);
+
+ function lstatcb_(er, lstat) {
+ if (lstat && lstat.isSymbolicLink()) {
+ // If it's a symlink, then treat it as the target, unless
+ // the target does not exist, then treat it as a file.
+ return self.fs.stat(abs, function (er, stat) {
+ if (er) self._stat2(f, abs, null, lstat, cb);else self._stat2(f, abs, er, stat, cb);
+ });
+ } else {
+ self._stat2(f, abs, er, lstat, cb);
+ }
+ }
+};
+
+Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
+ if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
+ this.statCache[abs] = false;
+ return cb();
+ }
+
+ var needDir = f.slice(-1) === '/';
+ this.statCache[abs] = stat;
+ if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat);
+ var c = true;
+ if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE';
+ this.cache[abs] = this.cache[abs] || c;
+ if (needDir && c === 'FILE') return cb();
+ return cb(null, c, stat);
+};
+
+/***/ }),
+/* 1002 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+module.exports = realpath;
+realpath.realpath = realpath;
+realpath.sync = realpathSync;
+realpath.realpathSync = realpathSync;
+realpath.monkeypatch = monkeypatch;
+realpath.unmonkeypatch = unmonkeypatch;
+
+var fs = __webpack_require__(971);
+
+var origRealpath = fs.realpath;
+var origRealpathSync = fs.realpathSync;
+var version = process.version;
+var ok = /^v[0-5]\./.test(version);
+
+var old = __webpack_require__(1003);
+
+function newError(er) {
+ return er && er.syscall === 'realpath' && (er.code === 'ELOOP' || er.code === 'ENOMEM' || er.code === 'ENAMETOOLONG');
+}
+
+function realpath(p, cache, cb) {
+ if (ok) {
+ return origRealpath(p, cache, cb);
+ }
+
+ if (typeof cache === 'function') {
+ cb = cache;
+ cache = null;
+ }
+
+ origRealpath(p, cache, function (er, result) {
+ if (newError(er)) {
+ old.realpath(p, cache, cb);
+ } else {
+ cb(er, result);
+ }
+ });
+}
+
+function realpathSync(p, cache) {
+ if (ok) {
+ return origRealpathSync(p, cache);
+ }
+
+ try {
+ return origRealpathSync(p, cache);
+ } catch (er) {
+ if (newError(er)) {
+ return old.realpathSync(p, cache);
+ } else {
+ throw er;
+ }
+ }
+}
+
+function monkeypatch() {
+ fs.realpath = realpath;
+ fs.realpathSync = realpathSync;
+}
+
+function unmonkeypatch() {
+ fs.realpath = origRealpath;
+ fs.realpathSync = origRealpathSync;
+}
+
+/***/ }),
+/* 1003 */
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+var pathModule = __webpack_require__(501);
+
+var isWindows = process.platform === 'win32';
+
+var fs = __webpack_require__(971); // JavaScript implementation of realpath, ported from node pre-v6
+
+
+var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
+
+function rethrow() {
+ // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
+ // is fairly slow to generate.
+ var callback;
+
+ if (DEBUG) {
+ var backtrace = new Error();
+ callback = debugCallback;
+ } else callback = missingCallback;
+
+ return callback;
+
+ function debugCallback(err) {
+ if (err) {
+ backtrace.message = err.message;
+ err = backtrace;
+ missingCallback(err);
+ }
+ }
+
+ function missingCallback(err) {
+ if (err) {
+ if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
+ else if (!process.noDeprecation) {
+ var msg = 'fs: missing callback ' + (err.stack || err.message);
+ if (process.traceDeprecation) console.trace(msg);else console.error(msg);
+ }
+ }
+ }
+}
+
+function maybeCallback(cb) {
+ return typeof cb === 'function' ? cb : rethrow();
+}
+
+var normalize = pathModule.normalize; // Regexp that finds the next partion of a (partial) path
+// result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
+
+if (isWindows) {
+ var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
+} else {
+ var nextPartRe = /(.*?)(?:[\/]+|$)/g;
+} // Regex to find the device root, including trailing slash. E.g. 'c:\\'.
+
+
+if (isWindows) {
+ var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
+} else {
+ var splitRootRe = /^[\/]*/;
+}
+
+exports.realpathSync = function realpathSync(p, cache) {
+ // make p is absolute
+ p = pathModule.resolve(p);
+
+ if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
+ return cache[p];
+ }
+
+ var original = p,
+ seenLinks = {},
+ knownHard = {}; // current character position in p
+
+ var pos; // the partial path so far, including a trailing slash if any
+
+ var current; // the partial path without a trailing slash (except when pointing at a root)
+
+ var base; // the partial path scanned in the previous round, with slash
+
+ var previous;
+ start();
+
+ function start() {
+ // Skip over roots
+ var m = splitRootRe.exec(p);
+ pos = m[0].length;
+ current = m[0];
+ base = m[0];
+ previous = ''; // On windows, check that the root exists. On unix there is no need.
+
+ if (isWindows && !knownHard[base]) {
+ fs.lstatSync(base);
+ knownHard[base] = true;
+ }
+ } // walk down the path, swapping out linked pathparts for their real
+ // values
+ // NB: p.length changes.
+
+
+ while (pos < p.length) {
+ // find the next part
+ nextPartRe.lastIndex = pos;
+ var result = nextPartRe.exec(p);
+ previous = current;
+ current += result[0];
+ base = previous + result[1];
+ pos = nextPartRe.lastIndex; // continue if not a symlink
+
+ if (knownHard[base] || cache && cache[base] === base) {
+ continue;
+ }
+
+ var resolvedLink;
+
+ if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
+ // some known symbolic link. no need to stat again.
+ resolvedLink = cache[base];
+ } else {
+ var stat = fs.lstatSync(base);
+
+ if (!stat.isSymbolicLink()) {
+ knownHard[base] = true;
+ if (cache) cache[base] = base;
+ continue;
+ } // read the link if it wasn't read before
+ // dev/ino always return 0 on windows, so skip the check.
+
+
+ var linkTarget = null;
+
+ if (!isWindows) {
+ var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
+
+ if (seenLinks.hasOwnProperty(id)) {
+ linkTarget = seenLinks[id];
+ }
+ }
+
+ if (linkTarget === null) {
+ fs.statSync(base);
+ linkTarget = fs.readlinkSync(base);
+ }
+
+ resolvedLink = pathModule.resolve(previous, linkTarget); // track this, if given a cache.
+
+ if (cache) cache[base] = resolvedLink;
+ if (!isWindows) seenLinks[id] = linkTarget;
+ } // resolve the link, then start over
+
+
+ p = pathModule.resolve(resolvedLink, p.slice(pos));
+ start();
+ }
+
+ if (cache) cache[original] = p;
+ return p;
+};
+
+exports.realpath = function realpath(p, cache, cb) {
+ if (typeof cb !== 'function') {
+ cb = maybeCallback(cache);
+ cache = null;
+ } // make p is absolute
+
+
+ p = pathModule.resolve(p);
+
+ if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
+ return process.nextTick(cb.bind(null, null, cache[p]));
+ }
+
+ var original = p,
+ seenLinks = {},
+ knownHard = {}; // current character position in p
+
+ var pos; // the partial path so far, including a trailing slash if any
+
+ var current; // the partial path without a trailing slash (except when pointing at a root)
+
+ var base; // the partial path scanned in the previous round, with slash
+
+ var previous;
+ start();
+
+ function start() {
+ // Skip over roots
+ var m = splitRootRe.exec(p);
+ pos = m[0].length;
+ current = m[0];
+ base = m[0];
+ previous = ''; // On windows, check that the root exists. On unix there is no need.
+
+ if (isWindows && !knownHard[base]) {
+ fs.lstat(base, function (err) {
+ if (err) return cb(err);
+ knownHard[base] = true;
+ LOOP();
+ });
+ } else {
+ process.nextTick(LOOP);
+ }
+ } // walk down the path, swapping out linked pathparts for their real
+ // values
+
+
+ function LOOP() {
+ // stop if scanned past end of path
+ if (pos >= p.length) {
+ if (cache) cache[original] = p;
+ return cb(null, p);
+ } // find the next part
+
+
+ nextPartRe.lastIndex = pos;
+ var result = nextPartRe.exec(p);
+ previous = current;
+ current += result[0];
+ base = previous + result[1];
+ pos = nextPartRe.lastIndex; // continue if not a symlink
+
+ if (knownHard[base] || cache && cache[base] === base) {
+ return process.nextTick(LOOP);
+ }
+
+ if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
+ // known symbolic link. no need to stat again.
+ return gotResolvedLink(cache[base]);
+ }
+
+ return fs.lstat(base, gotStat);
+ }
+
+ function gotStat(err, stat) {
+ if (err) return cb(err); // if not a symlink, skip to the next path part
+
+ if (!stat.isSymbolicLink()) {
+ knownHard[base] = true;
+ if (cache) cache[base] = base;
+ return process.nextTick(LOOP);
+ } // stat & read the link if not read before
+ // call gotTarget as soon as the link target is known
+ // dev/ino always return 0 on windows, so skip the check.
+
+
+ if (!isWindows) {
+ var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
+
+ if (seenLinks.hasOwnProperty(id)) {
+ return gotTarget(null, seenLinks[id], base);
+ }
+ }
+
+ fs.stat(base, function (err) {
+ if (err) return cb(err);
+ fs.readlink(base, function (err, target) {
+ if (!isWindows) seenLinks[id] = target;
+ gotTarget(err, target);
+ });
+ });
+ }
+
+ function gotTarget(err, target, base) {
+ if (err) return cb(err);
+ var resolvedLink = pathModule.resolve(previous, target);
+ if (cache) cache[base] = resolvedLink;
+ gotResolvedLink(resolvedLink);
+ }
+
+ function gotResolvedLink(resolvedLink) {
+ // resolve the link, then start over
+ p = pathModule.resolve(resolvedLink, p.slice(pos));
+ start();
+ }
+};
+
+/***/ }),
+/* 1004 */
+/***/ ((module) => {
+
+if (typeof Object.create === 'function') {
+ // implementation from standard node.js 'util' module
+ module.exports = function inherits(ctor, superCtor) {
+ if (superCtor) {
+ ctor.super_ = superCtor;
+ ctor.prototype = Object.create(superCtor.prototype, {
+ constructor: {
+ value: ctor,
+ enumerable: false,
+ writable: true,
+ configurable: true
+ }
+ });
+ }
+ };
+} else {
+ // old school shim for old browsers
+ module.exports = function inherits(ctor, superCtor) {
+ if (superCtor) {
+ ctor.super_ = superCtor;
+
+ var TempCtor = function () {};
+
+ TempCtor.prototype = superCtor.prototype;
+ ctor.prototype = new TempCtor();
+ ctor.prototype.constructor = ctor;
+ }
+ };
+}
+
+/***/ }),
+/* 1005 */
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("events");
+
+/***/ }),
+/* 1006 */
+/***/ ((module) => {
+
+"use strict";
+
+
+function posix(path) {
+ return path.charAt(0) === '/';
+}
+
+function win32(path) {
+ // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
+ var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
+ var result = splitDeviceRe.exec(path);
+ var device = result[1] || '';
+ var isUnc = Boolean(device && device.charAt(1) !== ':'); // UNC paths are always absolute
+
+ return Boolean(result[2] || isUnc);
+}
+
+module.exports = process.platform === 'win32' ? win32 : posix;
+module.exports.posix = posix;
+module.exports.win32 = win32;
+
+/***/ }),
+/* 1007 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+module.exports = globSync;
+globSync.GlobSync = GlobSync;
+
+var rp = __webpack_require__(1002);
+
+var minimatch = __webpack_require__(953);
+
+var Minimatch = minimatch.Minimatch;
+
+var Glob = (__webpack_require__(1001).Glob);
+
+var util = __webpack_require__(516);
+
+var path = __webpack_require__(501);
+
+var assert = __webpack_require__(503);
+
+var isAbsolute = __webpack_require__(1006);
+
+var common = __webpack_require__(1008);
+
+var setopts = common.setopts;
+var ownProp = common.ownProp;
+var childrenIgnored = common.childrenIgnored;
+var isIgnored = common.isIgnored;
+
+function globSync(pattern, options) {
+ if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n' + 'See: https://github.com/isaacs/node-glob/issues/167');
+ return new GlobSync(pattern, options).found;
+}
+
+function GlobSync(pattern, options) {
+ if (!pattern) throw new Error('must provide pattern');
+ if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n' + 'See: https://github.com/isaacs/node-glob/issues/167');
+ if (!(this instanceof GlobSync)) return new GlobSync(pattern, options);
+ setopts(this, pattern, options);
+ if (this.noprocess) return this;
+ var n = this.minimatch.set.length;
+ this.matches = new Array(n);
+
+ for (var i = 0; i < n; i++) {
+ this._process(this.minimatch.set[i], i, false);
+ }
+
+ this._finish();
+}
+
+GlobSync.prototype._finish = function () {
+ assert.ok(this instanceof GlobSync);
+
+ if (this.realpath) {
+ var self = this;
+ this.matches.forEach(function (matchset, index) {
+ var set = self.matches[index] = Object.create(null);
+
+ for (var p in matchset) {
+ try {
+ p = self._makeAbs(p);
+ var real = rp.realpathSync(p, self.realpathCache);
+ set[real] = true;
+ } catch (er) {
+ if (er.syscall === 'stat') set[self._makeAbs(p)] = true;else throw er;
+ }
+ }
+ });
+ }
+
+ common.finish(this);
+};
+
+GlobSync.prototype._process = function (pattern, index, inGlobStar) {
+ assert.ok(this instanceof GlobSync); // Get the first [n] parts of pattern that are all strings.
+
+ var n = 0;
+
+ while (typeof pattern[n] === 'string') {
+ n++;
+ } // now n is the index of the first one that is *not* a string.
+ // See if there's anything else
+
+
+ var prefix;
+
+ switch (n) {
+ // if not, then this is rather simple
+ case pattern.length:
+ this._processSimple(pattern.join('/'), index);
+
+ return;
+
+ case 0:
+ // pattern *starts* with some non-trivial item.
+ // going to readdir(cwd), but not include the prefix in matches.
+ prefix = null;
+ break;
+
+ default:
+ // pattern has some string bits in the front.
+ // whatever it starts with, whether that's 'absolute' like /foo/bar,
+ // or 'relative' like '../baz'
+ prefix = pattern.slice(0, n).join('/');
+ break;
+ }
+
+ var remain = pattern.slice(n); // get the list of entries.
+
+ var read;
+ if (prefix === null) read = '.';else if (isAbsolute(prefix) || isAbsolute(pattern.map(function (p) {
+ return typeof p === 'string' ? p : '[*]';
+ }).join('/'))) {
+ if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix;
+ read = prefix;
+ } else read = prefix;
+
+ var abs = this._makeAbs(read); //if ignored, skip processing
+
+
+ if (childrenIgnored(this, read)) return;
+ var isGlobStar = remain[0] === minimatch.GLOBSTAR;
+ if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);else this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
+};
+
+GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
+ var entries = this._readdir(abs, inGlobStar); // if the abs isn't a dir, then nothing can match!
+
+
+ if (!entries) return; // It will only match dot entries if it starts with a dot, or if
+ // dot is set. Stuff like @(.foo|.bar) isn't allowed.
+
+ var pn = remain[0];
+ var negate = !!this.minimatch.negate;
+ var rawGlob = pn._glob;
+ var dotOk = this.dot || rawGlob.charAt(0) === '.';
+ var matchedEntries = [];
+
+ for (var i = 0; i < entries.length; i++) {
+ var e = entries[i];
+
+ if (e.charAt(0) !== '.' || dotOk) {
+ var m;
+
+ if (negate && !prefix) {
+ m = !e.match(pn);
+ } else {
+ m = e.match(pn);
+ }
+
+ if (m) matchedEntries.push(e);
+ }
+ }
+
+ var len = matchedEntries.length; // If there are no matched entries, then nothing matches.
+
+ if (len === 0) return; // if this is the last remaining pattern bit, then no need for
+ // an additional stat *unless* the user has specified mark or
+ // stat explicitly. We know they exist, since readdir returned
+ // them.
+
+ if (remain.length === 1 && !this.mark && !this.stat) {
+ if (!this.matches[index]) this.matches[index] = Object.create(null);
+
+ for (var i = 0; i < len; i++) {
+ var e = matchedEntries[i];
+
+ if (prefix) {
+ if (prefix.slice(-1) !== '/') e = prefix + '/' + e;else e = prefix + e;
+ }
+
+ if (e.charAt(0) === '/' && !this.nomount) {
+ e = path.join(this.root, e);
+ }
+
+ this._emitMatch(index, e);
+ } // This was the last one, and no stats were needed
+
+
+ return;
+ } // now test all matched entries as stand-ins for that part
+ // of the pattern.
+
+
+ remain.shift();
+
+ for (var i = 0; i < len; i++) {
+ var e = matchedEntries[i];
+ var newPattern;
+ if (prefix) newPattern = [prefix, e];else newPattern = [e];
+
+ this._process(newPattern.concat(remain), index, inGlobStar);
+ }
+};
+
+GlobSync.prototype._emitMatch = function (index, e) {
+ if (isIgnored(this, e)) return;
+
+ var abs = this._makeAbs(e);
+
+ if (this.mark) e = this._mark(e);
+
+ if (this.absolute) {
+ e = abs;
+ }
+
+ if (this.matches[index][e]) return;
+
+ if (this.nodir) {
+ var c = this.cache[abs];
+ if (c === 'DIR' || Array.isArray(c)) return;
+ }
+
+ this.matches[index][e] = true;
+ if (this.stat) this._stat(e);
+};
+
+GlobSync.prototype._readdirInGlobStar = function (abs) {
+ // follow all symlinked directories forever
+ // just proceed as if this is a non-globstar situation
+ if (this.follow) return this._readdir(abs, false);
+ var entries;
+ var lstat;
+ var stat;
+
+ try {
+ lstat = this.fs.lstatSync(abs);
+ } catch (er) {
+ if (er.code === 'ENOENT') {
+ // lstat failed, doesn't exist
+ return null;
+ }
+ }
+
+ var isSym = lstat && lstat.isSymbolicLink();
+ this.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file.
+ // don't bother doing a readdir in that case.
+
+ if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = 'FILE';else entries = this._readdir(abs, false);
+ return entries;
+};
+
+GlobSync.prototype._readdir = function (abs, inGlobStar) {
+ var entries;
+ if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs);
+
+ if (ownProp(this.cache, abs)) {
+ var c = this.cache[abs];
+ if (!c || c === 'FILE') return null;
+ if (Array.isArray(c)) return c;
+ }
+
+ try {
+ return this._readdirEntries(abs, this.fs.readdirSync(abs));
+ } catch (er) {
+ this._readdirError(abs, er);
+
+ return null;
+ }
+};
+
+GlobSync.prototype._readdirEntries = function (abs, entries) {
+ // if we haven't asked to stat everything, then just
+ // assume that everything in there exists, so we can avoid
+ // having to stat it a second time.
+ if (!this.mark && !this.stat) {
+ for (var i = 0; i < entries.length; i++) {
+ var e = entries[i];
+ if (abs === '/') e = abs + e;else e = abs + '/' + e;
+ this.cache[e] = true;
+ }
+ }
+
+ this.cache[abs] = entries; // mark and cache dir-ness
+
+ return entries;
+};
+
+GlobSync.prototype._readdirError = function (f, er) {
+ // handle errors, and cache the information
+ switch (er.code) {
+ case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
+
+ case 'ENOTDIR':
+ // totally normal. means it *does* exist.
+ var abs = this._makeAbs(f);
+
+ this.cache[abs] = 'FILE';
+
+ if (abs === this.cwdAbs) {
+ var error = new Error(er.code + ' invalid cwd ' + this.cwd);
+ error.path = this.cwd;
+ error.code = er.code;
+ throw error;
+ }
+
+ break;
+
+ case 'ENOENT': // not terribly unusual
+
+ case 'ELOOP':
+ case 'ENAMETOOLONG':
+ case 'UNKNOWN':
+ this.cache[this._makeAbs(f)] = false;
+ break;
+
+ default:
+ // some unusual error. Treat as failure.
+ this.cache[this._makeAbs(f)] = false;
+ if (this.strict) throw er;
+ if (!this.silent) console.error('glob error', er);
+ break;
+ }
+};
+
+GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
+ var entries = this._readdir(abs, inGlobStar); // no entries means not a dir, so it can never have matches
+ // foo.txt/** doesn't match foo.txt
+
+
+ if (!entries) return; // test without the globstar, and with every child both below
+ // and replacing the globstar.
+
+ var remainWithoutGlobStar = remain.slice(1);
+ var gspref = prefix ? [prefix] : [];
+ var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state
+
+ this._process(noGlobStar, index, false);
+
+ var len = entries.length;
+ var isSym = this.symlinks[abs]; // If it's a symlink, and we're in a globstar, then stop
+
+ if (isSym && inGlobStar) return;
+
+ for (var i = 0; i < len; i++) {
+ var e = entries[i];
+ if (e.charAt(0) === '.' && !this.dot) continue; // these two cases enter the inGlobStar state
+
+ var instead = gspref.concat(entries[i], remainWithoutGlobStar);
+
+ this._process(instead, index, true);
+
+ var below = gspref.concat(entries[i], remain);
+
+ this._process(below, index, true);
+ }
+};
+
+GlobSync.prototype._processSimple = function (prefix, index) {
+ // XXX review this. Shouldn't it be doing the mounting etc
+ // before doing stat? kinda weird?
+ var exists = this._stat(prefix);
+
+ if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results
+
+ if (!exists) return;
+
+ if (prefix && isAbsolute(prefix) && !this.nomount) {
+ var trail = /[\/\\]$/.test(prefix);
+
+ if (prefix.charAt(0) === '/') {
+ prefix = path.join(this.root, prefix);
+ } else {
+ prefix = path.resolve(this.root, prefix);
+ if (trail) prefix += '/';
+ }
+ }
+
+ if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match
+
+ this._emitMatch(index, prefix);
+}; // Returns either 'DIR', 'FILE', or false
+
+
+GlobSync.prototype._stat = function (f) {
+ var abs = this._makeAbs(f);
+
+ var needDir = f.slice(-1) === '/';
+ if (f.length > this.maxLength) return false;
+
+ if (!this.stat && ownProp(this.cache, abs)) {
+ var c = this.cache[abs];
+ if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it
+
+ if (!needDir || c === 'DIR') return c;
+ if (needDir && c === 'FILE') return false; // otherwise we have to stat, because maybe c=true
+ // if we know it exists, but not what it is.
+ }
+
+ var exists;
+ var stat = this.statCache[abs];
+
+ if (!stat) {
+ var lstat;
+
+ try {
+ lstat = this.fs.lstatSync(abs);
+ } catch (er) {
+ if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
+ this.statCache[abs] = false;
+ return false;
+ }
+ }
+
+ if (lstat && lstat.isSymbolicLink()) {
+ try {
+ stat = this.fs.statSync(abs);
+ } catch (er) {
+ stat = lstat;
+ }
+ } else {
+ stat = lstat;
+ }
+ }
+
+ this.statCache[abs] = stat;
+ var c = true;
+ if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE';
+ this.cache[abs] = this.cache[abs] || c;
+ if (needDir && c === 'FILE') return false;
+ return c;
+};
+
+GlobSync.prototype._mark = function (p) {
+ return common.mark(this, p);
+};
+
+GlobSync.prototype._makeAbs = function (f) {
+ return common.makeAbs(this, f);
+};
+
+/***/ }),
+/* 1008 */
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+exports.setopts = setopts;
+exports.ownProp = ownProp;
+exports.makeAbs = makeAbs;
+exports.finish = finish;
+exports.mark = mark;
+exports.isIgnored = isIgnored;
+exports.childrenIgnored = childrenIgnored;
+
+function ownProp(obj, field) {
+ return Object.prototype.hasOwnProperty.call(obj, field);
+}
+
+var fs = __webpack_require__(971);
+
+var path = __webpack_require__(501);
+
+var minimatch = __webpack_require__(953);
+
+var isAbsolute = __webpack_require__(1006);
+
+var Minimatch = minimatch.Minimatch;
+
+function alphasort(a, b) {
+ return a.localeCompare(b, 'en');
+}
+
+function setupIgnores(self, options) {
+ self.ignore = options.ignore || [];
+ if (!Array.isArray(self.ignore)) self.ignore = [self.ignore];
+
+ if (self.ignore.length) {
+ self.ignore = self.ignore.map(ignoreMap);
+ }
+} // ignore patterns are always in dot:true mode.
+
+
+function ignoreMap(pattern) {
+ var gmatcher = null;
+
+ if (pattern.slice(-3) === '/**') {
+ var gpattern = pattern.replace(/(\/\*\*)+$/, '');
+ gmatcher = new Minimatch(gpattern, {
+ dot: true
+ });
+ }
+
+ return {
+ matcher: new Minimatch(pattern, {
+ dot: true
+ }),
+ gmatcher: gmatcher
+ };
+}
+
+function setopts(self, pattern, options) {
+ if (!options) options = {}; // base-matching: just use globstar for that.
+
+ if (options.matchBase && -1 === pattern.indexOf("/")) {
+ if (options.noglobstar) {
+ throw new Error("base matching requires globstar");
+ }
+
+ pattern = "**/" + pattern;
+ }
+
+ self.silent = !!options.silent;
+ self.pattern = pattern;
+ self.strict = options.strict !== false;
+ self.realpath = !!options.realpath;
+ self.realpathCache = options.realpathCache || Object.create(null);
+ self.follow = !!options.follow;
+ self.dot = !!options.dot;
+ self.mark = !!options.mark;
+ self.nodir = !!options.nodir;
+ if (self.nodir) self.mark = true;
+ self.sync = !!options.sync;
+ self.nounique = !!options.nounique;
+ self.nonull = !!options.nonull;
+ self.nosort = !!options.nosort;
+ self.nocase = !!options.nocase;
+ self.stat = !!options.stat;
+ self.noprocess = !!options.noprocess;
+ self.absolute = !!options.absolute;
+ self.fs = options.fs || fs;
+ self.maxLength = options.maxLength || Infinity;
+ self.cache = options.cache || Object.create(null);
+ self.statCache = options.statCache || Object.create(null);
+ self.symlinks = options.symlinks || Object.create(null);
+ setupIgnores(self, options);
+ self.changedCwd = false;
+ var cwd = process.cwd();
+ if (!ownProp(options, "cwd")) self.cwd = cwd;else {
+ self.cwd = path.resolve(options.cwd);
+ self.changedCwd = self.cwd !== cwd;
+ }
+ self.root = options.root || path.resolve(self.cwd, "/");
+ self.root = path.resolve(self.root);
+ if (process.platform === "win32") self.root = self.root.replace(/\\/g, "/"); // TODO: is an absolute `cwd` supposed to be resolved against `root`?
+ // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
+
+ self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
+ if (process.platform === "win32") self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
+ self.nomount = !!options.nomount; // disable comments and negation in Minimatch.
+ // Note that they are not supported in Glob itself anyway.
+
+ options.nonegate = true;
+ options.nocomment = true; // always treat \ in patterns as escapes, not path separators
+
+ options.allowWindowsEscape = false;
+ self.minimatch = new Minimatch(pattern, options);
+ self.options = self.minimatch.options;
+}
+
+function finish(self) {
+ var nou = self.nounique;
+ var all = nou ? [] : Object.create(null);
+
+ for (var i = 0, l = self.matches.length; i < l; i++) {
+ var matches = self.matches[i];
+
+ if (!matches || Object.keys(matches).length === 0) {
+ if (self.nonull) {
+ // do like the shell, and spit out the literal glob
+ var literal = self.minimatch.globSet[i];
+ if (nou) all.push(literal);else all[literal] = true;
+ }
+ } else {
+ // had matches
+ var m = Object.keys(matches);
+ if (nou) all.push.apply(all, m);else m.forEach(function (m) {
+ all[m] = true;
+ });
+ }
+ }
+
+ if (!nou) all = Object.keys(all);
+ if (!self.nosort) all = all.sort(alphasort); // at *some* point we statted all of these
+
+ if (self.mark) {
+ for (var i = 0; i < all.length; i++) {
+ all[i] = self._mark(all[i]);
+ }
+
+ if (self.nodir) {
+ all = all.filter(function (e) {
+ var notDir = !/\/$/.test(e);
+ var c = self.cache[e] || self.cache[makeAbs(self, e)];
+ if (notDir && c) notDir = c !== 'DIR' && !Array.isArray(c);
+ return notDir;
+ });
+ }
+ }
+
+ if (self.ignore.length) all = all.filter(function (m) {
+ return !isIgnored(self, m);
+ });
+ self.found = all;
+}
+
+function mark(self, p) {
+ var abs = makeAbs(self, p);
+ var c = self.cache[abs];
+ var m = p;
+
+ if (c) {
+ var isDir = c === 'DIR' || Array.isArray(c);
+ var slash = p.slice(-1) === '/';
+ if (isDir && !slash) m += '/';else if (!isDir && slash) m = m.slice(0, -1);
+
+ if (m !== p) {
+ var mabs = makeAbs(self, m);
+ self.statCache[mabs] = self.statCache[abs];
+ self.cache[mabs] = self.cache[abs];
+ }
+ }
+
+ return m;
+} // lotta situps...
+
+
+function makeAbs(self, f) {
+ var abs = f;
+
+ if (f.charAt(0) === '/') {
+ abs = path.join(self.root, f);
+ } else if (isAbsolute(f) || f === '') {
+ abs = f;
+ } else if (self.changedCwd) {
+ abs = path.resolve(self.cwd, f);
+ } else {
+ abs = path.resolve(f);
+ }
+
+ if (process.platform === 'win32') abs = abs.replace(/\\/g, '/');
+ return abs;
+} // Return true, if pattern ends with globstar '**', for the accompanying parent directory.
+// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
+
+
+function isIgnored(self, path) {
+ if (!self.ignore.length) return false;
+ return self.ignore.some(function (item) {
+ return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path));
+ });
+}
+
+function childrenIgnored(self, path) {
+ if (!self.ignore.length) return false;
+ return self.ignore.some(function (item) {
+ return !!(item.gmatcher && item.gmatcher.match(path));
+ });
+}
+
+/***/ }),
+/* 1009 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+var wrappy = __webpack_require__(1010);
+
+var reqs = Object.create(null);
+
+var once = __webpack_require__(1011);
+
+module.exports = wrappy(inflight);
+
+function inflight(key, cb) {
+ if (reqs[key]) {
+ reqs[key].push(cb);
+ return null;
+ } else {
+ reqs[key] = [cb];
+ return makeres(key);
+ }
+}
+
+function makeres(key) {
+ return once(function RES() {
+ var cbs = reqs[key];
+ var len = cbs.length;
+ var args = slice(arguments); // XXX It's somewhat ambiguous whether a new callback added in this
+ // pass should be queued for later execution if something in the
+ // list of callbacks throws, or if it should just be discarded.
+ // However, it's such an edge case that it hardly matters, and either
+ // choice is likely as surprising as the other.
+ // As it happens, we do go ahead and schedule it for later execution.
+
+ try {
+ for (var i = 0; i < len; i++) {
+ cbs[i].apply(null, args);
+ }
+ } finally {
+ if (cbs.length > len) {
+ // added more in the interim.
+ // de-zalgo, just in case, but don't call again.
+ cbs.splice(0, len);
+ process.nextTick(function () {
+ RES.apply(null, args);
+ });
+ } else {
+ delete reqs[key];
+ }
+ }
+ });
+}
+
+function slice(args) {
+ var length = args.length;
+ var array = [];
+
+ for (var i = 0; i < length; i++) array[i] = args[i];
+
+ return array;
+}
+
+/***/ }),
+/* 1010 */
+/***/ ((module) => {
+
+// Returns a wrapper function that returns a wrapped callback
+// The wrapper function should do some stuff, and return a
+// presumably different callback function.
+// This makes sure that own properties are retained, so that
+// decorations and such are not lost along the way.
+module.exports = wrappy;
+
+function wrappy(fn, cb) {
+ if (fn && cb) return wrappy(fn)(cb);
+ if (typeof fn !== 'function') throw new TypeError('need wrapper function');
+ Object.keys(fn).forEach(function (k) {
+ wrapper[k] = fn[k];
+ });
+ return wrapper;
+
+ function wrapper() {
+ var args = new Array(arguments.length);
+
+ for (var i = 0; i < args.length; i++) {
+ args[i] = arguments[i];
+ }
+
+ var ret = fn.apply(this, args);
+ var cb = args[args.length - 1];
+
+ if (typeof ret === 'function' && ret !== cb) {
+ Object.keys(cb).forEach(function (k) {
+ ret[k] = cb[k];
+ });
+ }
+
+ return ret;
+ }
+}
+
+/***/ }),
+/* 1011 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+var wrappy = __webpack_require__(1010);
+
+module.exports = wrappy(once);
+module.exports.strict = wrappy(onceStrict);
+once.proto = once(function () {
+ Object.defineProperty(Function.prototype, 'once', {
+ value: function () {
+ return once(this);
+ },
+ configurable: true
+ });
+ Object.defineProperty(Function.prototype, 'onceStrict', {
+ value: function () {
+ return onceStrict(this);
+ },
+ configurable: true
+ });
+});
+
+function once(fn) {
+ var f = function () {
+ if (f.called) return f.value;
+ f.called = true;
+ return f.value = fn.apply(this, arguments);
+ };
+
+ f.called = false;
+ return f;
+}
+
+function onceStrict(fn) {
+ var f = function () {
+ if (f.called) throw new Error(f.onceError);
+ f.called = true;
+ return f.value = fn.apply(this, arguments);
+ };
+
+ var name = fn.name || 'Function wrapped with `once`';
+ f.onceError = name + " shouldn't be called more than once";
+ f.called = false;
+ return f;
+}
+
+/***/ }),
+/* 1012 */
+/***/ ((module) => {
+
+module.exports = function (obj, opts) {
+ if (!opts) opts = {};
+ if (typeof opts === 'function') opts = {
+ cmp: opts
+ };
+ var space = opts.space || '';
+ if (typeof space === 'number') space = Array(space + 1).join(' ');
+ var cycles = typeof opts.cycles === 'boolean' ? opts.cycles : false;
+
+ var replacer = opts.replacer || function (key, value) {
+ return value;
+ };
+
+ var cmp = opts.cmp && function (f) {
+ return function (node) {
+ return function (a, b) {
+ var aobj = {
+ key: a,
+ value: node[a]
+ };
+ var bobj = {
+ key: b,
+ value: node[b]
+ };
+ return f(aobj, bobj);
+ };
+ };
+ }(opts.cmp);
+
+ var seen = [];
+ return function stringify(parent, key, node, level) {
+ var indent = space ? '\n' + new Array(level + 1).join(space) : '';
+ var colonSeparator = space ? ': ' : ':';
+
+ if (node && node.toJSON && typeof node.toJSON === 'function') {
+ node = node.toJSON();
+ }
+
+ node = replacer.call(parent, key, node);
+
+ if (node === undefined) {
+ return;
+ }
+
+ if (typeof node !== 'object' || node === null) {
+ return JSON.stringify(node);
+ }
+
+ if (isArray(node)) {
+ var out = [];
+
+ for (var i = 0; i < node.length; i++) {
+ var item = stringify(node, i, node[i], level + 1) || JSON.stringify(null);
+ out.push(indent + space + item);
+ }
+
+ return '[' + out.join(',') + indent + ']';
+ } else {
+ if (seen.indexOf(node) !== -1) {
+ if (cycles) return JSON.stringify('__cycle__');
+ throw new TypeError('Converting circular structure to JSON');
+ } else seen.push(node);
+
+ var keys = objectKeys(node).sort(cmp && cmp(node));
+ var out = [];
+
+ for (var i = 0; i < keys.length; i++) {
+ var key = keys[i];
+ var value = stringify(node, key, node[key], level + 1);
+ if (!value) continue;
+ var keyValue = JSON.stringify(key) + colonSeparator + value;
+ ;
+ out.push(indent + space + keyValue);
+ }
+
+ seen.splice(seen.indexOf(node), 1);
+ return '{' + out.join(',') + indent + '}';
+ }
+ }({
+ '': obj
+ }, '', obj, 0);
+};
+
+var isArray = Array.isArray || function (x) {
+ return {}.toString.call(x) === '[object Array]';
+};
+
+var objectKeys = Object.keys || function (obj) {
+ var has = Object.prototype.hasOwnProperty || function () {
+ return true;
+ };
+
+ var keys = [];
+
+ for (var key in obj) {
+ if (has.call(obj, key)) keys.push(key);
+ }
+
+ return keys;
+};
+
+/***/ }),
+/* 1013 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+/**
+ * @fileoverview Main class using flat config
+ * @author Nicholas C. Zakas
+ */
+ //------------------------------------------------------------------------------
+// Requirements
+//------------------------------------------------------------------------------
+// Note: Node.js 12 does not support fs/promises.
+
+const fs = (__webpack_require__(971).promises);
+
+const path = __webpack_require__(501);
+
+const findUp = __webpack_require__(1014);
+
+const {
+ version
+} = __webpack_require__(513);
+
+const {
+ Linter
+} = __webpack_require__(988);
+
+const {
+ getRuleFromConfig
+} = __webpack_require__(950);
+
+const {
+ gitignoreToMinimatch
+} = __webpack_require__(1020);
+
+const {
+ Legacy: {
+ ConfigOps: {
+ getRuleSeverity
+ },
+ ModuleResolver,
+ naming
+ }
+} = __webpack_require__(974);
+
+const {
+ fileExists,
+ findFiles,
+ getCacheFile,
+ isNonEmptyString,
+ isArrayOfNonEmptyString,
+ createIgnoreResult,
+ isErrorMessage,
+ processOptions
+} = __webpack_require__(1021);
+
+const {
+ pathToFileURL
+} = __webpack_require__(983);
+
+const {
+ FlatConfigArray
+} = __webpack_require__(951);
+
+const LintResultCache = __webpack_require__(993);
+/*
+ * This is necessary to allow overwriting writeFile for testing purposes.
+ * We can just use fs/promises once we drop Node.js 12 support.
+ */
+//------------------------------------------------------------------------------
+// Typedefs
+//------------------------------------------------------------------------------
+// For VSCode IntelliSense
+
+/** @typedef {import("../shared/types").ConfigData} ConfigData */
+
+/** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */
+
+/** @typedef {import("../shared/types").LintMessage} LintMessage */
+
+/** @typedef {import("../shared/types").ParserOptions} ParserOptions */
+
+/** @typedef {import("../shared/types").Plugin} Plugin */
+
+/** @typedef {import("../shared/types").RuleConf} RuleConf */
+
+/** @typedef {import("../shared/types").Rule} Rule */
+
+/** @typedef {ReturnType<ConfigArray.extractConfig>} ExtractedConfig */
+
+/**
+ * The options with which to configure the ESLint instance.
+ * @typedef {Object} FlatESLintOptions
+ * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments.
+ * @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this instance
+ * @property {boolean} [cache] Enable result caching.
+ * @property {string} [cacheLocation] The cache file to use instead of .eslintcache.
+ * @property {"metadata" | "content"} [cacheStrategy] The strategy used to detect changed files.
+ * @property {string} [cwd] The value to use for the current working directory.
+ * @property {boolean} [errorOnUnmatchedPattern] If `false` then `ESLint#lintFiles()` doesn't throw even if no target files found. Defaults to `true`.
+ * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean.
+ * @property {string[]} [fixTypes] Array of rule types to apply fixes for.
+ * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file.
+ * @property {boolean} [ignore] False disables use of .eslintignore.
+ * @property {string} [ignorePath] The ignore file to use instead of .eslintignore.
+ * @property {string[]} [ignorePatterns] Ignore file patterns to use in addition to .eslintignore.
+ * @property {ConfigData} [overrideConfig] Override config object, overrides all configs used with this instance
+ * @property {boolean|string} [overrideConfigFile] Searches for default config file when falsy;
+ * doesn't do any config file lookup when `true`; considered to be a config filename
+ * when a string.
+ * @property {Record<string,Plugin>} [plugins] An array of plugin implementations.
+ * @property {"error" | "warn" | "off"} [reportUnusedDisableDirectives] the severity to report unused eslint-disable directives.
+ */
+//------------------------------------------------------------------------------
+// Helpers
+//------------------------------------------------------------------------------
+
+
+const FLAT_CONFIG_FILENAME = "eslint.config.js";
+
+const debug = __webpack_require__(566)("eslint:flat-eslint");
+
+const removedFormatters = new Set(["table", "codeframe"]);
+const privateMembers = new WeakMap();
+/**
+ * It will calculate the error and warning count for collection of messages per file
+ * @param {LintMessage[]} messages Collection of messages
+ * @returns {Object} Contains the stats
+ * @private
+ */
+
+function calculateStatsPerFile(messages) {
+ return messages.reduce((stat, message) => {
+ if (message.fatal || message.severity === 2) {
+ stat.errorCount++;
+
+ if (message.fatal) {
+ stat.fatalErrorCount++;
+ }
+
+ if (message.fix) {
+ stat.fixableErrorCount++;
+ }
+ } else {
+ stat.warningCount++;
+
+ if (message.fix) {
+ stat.fixableWarningCount++;
+ }
+ }
+
+ return stat;
+ }, {
+ errorCount: 0,
+ fatalErrorCount: 0,
+ warningCount: 0,
+ fixableErrorCount: 0,
+ fixableWarningCount: 0
+ });
+}
+/**
+ * It will calculate the error and warning count for collection of results from all files
+ * @param {LintResult[]} results Collection of messages from all the files
+ * @returns {Object} Contains the stats
+ * @private
+ */
+
+
+function calculateStatsPerRun(results) {
+ return results.reduce((stat, result) => {
+ stat.errorCount += result.errorCount;
+ stat.fatalErrorCount += result.fatalErrorCount;
+ stat.warningCount += result.warningCount;
+ stat.fixableErrorCount += result.fixableErrorCount;
+ stat.fixableWarningCount += result.fixableWarningCount;
+ return stat;
+ }, {
+ errorCount: 0,
+ fatalErrorCount: 0,
+ warningCount: 0,
+ fixableErrorCount: 0,
+ fixableWarningCount: 0
+ });
+}
+/**
+ * Loads global ignore patterns from an ignore file (usually .eslintignore).
+ * @param {string} filePath The filename to load.
+ * @returns {ignore} A function encapsulating the ignore patterns.
+ * @throws {Error} If the file cannot be read.
+ * @private
+ */
+
+
+async function loadIgnoreFilePatterns(filePath) {
+ debug(`Loading ignore file: ${filePath}`);
+
+ try {
+ const ignoreFileText = await fs.readFile(filePath, {
+ encoding: "utf8"
+ });
+ return ignoreFileText.split(/\r?\n/gu).filter(line => line.trim() !== "" && !line.startsWith("#"));
+ } catch (e) {
+ debug(`Error reading ignore file: ${filePath}`);
+ e.message = `Cannot read ignore file: ${filePath}\nError: ${e.message}`;
+ throw e;
+ }
+}
+/**
+ * Create rulesMeta object.
+ * @param {Map<string,Rule>} rules a map of rules from which to generate the object.
+ * @returns {Object} metadata for all enabled rules.
+ */
+
+
+function createRulesMeta(rules) {
+ return Array.from(rules).reduce((retVal, _ref) => {
+ let [id, rule] = _ref;
+ retVal[id] = rule.meta;
+ return retVal;
+ }, {});
+}
+/** @type {WeakMap<ExtractedConfig, DeprecatedRuleInfo[]>} */
+
+
+const usedDeprecatedRulesCache = new WeakMap();
+/**
+ * Create used deprecated rule list.
+ * @param {CLIEngine} eslint The CLIEngine instance.
+ * @param {string} maybeFilePath The absolute path to a lint target file or `"<text>"`.
+ * @returns {DeprecatedRuleInfo[]} The used deprecated rule list.
+ */
+
+function getOrFindUsedDeprecatedRules(eslint, maybeFilePath) {
+ const {
+ configs,
+ options: {
+ cwd
+ }
+ } = privateMembers.get(eslint);
+ const filePath = path.isAbsolute(maybeFilePath) ? maybeFilePath : path.join(cwd, "__placeholder__.js");
+ const config = configs.getConfig(filePath); // Most files use the same config, so cache it.
+
+ if (config && !usedDeprecatedRulesCache.has(config)) {
+ const retv = [];
+
+ if (config.rules) {
+ for (const [ruleId, ruleConf] of Object.entries(config.rules)) {
+ if (getRuleSeverity(ruleConf) === 0) {
+ continue;
+ }
+
+ const rule = getRuleFromConfig(ruleId, config);
+ const meta = rule && rule.meta;
+
+ if (meta && meta.deprecated) {
+ retv.push({
+ ruleId,
+ replacedBy: meta.replacedBy || []
+ });
+ }
+ }
+ }
+
+ usedDeprecatedRulesCache.set(config, Object.freeze(retv));
+ }
+
+ return config ? usedDeprecatedRulesCache.get(config) : Object.freeze([]);
+}
+/**
+ * Processes the linting results generated by a CLIEngine linting report to
+ * match the ESLint class's API.
+ * @param {CLIEngine} eslint The CLIEngine instance.
+ * @param {CLIEngineLintReport} report The CLIEngine linting report to process.
+ * @returns {LintResult[]} The processed linting results.
+ */
+
+
+function processLintReport(eslint, _ref2) {
+ let {
+ results
+ } = _ref2;
+ const descriptor = {
+ configurable: true,
+ enumerable: true,
+
+ get() {
+ return getOrFindUsedDeprecatedRules(eslint, this.filePath);
+ }
+
+ };
+
+ for (const result of results) {
+ Object.defineProperty(result, "usedDeprecatedRules", descriptor);
+ }
+
+ return results;
+}
+/**
+ * An Array.prototype.sort() compatible compare function to order results by their file path.
+ * @param {LintResult} a The first lint result.
+ * @param {LintResult} b The second lint result.
+ * @returns {number} An integer representing the order in which the two results should occur.
+ */
+
+
+function compareResultsByFilePath(a, b) {
+ if (a.filePath < b.filePath) {
+ return -1;
+ }
+
+ if (a.filePath > b.filePath) {
+ return 1;
+ }
+
+ return 0;
+}
+/**
+ * Searches from the current working directory up until finding the
+ * given flat config filename.
+ * @param {string} cwd The current working directory to search from.
+ * @returns {Promise<string|null>} The filename if found or `null` if not.
+ */
+
+
+function findFlatConfigFile(cwd) {
+ return findUp(FLAT_CONFIG_FILENAME, {
+ cwd
+ });
+}
+/**
+ * Load the config array from the given filename.
+ * @param {string} filePath The filename to load from.
+ * @param {Object} options Options to help load the config file.
+ * @param {string} options.basePath The base path for the config array.
+ * @param {boolean} options.shouldIgnore Whether to honor ignore patterns.
+ * @returns {Promise<FlatConfigArray>} The config array loaded from the config file.
+ */
+
+
+async function loadFlatConfigFile(filePath, _ref3) {
+ let {
+ basePath,
+ shouldIgnore
+ } = _ref3;
+ debug(`Loading config from ${filePath}`);
+ const fileURL = pathToFileURL(filePath);
+ debug(`Config file URL is ${fileURL}`);
+ const module = await __webpack_require__(1102)(fileURL);
+ return new FlatConfigArray(module.default, {
+ basePath,
+ shouldIgnore
+ });
+}
+/**
+ * Calculates the config array for this run based on inputs.
+ * @param {FlatESLint} eslint The instance to create the config array for.
+ * @param {import("./eslint").ESLintOptions} options The ESLint instance options.
+ * @returns {FlatConfigArray} The config array for `eslint``.
+ */
+
+
+async function calculateConfigArray(eslint, _ref4) {
+ let {
+ cwd,
+ overrideConfig,
+ configFile,
+ ignore: shouldIgnore,
+ ignorePath,
+ ignorePatterns
+ } = _ref4;
+ // check for cached instance
+ const slots = privateMembers.get(eslint);
+
+ if (slots.configs) {
+ return slots.configs;
+ } // determine where to load config file from
+
+
+ let configFilePath;
+ let basePath = cwd;
+
+ if (typeof configFile === "string") {
+ debug(`Override config file path is ${configFile}`);
+ configFilePath = path.resolve(cwd, configFile);
+ } else if (configFile !== false) {
+ debug("Searching for eslint.config.js");
+ configFilePath = await findFlatConfigFile(cwd);
+
+ if (!configFilePath) {
+ throw new Error("Could not find config file.");
+ }
+
+ basePath = path.resolve(path.dirname(configFilePath));
+ } // load config array
+
+
+ let configs;
+
+ if (configFilePath) {
+ configs = await loadFlatConfigFile(configFilePath, {
+ basePath,
+ shouldIgnore
+ });
+ } else {
+ configs = new FlatConfigArray([], {
+ basePath,
+ shouldIgnore
+ });
+ } // add in any configured defaults
+
+
+ configs.push(...slots.defaultConfigs);
+ let allIgnorePatterns = [];
+ let ignoreFilePath; // load ignore file if necessary
+
+ if (shouldIgnore) {
+ if (ignorePath) {
+ ignoreFilePath = path.resolve(cwd, ignorePath);
+ allIgnorePatterns = await loadIgnoreFilePatterns(ignoreFilePath);
+ } else {
+ ignoreFilePath = path.resolve(cwd, ".eslintignore"); // no error if .eslintignore doesn't exist`
+
+ if (fileExists(ignoreFilePath)) {
+ allIgnorePatterns = await loadIgnoreFilePatterns(ignoreFilePath);
+ }
+ }
+ } // append command line ignore patterns
+
+
+ if (ignorePatterns) {
+ if (typeof ignorePatterns === "string") {
+ allIgnorePatterns.push(ignorePatterns);
+ } else {
+ allIgnorePatterns.push(...ignorePatterns);
+ }
+ }
+ /*
+ * If the config file basePath is different than the cwd, then
+ * the ignore patterns won't work correctly. Here, we adjust the
+ * ignore pattern to include the correct relative path. Patterns
+ * loaded from ignore files are always relative to the cwd, whereas
+ * the config file basePath can be an ancestor of the cwd.
+ */
+
+
+ if (basePath !== cwd && allIgnorePatterns.length) {
+ const relativeIgnorePath = path.relative(basePath, cwd);
+ allIgnorePatterns = allIgnorePatterns.map(pattern => {
+ const negated = pattern.startsWith("!");
+ const basePattern = negated ? pattern.slice(1) : pattern;
+ /*
+ * Ignore patterns are considered relative to a directory
+ * when the pattern contains a slash in a position other
+ * than the last character. If that's the case, we need to
+ * add the relative ignore path to the current pattern to
+ * get the correct behavior. Otherwise, no change is needed.
+ */
+
+ if (!basePattern.includes("/") || basePattern.endsWith("/")) {
+ return pattern;
+ }
+
+ return (negated ? "!" : "") + path.posix.join(relativeIgnorePath, basePattern);
+ });
+ }
+
+ if (allIgnorePatterns.length) {
+ /*
+ * Ignore patterns are added to the end of the config array
+ * so they can override default ignores.
+ */
+ configs.push({
+ ignores: allIgnorePatterns.map(gitignoreToMinimatch)
+ });
+ }
+
+ if (overrideConfig) {
+ if (Array.isArray(overrideConfig)) {
+ configs.push(...overrideConfig);
+ } else {
+ configs.push(overrideConfig);
+ }
+ }
+
+ await configs.normalize(); // cache the config array for this instance
+
+ slots.configs = configs;
+ return configs;
+}
+/**
+ * Processes an source code using ESLint.
+ * @param {Object} config The config object.
+ * @param {string} config.text The source code to verify.
+ * @param {string} config.cwd The path to the current working directory.
+ * @param {string|undefined} config.filePath The path to the file of `text`. If this is undefined, it uses `<text>`.
+ * @param {FlatConfigArray} config.configs The config.
+ * @param {boolean} config.fix If `true` then it does fix.
+ * @param {boolean} config.allowInlineConfig If `true` then it uses directive comments.
+ * @param {boolean} config.reportUnusedDisableDirectives If `true` then it reports unused `eslint-disable` comments.
+ * @param {Linter} config.linter The linter instance to verify.
+ * @returns {LintResult} The result of linting.
+ * @private
+ */
+
+
+function verifyText(_ref5) {
+ let {
+ text,
+ cwd,
+ filePath: providedFilePath,
+ configs,
+ fix,
+ allowInlineConfig,
+ reportUnusedDisableDirectives,
+ linter
+ } = _ref5;
+ const filePath = providedFilePath || "<text>";
+ debug(`Lint ${filePath}`);
+ /*
+ * Verify.
+ * `config.extractConfig(filePath)` requires an absolute path, but `linter`
+ * doesn't know CWD, so it gives `linter` an absolute path always.
+ */
+
+ const filePathToVerify = filePath === "<text>" ? path.join(cwd, "__placeholder__.js") : filePath;
+ const {
+ fixed,
+ messages,
+ output
+ } = linter.verifyAndFix(text, configs, {
+ allowInlineConfig,
+ filename: filePathToVerify,
+ fix,
+ reportUnusedDisableDirectives,
+
+ /**
+ * Check if the linter should adopt a given code block or not.
+ * @param {string} blockFilename The virtual filename of a code block.
+ * @returns {boolean} `true` if the linter should adopt the code block.
+ */
+ filterCodeBlock(blockFilename) {
+ return configs.isExplicitMatch(blockFilename);
+ }
+
+ }); // Tweak and return.
+
+ const result = {
+ filePath: filePath === "<text>" ? filePath : path.resolve(filePath),
+ messages,
+ suppressedMessages: linter.getSuppressedMessages(),
+ ...calculateStatsPerFile(messages)
+ };
+
+ if (fixed) {
+ result.output = output;
+ }
+
+ if (result.errorCount + result.warningCount > 0 && typeof result.output === "undefined") {
+ result.source = text;
+ }
+
+ return result;
+}
+/**
+ * Checks whether a message's rule type should be fixed.
+ * @param {LintMessage} message The message to check.
+ * @param {FlatConfig} config The config for the file that generated the message.
+ * @param {string[]} fixTypes An array of fix types to check.
+ * @returns {boolean} Whether the message should be fixed.
+ */
+
+
+function shouldMessageBeFixed(message, config, fixTypes) {
+ if (!message.ruleId) {
+ return fixTypes.has("directive");
+ }
+
+ const rule = message.ruleId && getRuleFromConfig(message.ruleId, config);
+ return Boolean(rule && rule.meta && fixTypes.has(rule.meta.type));
+}
+/**
+ * Collect used deprecated rules.
+ * @param {Array<FlatConfig>} configs The configs to evaluate.
+ * @returns {IterableIterator<DeprecatedRuleInfo>} Used deprecated rules.
+ */
+
+
+function* iterateRuleDeprecationWarnings(configs) {
+ const processedRuleIds = new Set();
+
+ for (const config of configs) {
+ for (const [ruleId, ruleConfig] of Object.entries(config.rules)) {
+ // Skip if it was processed.
+ if (processedRuleIds.has(ruleId)) {
+ continue;
+ }
+
+ processedRuleIds.add(ruleId); // Skip if it's not used.
+
+ if (!getRuleSeverity(ruleConfig)) {
+ continue;
+ }
+
+ const rule = getRuleFromConfig(ruleId, config); // Skip if it's not deprecated.
+
+ if (!(rule && rule.meta && rule.meta.deprecated)) {
+ continue;
+ } // This rule was used and deprecated.
+
+
+ yield {
+ ruleId,
+ replacedBy: rule.meta.replacedBy || []
+ };
+ }
+ }
+} //-----------------------------------------------------------------------------
+// Main API
+//-----------------------------------------------------------------------------
+
+/**
+ * Primary Node.js API for ESLint.
+ */
+
+
+class FlatESLint {
+ /**
+ * Creates a new instance of the main ESLint API.
+ * @param {FlatESLintOptions} options The options for this instance.
+ */
+ constructor() {
+ let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+ const defaultConfigs = [];
+ const processedOptions = processOptions(options);
+ const linter = new Linter({
+ cwd: processedOptions.cwd,
+ configType: "flat"
+ });
+ const cacheFilePath = getCacheFile(processedOptions.cacheLocation, processedOptions.cwd);
+ const lintResultCache = processedOptions.cache ? new LintResultCache(cacheFilePath, processedOptions.cacheStrategy) : null;
+ privateMembers.set(this, {
+ options: processedOptions,
+ linter,
+ cacheFilePath,
+ lintResultCache,
+ defaultConfigs,
+ defaultIgnores: () => false,
+ configs: null
+ });
+ /**
+ * If additional plugins are passed in, add that to the default
+ * configs for this instance.
+ */
+
+ if (options.plugins) {
+ const plugins = {};
+
+ for (const [pluginName, plugin] of Object.entries(options.plugins)) {
+ plugins[naming.getShorthandName(pluginName, "eslint-plugin")] = plugin;
+ }
+
+ defaultConfigs.push({
+ plugins
+ });
+ }
+ }
+ /**
+ * The version text.
+ * @type {string}
+ */
+
+
+ static get version() {
+ return version;
+ }
+ /**
+ * Outputs fixes from the given results to files.
+ * @param {LintResult[]} results The lint results.
+ * @returns {Promise<void>} Returns a promise that is used to track side effects.
+ */
+
+
+ static async outputFixes(results) {
+ if (!Array.isArray(results)) {
+ throw new Error("'results' must be an array");
+ }
+
+ await Promise.all(results.filter(result => {
+ if (typeof result !== "object" || result === null) {
+ throw new Error("'results' must include only objects");
+ }
+
+ return typeof result.output === "string" && path.isAbsolute(result.filePath);
+ }).map(r => fs.writeFile(r.filePath, r.output)));
+ }
+ /**
+ * Returns results that only contains errors.
+ * @param {LintResult[]} results The results to filter.
+ * @returns {LintResult[]} The filtered results.
+ */
+
+
+ static getErrorResults(results) {
+ const filtered = [];
+ results.forEach(result => {
+ const filteredMessages = result.messages.filter(isErrorMessage);
+ const filteredSuppressedMessages = result.suppressedMessages.filter(isErrorMessage);
+
+ if (filteredMessages.length > 0) {
+ filtered.push({ ...result,
+ messages: filteredMessages,
+ suppressedMessages: filteredSuppressedMessages,
+ errorCount: filteredMessages.length,
+ warningCount: 0,
+ fixableErrorCount: result.fixableErrorCount,
+ fixableWarningCount: 0
+ });
+ }
+ });
+ return filtered;
+ }
+ /**
+ * Returns meta objects for each rule represented in the lint results.
+ * @param {LintResult[]} results The results to fetch rules meta for.
+ * @returns {Object} A mapping of ruleIds to rule meta objects.
+ * @throws {TypeError} When the results object wasn't created from this ESLint instance.
+ * @throws {TypeError} When a plugin or rule is missing.
+ */
+
+
+ getRulesMetaForResults(results) {
+ const resultRules = new Map(); // short-circuit simple case
+
+ if (results.length === 0) {
+ return resultRules;
+ }
+
+ const {
+ configs
+ } = privateMembers.get(this);
+ /*
+ * We can only accurately return rules meta information for linting results if the
+ * results were created by this instance. Otherwise, the necessary rules data is
+ * not available. So if the config array doesn't already exist, just throw an error
+ * to let the user know we can't do anything here.
+ */
+
+ if (!configs) {
+ throw new TypeError("Results object was not created from this ESLint instance.");
+ }
+
+ for (const result of results) {
+ /*
+ * Normalize filename for <text>.
+ */
+ const filePath = result.filePath === "<text>" ? "__placeholder__.js" : result.filePath;
+ /*
+ * All of the plugin and rule information is contained within the
+ * calculated config for the given file.
+ */
+
+ const config = configs.getConfig(filePath);
+ const allMessages = result.messages.concat(result.suppressedMessages);
+
+ for (const {
+ ruleId
+ } of allMessages) {
+ const rule = getRuleFromConfig(ruleId, config); // ensure the rule exists
+
+ if (!rule) {
+ throw new TypeError(`Could not find the rule "${ruleId}".`);
+ }
+
+ resultRules.set(ruleId, rule);
+ }
+ }
+
+ return createRulesMeta(resultRules);
+ }
+ /**
+ * Executes the current configuration on an array of file and directory names.
+ * @param {string|string[]} patterns An array of file and directory names.
+ * @returns {Promise<LintResult[]>} The results of linting the file patterns given.
+ */
+
+
+ async lintFiles(patterns) {
+ if (!isNonEmptyString(patterns) && !isArrayOfNonEmptyString(patterns)) {
+ throw new Error("'patterns' must be a non-empty string or an array of non-empty strings");
+ }
+
+ const {
+ cacheFilePath,
+ lintResultCache,
+ linter,
+ options: eslintOptions
+ } = privateMembers.get(this);
+ const configs = await calculateConfigArray(this, eslintOptions);
+ const {
+ allowInlineConfig,
+ cache,
+ cwd,
+ fix,
+ fixTypes,
+ reportUnusedDisableDirectives,
+ globInputPaths,
+ errorOnUnmatchedPattern
+ } = eslintOptions;
+ const startTime = Date.now();
+ const usedConfigs = [];
+ const fixTypesSet = fixTypes ? new Set(fixTypes) : null; // Delete cache file; should this be done here?
+
+ if (!cache && cacheFilePath) {
+ debug(`Deleting cache file at ${cacheFilePath}`);
+
+ try {
+ await fs.unlink(cacheFilePath);
+ } catch (error) {
+ const errorCode = error && error.code; // Ignore errors when no such file exists or file system is read only (and cache file does not exist)
+
+ if (errorCode !== "ENOENT" && !(errorCode === "EROFS" && !(await fs.exists(cacheFilePath)))) {
+ throw error;
+ }
+ }
+ }
+
+ const filePaths = await findFiles({
+ patterns: typeof patterns === "string" ? [patterns] : patterns,
+ cwd,
+ globInputPaths,
+ configs,
+ errorOnUnmatchedPattern
+ });
+ debug(`${filePaths.length} files found in: ${Date.now() - startTime}ms`);
+ /*
+ * Because we need to process multiple files, including reading from disk,
+ * it is most efficient to start by reading each file via promises so that
+ * they can be done in parallel. Then, we can lint the returned text. This
+ * ensures we are waiting the minimum amount of time in between lints.
+ */
+
+ const results = await Promise.all(filePaths.map(_ref6 => {
+ let {
+ filePath,
+ ignored
+ } = _ref6;
+
+ /*
+ * If a filename was entered that matches an ignore
+ * pattern, then notify the user.
+ */
+ if (ignored) {
+ return createIgnoreResult(filePath, cwd);
+ }
+
+ const config = configs.getConfig(filePath);
+ /*
+ * Sometimes a file found through a glob pattern will
+ * be ignored. In this case, `config` will be undefined
+ * and we just silently ignore the file.
+ */
+
+ if (!config) {
+ return void 0;
+ }
+ /*
+ * Store used configs for:
+ * - this method uses to collect used deprecated rules.
+ * - `--fix-type` option uses to get the loaded rule's meta data.
+ */
+
+
+ if (!usedConfigs.includes(config)) {
+ usedConfigs.push(config);
+ } // Skip if there is cached result.
+
+
+ if (lintResultCache) {
+ const cachedResult = lintResultCache.getCachedLintResults(filePath, config);
+
+ if (cachedResult) {
+ const hadMessages = cachedResult.messages && cachedResult.messages.length > 0;
+
+ if (hadMessages && fix) {
+ debug(`Reprocessing cached file to allow autofix: ${filePath}`);
+ } else {
+ debug(`Skipping file since it hasn't changed: ${filePath}`);
+ return cachedResult;
+ }
+ }
+ } // set up fixer for fixtypes if necessary
+
+
+ let fixer = fix;
+
+ if (fix && fixTypesSet) {
+ // save original value of options.fix in case it's a function
+ const originalFix = typeof fix === "function" ? fix : () => true;
+
+ fixer = message => shouldMessageBeFixed(message, config, fixTypesSet) && originalFix(message);
+ }
+
+ return fs.readFile(filePath, "utf8").then(text => {
+ // do the linting
+ const result = verifyText({
+ text,
+ filePath,
+ configs,
+ cwd,
+ fix: fixer,
+ allowInlineConfig,
+ reportUnusedDisableDirectives,
+ linter
+ });
+ /*
+ * Store the lint result in the LintResultCache.
+ * NOTE: The LintResultCache will remove the file source and any
+ * other properties that are difficult to serialize, and will
+ * hydrate those properties back in on future lint runs.
+ */
+
+ if (lintResultCache) {
+ lintResultCache.setCachedLintResults(filePath, config, result);
+ }
+
+ return result;
+ });
+ })); // Persist the cache to disk.
+
+ if (lintResultCache) {
+ lintResultCache.reconcile();
+ }
+
+ let usedDeprecatedRules;
+ const finalResults = results.filter(result => !!result);
+ return processLintReport(this, {
+ results: finalResults,
+ ...calculateStatsPerRun(finalResults),
+
+ // Initialize it lazily because CLI and `ESLint` API don't use it.
+ get usedDeprecatedRules() {
+ if (!usedDeprecatedRules) {
+ usedDeprecatedRules = Array.from(iterateRuleDeprecationWarnings(usedConfigs));
+ }
+
+ return usedDeprecatedRules;
+ }
+
+ });
+ }
+ /**
+ * Executes the current configuration on text.
+ * @param {string} code A string of JavaScript code to lint.
+ * @param {Object} [options] The options.
+ * @param {string} [options.filePath] The path to the file of the source code.
+ * @param {boolean} [options.warnIgnored] When set to true, warn if given filePath is an ignored path.
+ * @returns {Promise<LintResult[]>} The results of linting the string of code given.
+ */
+
+
+ async lintText(code) {
+ let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+
+ // Parameter validation
+ if (typeof code !== "string") {
+ throw new Error("'code' must be a string");
+ }
+
+ if (typeof options !== "object") {
+ throw new Error("'options' must be an object, null, or undefined");
+ } // Options validation
+
+
+ const {
+ filePath,
+ warnIgnored = false,
+ ...unknownOptions
+ } = options || {};
+ const unknownOptionKeys = Object.keys(unknownOptions);
+
+ if (unknownOptionKeys.length > 0) {
+ throw new Error(`'options' must not include the unknown option(s): ${unknownOptionKeys.join(", ")}`);
+ }
+
+ if (filePath !== void 0 && !isNonEmptyString(filePath)) {
+ throw new Error("'options.filePath' must be a non-empty string or undefined");
+ }
+
+ if (typeof warnIgnored !== "boolean") {
+ throw new Error("'options.warnIgnored' must be a boolean or undefined");
+ } // Now we can get down to linting
+
+
+ const {
+ linter,
+ options: eslintOptions
+ } = privateMembers.get(this);
+ const configs = await calculateConfigArray(this, eslintOptions);
+ const {
+ allowInlineConfig,
+ cwd,
+ fix,
+ reportUnusedDisableDirectives
+ } = eslintOptions;
+ const results = [];
+ const startTime = Date.now();
+ const resolvedFilename = path.resolve(cwd, filePath || "__placeholder__.js");
+ let config; // Clear the last used config arrays.
+
+ if (resolvedFilename && (await this.isPathIgnored(resolvedFilename))) {
+ if (warnIgnored) {
+ results.push(createIgnoreResult(resolvedFilename, cwd));
+ }
+ } else {
+ // TODO: Needed?
+ config = configs.getConfig(resolvedFilename); // Do lint.
+
+ results.push(verifyText({
+ text: code,
+ filePath: resolvedFilename.endsWith("__placeholder__.js") ? "<text>" : resolvedFilename,
+ configs,
+ cwd,
+ fix,
+ allowInlineConfig,
+ reportUnusedDisableDirectives,
+ linter
+ }));
+ }
+
+ debug(`Linting complete in: ${Date.now() - startTime}ms`);
+ let usedDeprecatedRules;
+ return processLintReport(this, {
+ results,
+ ...calculateStatsPerRun(results),
+
+ // Initialize it lazily because CLI and `ESLint` API don't use it.
+ get usedDeprecatedRules() {
+ if (!usedDeprecatedRules) {
+ usedDeprecatedRules = Array.from(iterateRuleDeprecationWarnings(config));
+ }
+
+ return usedDeprecatedRules;
+ }
+
+ });
+ }
+ /**
+ * Returns the formatter representing the given formatter name.
+ * @param {string} [name] The name of the formatter to load.
+ * The following values are allowed:
+ * - `undefined` ... Load `stylish` builtin formatter.
+ * - A builtin formatter name ... Load the builtin formatter.
+ * - A thirdparty formatter name:
+ * - `foo` → `eslint-formatter-foo`
+ * - `@foo` → `@foo/eslint-formatter`
+ * - `@foo/bar` → `@foo/eslint-formatter-bar`
+ * - A file path ... Load the file.
+ * @returns {Promise<Formatter>} A promise resolving to the formatter object.
+ * This promise will be rejected if the given formatter was not found or not
+ * a function.
+ */
+
+
+ async loadFormatter() {
+ let name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "stylish";
+
+ if (typeof name !== "string") {
+ throw new Error("'name' must be a string");
+ } // replace \ with / for Windows compatibility
+
+
+ const normalizedFormatName = name.replace(/\\/gu, "/");
+ const namespace = naming.getNamespaceFromTerm(normalizedFormatName); // grab our options
+
+ const {
+ cwd
+ } = privateMembers.get(this).options;
+ let formatterPath; // if there's a slash, then it's a file (TODO: this check seems dubious for scoped npm packages)
+
+ if (!namespace && normalizedFormatName.includes("/")) {
+ formatterPath = path.resolve(cwd, normalizedFormatName);
+ } else {
+ try {
+ const npmFormat = naming.normalizePackageName(normalizedFormatName, "eslint-formatter"); // TODO: This is pretty dirty...would be nice to clean up at some point.
+
+ formatterPath = ModuleResolver.resolve(npmFormat, path.join(cwd, "__placeholder__.js"));
+ } catch {
+ formatterPath = path.resolve(__dirname, "../", "cli-engine", "formatters", `${normalizedFormatName}.js`);
+ }
+ }
+
+ let formatter;
+
+ try {
+ formatter = (await __webpack_require__(1102)(pathToFileURL(formatterPath))).default;
+ } catch (ex) {
+ // check for formatters that have been removed
+ if (removedFormatters.has(name)) {
+ ex.message = `The ${name} formatter is no longer part of core ESLint. Install it manually with \`npm install -D eslint-formatter-${name}\``;
+ } else {
+ ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`;
+ }
+
+ throw ex;
+ }
+
+ if (typeof formatter !== "function") {
+ throw new TypeError(`Formatter must be a function, but got a ${typeof formatter}.`);
+ }
+
+ const eslint = this;
+ return {
+ /**
+ * The main formatter method.
+ * @param {LintResults[]} results The lint results to format.
+ * @returns {string} The formatted lint results.
+ */
+ format(results) {
+ let rulesMeta = null;
+ results.sort(compareResultsByFilePath);
+ return formatter(results, {
+ cwd,
+
+ get rulesMeta() {
+ if (!rulesMeta) {
+ rulesMeta = eslint.getRulesMetaForResults(results);
+ }
+
+ return rulesMeta;
+ }
+
+ });
+ }
+
+ };
+ }
+ /**
+ * Returns a configuration object for the given file based on the CLI options.
+ * This is the same logic used by the ESLint CLI executable to determine
+ * configuration for each file it processes.
+ * @param {string} filePath The path of the file to retrieve a config object for.
+ * @returns {Promise<ConfigData|undefined>} A configuration object for the file
+ * or `undefined` if there is no configuration data for the object.
+ */
+
+
+ async calculateConfigForFile(filePath) {
+ if (!isNonEmptyString(filePath)) {
+ throw new Error("'filePath' must be a non-empty string");
+ }
+
+ const options = privateMembers.get(this).options;
+ const absolutePath = path.resolve(options.cwd, filePath);
+ const configs = await calculateConfigArray(this, options);
+ return configs.getConfig(absolutePath);
+ }
+ /**
+ * Checks if a given path is ignored by ESLint.
+ * @param {string} filePath The path of the file to check.
+ * @returns {Promise<boolean>} Whether or not the given path is ignored.
+ */
+
+
+ async isPathIgnored(filePath) {
+ const config = await this.calculateConfigForFile(filePath);
+ return config === void 0;
+ }
+
+} //------------------------------------------------------------------------------
+// Public Interface
+//------------------------------------------------------------------------------
+
+
+module.exports = {
+ FlatESLint,
+ findFlatConfigFile
+};
+
+/***/ }),
+/* 1014 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+
+
+const path = __webpack_require__(501);
+
+const locatePath = __webpack_require__(1015);
+
+const pathExists = __webpack_require__(1019);
+
+const stop = Symbol('findUp.stop');
+
+module.exports = async function (name) {
+ let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ let directory = path.resolve(options.cwd || '');
+ const {
+ root
+ } = path.parse(directory);
+ const paths = [].concat(name);
+
+ const runMatcher = async locateOptions => {
+ if (typeof name !== 'function') {
+ return locatePath(paths, locateOptions);
+ }
+
+ const foundPath = await name(locateOptions.cwd);
+
+ if (typeof foundPath === 'string') {
+ return locatePath([foundPath], locateOptions);
+ }
+
+ return foundPath;
+ }; // eslint-disable-next-line no-constant-condition
+
+
+ while (true) {
+ // eslint-disable-next-line no-await-in-loop
+ const foundPath = await runMatcher({ ...options,
+ cwd: directory
+ });
+
+ if (foundPath === stop) {
+ return;
+ }
+
+ if (foundPath) {
+ return path.resolve(directory, foundPath);
+ }
+
+ if (directory === root) {
+ return;
+ }
+
+ directory = path.dirname(directory);
+ }
+};
+
+module.exports.sync = function (name) {
+ let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ let directory = path.resolve(options.cwd || '');
+ const {
+ root
+ } = path.parse(directory);
+ const paths = [].concat(name);
+
+ const runMatcher = locateOptions => {
+ if (typeof name !== 'function') {
+ return locatePath.sync(paths, locateOptions);
+ }
+
+ const foundPath = name(locateOptions.cwd);
+
+ if (typeof foundPath === 'string') {
+ return locatePath.sync([foundPath], locateOptions);
+ }
+
+ return foundPath;
+ }; // eslint-disable-next-line no-constant-condition
+
+
+ while (true) {
+ const foundPath = runMatcher({ ...options,
+ cwd: directory
+ });
+
+ if (foundPath === stop) {
+ return;
+ }
+
+ if (foundPath) {
+ return path.resolve(directory, foundPath);
+ }
+
+ if (directory === root) {
+ return;
+ }
+
+ directory = path.dirname(directory);
+ }
+};
+
+module.exports.exists = pathExists;
+module.exports.sync.exists = pathExists.sync;
+module.exports.stop = stop;
+
+/***/ }),
+/* 1015 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+
+
+const path = __webpack_require__(501);
+
+const fs = __webpack_require__(971);
+
+const {
+ promisify
+} = __webpack_require__(516);
+
+const pLocate = __webpack_require__(1016);
+
+const fsStat = promisify(fs.stat);
+const fsLStat = promisify(fs.lstat);
+const typeMappings = {
+ directory: 'isDirectory',
+ file: 'isFile'
+};
+
+function checkType(_ref) {
+ let {
+ type
+ } = _ref;
+
+ if (type in typeMappings) {
+ return;
+ }
+
+ throw new Error(`Invalid type specified: ${type}`);
+}
+
+const matchType = (type, stat) => type === undefined || stat[typeMappings[type]]();
+
+module.exports = async (paths, options) => {
+ options = {
+ cwd: process.cwd(),
+ type: 'file',
+ allowSymlinks: true,
+ ...options
+ };
+ checkType(options);
+ const statFn = options.allowSymlinks ? fsStat : fsLStat;
+ return pLocate(paths, async path_ => {
+ try {
+ const stat = await statFn(path.resolve(options.cwd, path_));
+ return matchType(options.type, stat);
+ } catch {
+ return false;
+ }
+ }, options);
+};
+
+module.exports.sync = (paths, options) => {
+ options = {
+ cwd: process.cwd(),
+ allowSymlinks: true,
+ type: 'file',
+ ...options
+ };
+ checkType(options);
+ const statFn = options.allowSymlinks ? fs.statSync : fs.lstatSync;
+
+ for (const path_ of paths) {
+ try {
+ const stat = statFn(path.resolve(options.cwd, path_));
+
+ if (matchType(options.type, stat)) {
+ return path_;
+ }
+ } catch {}
+ }
+};
+
+/***/ }),
+/* 1016 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+
+
+const pLimit = __webpack_require__(1017);
+
+class EndError extends Error {
+ constructor(value) {
+ super();
+ this.value = value;
+ }
+
+} // The input can also be a promise, so we await it
+
+
+const testElement = async (element, tester) => tester(await element); // The input can also be a promise, so we `Promise.all()` them both
+
+
+const finder = async element => {
+ const values = await Promise.all(element);
+
+ if (values[1] === true) {
+ throw new EndError(values[0]);
+ }
+
+ return false;
+};
+
+const pLocate = async (iterable, tester, options) => {
+ options = {
+ concurrency: Infinity,
+ preserveOrder: true,
+ ...options
+ };
+ const limit = pLimit(options.concurrency); // Start all the promises concurrently with optional limit
+
+ const items = [...iterable].map(element => [element, limit(testElement, element, tester)]); // Check the promises either serially or concurrently
+
+ const checkLimit = pLimit(options.preserveOrder ? 1 : Infinity);
+
+ try {
+ await Promise.all(items.map(element => checkLimit(finder, element)));
+ } catch (error) {
+ if (error instanceof EndError) {
+ return error.value;
+ }
+
+ throw error;
+ }
+};
+
+module.exports = pLocate;
+
+/***/ }),
+/* 1017 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+
+
+const Queue = __webpack_require__(1018);
+
+const pLimit = concurrency => {
+ if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {
+ throw new TypeError('Expected `concurrency` to be a number from 1 and up');
+ }
+
+ const queue = new Queue();
+ let activeCount = 0;
+
+ const next = () => {
+ activeCount--;
+
+ if (queue.size > 0) {
+ queue.dequeue()();
+ }
+ };
+
+ const run = async function (fn, resolve) {
+ for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
+ args[_key - 2] = arguments[_key];
+ }
+
+ activeCount++;
+
+ const result = (async () => fn(...args))();
+
+ resolve(result);
+
+ try {
+ await result;
+ } catch {}
+
+ next();
+ };
+
+ const enqueue = function (fn, resolve) {
+ for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
+ args[_key2 - 2] = arguments[_key2];
+ }
+
+ queue.enqueue(run.bind(null, fn, resolve, ...args));
+
+ (async () => {
+ // This function needs to wait until the next microtask before comparing
+ // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
+ // when the run function is dequeued and called. The comparison in the if-statement
+ // needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
+ await Promise.resolve();
+
+ if (activeCount < concurrency && queue.size > 0) {
+ queue.dequeue()();
+ }
+ })();
+ };
+
+ const generator = function (fn) {
+ for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
+ args[_key3 - 1] = arguments[_key3];
+ }
+
+ return new Promise(resolve => {
+ enqueue(fn, resolve, ...args);
+ });
+ };
+
+ Object.defineProperties(generator, {
+ activeCount: {
+ get: () => activeCount
+ },
+ pendingCount: {
+ get: () => queue.size
+ },
+ clearQueue: {
+ value: () => {
+ queue.clear();
+ }
+ }
+ });
+ return generator;
+};
+
+module.exports = pLimit;
+
+/***/ }),
+/* 1018 */
+/***/ ((module) => {
+
+class Node {
+ /// value;
+ /// next;
+ constructor(value) {
+ this.value = value; // TODO: Remove this when targeting Node.js 12.
+
+ this.next = undefined;
+ }
+
+}
+
+class Queue {
+ // TODO: Use private class fields when targeting Node.js 12.
+ // #_head;
+ // #_tail;
+ // #_size;
+ constructor() {
+ this.clear();
+ }
+
+ enqueue(value) {
+ const node = new Node(value);
+
+ if (this._head) {
+ this._tail.next = node;
+ this._tail = node;
+ } else {
+ this._head = node;
+ this._tail = node;
+ }
+
+ this._size++;
+ }
+
+ dequeue() {
+ const current = this._head;
+
+ if (!current) {
+ return;
+ }
+
+ this._head = this._head.next;
+ this._size--;
+ return current.value;
+ }
+
+ clear() {
+ this._head = undefined;
+ this._tail = undefined;
+ this._size = 0;
+ }
+
+ get size() {
+ return this._size;
+ }
+
+ *[Symbol.iterator]() {
+ let current = this._head;
+
+ while (current) {
+ yield current.value;
+ current = current.next;
+ }
+ }
+
+}
+
+module.exports = Queue;
+
+/***/ }),
+/* 1019 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+
+
+const fs = __webpack_require__(971);
+
+const {
+ promisify
+} = __webpack_require__(516);
+
+const pAccess = promisify(fs.access);
+
+module.exports = async path => {
+ try {
+ await pAccess(path);
+ return true;
+ } catch (_) {
+ return false;
+ }
+};
+
+module.exports.sync = path => {
+ try {
+ fs.accessSync(path);
+ return true;
+ } catch (_) {
+ return false;
+ }
+};
+
+/***/ }),
+/* 1020 */
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+/**
+ * @fileoverview Utility to convert gitignore patterns to minimatch.
+ * @author Nicholas C. Zakas
+ */
+
+/**
+ * Converts a gitignore pattern to a minimatch pattern.
+ * @param {string} pattern The gitignore pattern to convert.
+ * @returns {string} A minimatch pattern equivalent to `pattern`.
+ */
+function gitignoreToMinimatch(pattern) {
+
+ if (typeof pattern !== "string") {
+ throw new TypeError("Argument must be a string.");
+ }
+
+ // Special case: Empty string
+ if (!pattern) {
+ return pattern;
+ }
+
+ // strip off negation to make life easier
+ const negated = pattern.startsWith("!");
+ let patternToTest = negated ? pattern.slice(1) : pattern;
+ let result = patternToTest;
+ let leadingSlash = false;
+
+ // strip off leading slash
+ if (patternToTest[0] === "/") {
+ leadingSlash = true;
+ result = patternToTest.slice(1);
+ }
+
+ // For the most part, the first character determines what to do
+ switch (result[0]) {
+
+ case "*":
+ if (patternToTest[1] !== "*") {
+ result = "**/" + result;
+ }
+ break;
+
+ default:
+ if (!leadingSlash && !result.includes("/") || result.endsWith("/")) {
+ result = "**/" + result;
+ }
+
+ // no further changes if the pattern ends with a wildcard
+ if (result.endsWith("*") || result.endsWith("?")) {
+ break;
+ }
+
+ // differentiate between filenames and directory names
+ if (!/\.[a-z\d_-]+$/.test(result)) {
+ if (!result.endsWith("/")) {
+ result += "/";
+ }
+
+ result += "**";
+ }
+ }
+
+ return negated ? "!" + result : result;
+
+}
+
+exports.gitignoreToMinimatch = gitignoreToMinimatch;
+
+
+/***/ }),
+/* 1021 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+/**
+ * @fileoverview Helper functions for ESLint class
+ * @author Nicholas C. Zakas
+ */
+ //-----------------------------------------------------------------------------
+// Requirements
+//-----------------------------------------------------------------------------
+
+const path = __webpack_require__(501);
+
+const fs = __webpack_require__(971);
+
+const fsp = fs.promises;
+
+const isGlob = __webpack_require__(986);
+
+const globby = __webpack_require__(1022);
+
+const hash = __webpack_require__(991);
+
+const minimatch = __webpack_require__(953); //-----------------------------------------------------------------------------
+// Errors
+//-----------------------------------------------------------------------------
+
+/**
+ * The error type when no files match a glob.
+ */
+
+
+class NoFilesFoundError extends Error {
+ /**
+ * @param {string} pattern The glob pattern which was not found.
+ * @param {boolean} globEnabled If `false` then the pattern was a glob pattern, but glob was disabled.
+ */
+ constructor(pattern, globEnabled) {
+ super(`No files matching '${pattern}' were found${!globEnabled ? " (glob was disabled)" : ""}.`);
+ this.messageTemplate = "file-not-found";
+ this.messageData = {
+ pattern,
+ globDisabled: !globEnabled
+ };
+ }
+
+}
+/**
+ * The error type when there are files matched by a glob, but all of them have been ignored.
+ */
+
+
+class AllFilesIgnoredError extends Error {
+ /**
+ * @param {string} pattern The glob pattern which was not found.
+ */
+ constructor(pattern) {
+ super(`All files matched by '${pattern}' are ignored.`);
+ this.messageTemplate = "all-files-ignored";
+ this.messageData = {
+ pattern
+ };
+ }
+
+} //-----------------------------------------------------------------------------
+// General Helpers
+//-----------------------------------------------------------------------------
+
+/**
+ * Check if a given value is a non-empty string or not.
+ * @param {any} x The value to check.
+ * @returns {boolean} `true` if `x` is a non-empty string.
+ */
+
+
+function isNonEmptyString(x) {
+ return typeof x === "string" && x.trim() !== "";
+}
+/**
+ * Check if a given value is an array of non-empty stringss or not.
+ * @param {any} x The value to check.
+ * @returns {boolean} `true` if `x` is an array of non-empty stringss.
+ */
+
+
+function isArrayOfNonEmptyString(x) {
+ return Array.isArray(x) && x.every(isNonEmptyString);
+} //-----------------------------------------------------------------------------
+// File-related Helpers
+//-----------------------------------------------------------------------------
+
+/**
+ * Normalizes slashes in a file pattern to posix-style.
+ * @param {string} pattern The pattern to replace slashes in.
+ * @returns {string} The pattern with slashes normalized.
+ */
+
+
+function normalizeToPosix(pattern) {
+ return pattern.replace(/\\/gu, "/");
+}
+/**
+ * Check if a string is a glob pattern or not.
+ * @param {string} pattern A glob pattern.
+ * @returns {boolean} `true` if the string is a glob pattern.
+ */
+
+
+function isGlobPattern(pattern) {
+ return isGlob(path.sep === "\\" ? normalizeToPosix(pattern) : pattern);
+}
+/**
+ * Finds all files matching the options specified.
+ * @param {Object} args The arguments objects.
+ * @param {Array<string>} args.patterns An array of glob patterns.
+ * @param {boolean} args.globInputPaths true to interpret glob patterns,
+ * false to not interpret glob patterns.
+ * @param {string} args.cwd The current working directory to find from.
+ * @param {FlatConfigArray} args.configs The configs for the current run.
+ * @param {boolean} args.errorOnUnmatchedPattern Determines if an unmatched pattern
+ * should throw an error.
+ * @returns {Promise<Array<string>>} The fully resolved file paths.
+ * @throws {AllFilesIgnoredError} If there are no results due to an ignore pattern.
+ * @throws {NoFilesFoundError} If no files matched the given patterns.
+ */
+
+
+async function findFiles(_ref) {
+ let {
+ patterns,
+ globInputPaths,
+ cwd,
+ configs,
+ errorOnUnmatchedPattern
+ } = _ref;
+ const results = [];
+ const globbyPatterns = [];
+ const missingPatterns = []; // check to see if we have explicit files and directories
+
+ const filePaths = patterns.map(filePath => path.resolve(cwd, filePath));
+ const stats = await Promise.all(filePaths.map(filePath => fsp.stat(filePath).catch(() => {})));
+ stats.forEach((stat, index) => {
+ const filePath = filePaths[index];
+ const pattern = normalizeToPosix(patterns[index]);
+
+ if (stat) {
+ // files are added directly to the list
+ if (stat.isFile()) {
+ results.push({
+ filePath,
+ ignored: configs.isIgnored(filePath)
+ });
+ } // directories need extensions attached
+
+
+ if (stat.isDirectory()) {
+ // filePatterns are all relative to cwd
+ const filePatterns = configs.files.filter(filePattern => {
+ // can only do this for strings, not functions
+ if (typeof filePattern !== "string") {
+ return false;
+ } // patterns starting with ** always apply
+
+
+ if (filePattern.startsWith("**")) {
+ return true;
+ } // patterns ending with * are not used for file search
+
+
+ if (filePattern.endsWith("*")) {
+ return false;
+ } // not sure how to handle negated patterns yet
+
+
+ if (filePattern.startsWith("!")) {
+ return false;
+ } // check if the pattern would be inside the config base path or not
+
+
+ const fullFilePattern = path.join(cwd, filePattern);
+ const patternRelativeToConfigBasePath = path.relative(configs.basePath, fullFilePattern);
+
+ if (patternRelativeToConfigBasePath.startsWith("..")) {
+ return false;
+ } // check if the pattern matches
+
+
+ if (minimatch(filePath, path.dirname(fullFilePattern), {
+ partial: true
+ })) {
+ return true;
+ } // check if the pattern is inside the directory or not
+
+
+ const patternRelativeToFilePath = path.relative(filePath, fullFilePattern);
+
+ if (patternRelativeToFilePath.startsWith("..")) {
+ return false;
+ }
+
+ return true;
+ }).map(filePattern => {
+ if (filePattern.startsWith("**")) {
+ return path.join(pattern, filePattern);
+ } // adjust the path to be relative to the cwd
+
+
+ return path.relative(cwd, path.join(configs.basePath, filePattern));
+ }).map(normalizeToPosix);
+
+ if (filePatterns.length) {
+ globbyPatterns.push(...filePatterns);
+ }
+ }
+
+ return;
+ } // save patterns for later use based on whether globs are enabled
+
+
+ if (globInputPaths && isGlobPattern(filePath)) {
+ globbyPatterns.push(pattern);
+ } else {
+ missingPatterns.push(pattern);
+ }
+ }); // note: globbyPatterns can be an empty array
+
+ const globbyResults = await globby(globbyPatterns, {
+ cwd,
+ absolute: true,
+ ignore: configs.ignores.filter(matcher => typeof matcher === "string")
+ }); // if there are no results, tell the user why
+
+ if (!results.length && !globbyResults.length) {
+ // try globby without ignoring anything
+
+ /* eslint-disable no-unreachable-loop -- We want to exit early. */
+ for (const globbyPattern of globbyPatterns) {
+ /* eslint-disable-next-line no-unused-vars -- Want to exit early. */
+ for await (const filePath of globby.stream(globbyPattern, {
+ cwd,
+ absolute: true
+ })) {
+ // files were found but ignored
+ throw new AllFilesIgnoredError(globbyPattern);
+ } // no files were found
+
+
+ if (errorOnUnmatchedPattern) {
+ throw new NoFilesFoundError(globbyPattern, globInputPaths);
+ }
+ }
+ /* eslint-enable no-unreachable-loop -- Go back to normal. */
+
+ } // there were patterns that didn't match anything, tell the user
+
+
+ if (errorOnUnmatchedPattern && missingPatterns.length) {
+ throw new NoFilesFoundError(missingPatterns[0], globInputPaths);
+ }
+
+ return [...results, ...globbyResults.map(filePath => ({
+ filePath: path.resolve(filePath),
+ ignored: false
+ }))];
+}
+/**
+ * Checks whether a file exists at the given location
+ * @param {string} resolvedPath A path from the CWD
+ * @throws {Error} As thrown by `fs.statSync` or `fs.isFile`.
+ * @returns {boolean} `true` if a file exists
+ */
+
+
+function fileExists(resolvedPath) {
+ try {
+ return fs.statSync(resolvedPath).isFile();
+ } catch (error) {
+ if (error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
+ return false;
+ }
+
+ throw error;
+ }
+}
+/**
+ * Checks whether a directory exists at the given location
+ * @param {string} resolvedPath A path from the CWD
+ * @throws {Error} As thrown by `fs.statSync` or `fs.isDirectory`.
+ * @returns {boolean} `true` if a directory exists
+ */
+
+
+function directoryExists(resolvedPath) {
+ try {
+ return fs.statSync(resolvedPath).isDirectory();
+ } catch (error) {
+ if (error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
+ return false;
+ }
+
+ throw error;
+ }
+} //-----------------------------------------------------------------------------
+// Results-related Helpers
+//-----------------------------------------------------------------------------
+
+/**
+ * Checks if the given message is an error message.
+ * @param {LintMessage} message The message to check.
+ * @returns {boolean} Whether or not the message is an error message.
+ * @private
+ */
+
+
+function isErrorMessage(message) {
+ return message.severity === 2;
+}
+/**
+ * Returns result with warning by ignore settings
+ * @param {string} filePath File path of checked code
+ * @param {string} baseDir Absolute path of base directory
+ * @returns {LintResult} Result with single warning
+ * @private
+ */
+
+
+function createIgnoreResult(filePath, baseDir) {
+ let message;
+ const isHidden = filePath.split(path.sep).find(segment => /^\./u.test(segment));
+ const isInNodeModules = baseDir && path.relative(baseDir, filePath).startsWith("node_modules");
+
+ if (isHidden) {
+ message = "File ignored by default. Use a negated ignore pattern (like \"--ignore-pattern '!<relative/path/to/filename>'\") to override.";
+ } else if (isInNodeModules) {
+ message = "File ignored by default. Use \"--ignore-pattern '!node_modules/*'\" to override.";
+ } else {
+ message = "File ignored because of a matching ignore pattern. Use \"--no-ignore\" to override.";
+ }
+
+ return {
+ filePath: path.resolve(filePath),
+ messages: [{
+ fatal: false,
+ severity: 1,
+ message
+ }],
+ suppressedMessages: [],
+ errorCount: 0,
+ warningCount: 1,
+ fatalErrorCount: 0,
+ fixableErrorCount: 0,
+ fixableWarningCount: 0
+ };
+} //-----------------------------------------------------------------------------
+// Options-related Helpers
+//-----------------------------------------------------------------------------
+
+/**
+ * Check if a given value is a valid fix type or not.
+ * @param {any} x The value to check.
+ * @returns {boolean} `true` if `x` is valid fix type.
+ */
+
+
+function isFixType(x) {
+ return x === "directive" || x === "problem" || x === "suggestion" || x === "layout";
+}
+/**
+ * Check if a given value is an array of fix types or not.
+ * @param {any} x The value to check.
+ * @returns {boolean} `true` if `x` is an array of fix types.
+ */
+
+
+function isFixTypeArray(x) {
+ return Array.isArray(x) && x.every(isFixType);
+}
+/**
+ * The error for invalid options.
+ */
+
+
+class ESLintInvalidOptionsError extends Error {
+ constructor(messages) {
+ super(`Invalid Options:\n- ${messages.join("\n- ")}`);
+ this.code = "ESLINT_INVALID_OPTIONS";
+ Error.captureStackTrace(this, ESLintInvalidOptionsError);
+ }
+
+}
+/**
+ * Validates and normalizes options for the wrapped CLIEngine instance.
+ * @param {FlatESLintOptions} options The options to process.
+ * @throws {ESLintInvalidOptionsError} If of any of a variety of type errors.
+ * @returns {FlatESLintOptions} The normalized options.
+ */
+
+
+function processOptions(_ref2) {
+ let {
+ allowInlineConfig = true,
+ // ← we cannot use `overrideConfig.noInlineConfig` instead because `allowInlineConfig` has side-effect that suppress warnings that show inline configs are ignored.
+ baseConfig = null,
+ cache = false,
+ cacheLocation = ".eslintcache",
+ cacheStrategy = "metadata",
+ cwd = process.cwd(),
+ errorOnUnmatchedPattern = true,
+ fix = false,
+ fixTypes = null,
+ // ← should be null by default because if it's an array then it suppresses rules that don't have the `meta.type` property.
+ globInputPaths = true,
+ ignore = true,
+ ignorePath = null,
+ // ← should be null by default because if it's a string then it may throw ENOENT.
+ ignorePatterns = null,
+ overrideConfig = null,
+ overrideConfigFile = null,
+ plugins = {},
+ reportUnusedDisableDirectives = null,
+ // ← should be null by default because if it's a string then it overrides the 'reportUnusedDisableDirectives' setting in config files. And we cannot use `overrideConfig.reportUnusedDisableDirectives` instead because we cannot configure the `error` severity with that.
+ ...unknownOptions
+ } = _ref2;
+ const errors = [];
+ const unknownOptionKeys = Object.keys(unknownOptions);
+
+ if (unknownOptionKeys.length >= 1) {
+ errors.push(`Unknown options: ${unknownOptionKeys.join(", ")}`);
+
+ if (unknownOptionKeys.includes("cacheFile")) {
+ errors.push("'cacheFile' has been removed. Please use the 'cacheLocation' option instead.");
+ }
+
+ if (unknownOptionKeys.includes("configFile")) {
+ errors.push("'configFile' has been removed. Please use the 'overrideConfigFile' option instead.");
+ }
+
+ if (unknownOptionKeys.includes("envs")) {
+ errors.push("'envs' has been removed.");
+ }
+
+ if (unknownOptionKeys.includes("extensions")) {
+ errors.push("'extensions' has been removed.");
+ }
+
+ if (unknownOptionKeys.includes("resolvePluginsRelativeTo")) {
+ errors.push("'resolvePluginsRelativeTo' has been removed.");
+ }
+
+ if (unknownOptionKeys.includes("globals")) {
+ errors.push("'globals' has been removed. Please use the 'overrideConfig.languageOptions.globals' option instead.");
+ }
+
+ if (unknownOptionKeys.includes("ignorePattern")) {
+ errors.push("'ignorePattern' has been removed. Please use the 'overrideConfig.ignorePatterns' option instead.");
+ }
+
+ if (unknownOptionKeys.includes("parser")) {
+ errors.push("'parser' has been removed. Please use the 'overrideConfig.languageOptions.parser' option instead.");
+ }
+
+ if (unknownOptionKeys.includes("parserOptions")) {
+ errors.push("'parserOptions' has been removed. Please use the 'overrideConfig.languageOptions.parserOptions' option instead.");
+ }
+
+ if (unknownOptionKeys.includes("rules")) {
+ errors.push("'rules' has been removed. Please use the 'overrideConfig.rules' option instead.");
+ }
+
+ if (unknownOptionKeys.includes("rulePaths")) {
+ errors.push("'rulePaths' has been removed. Please define your rules using plugins.");
+ }
+ }
+
+ if (typeof allowInlineConfig !== "boolean") {
+ errors.push("'allowInlineConfig' must be a boolean.");
+ }
+
+ if (typeof baseConfig !== "object") {
+ errors.push("'baseConfig' must be an object or null.");
+ }
+
+ if (typeof cache !== "boolean") {
+ errors.push("'cache' must be a boolean.");
+ }
+
+ if (!isNonEmptyString(cacheLocation)) {
+ errors.push("'cacheLocation' must be a non-empty string.");
+ }
+
+ if (cacheStrategy !== "metadata" && cacheStrategy !== "content") {
+ errors.push("'cacheStrategy' must be any of \"metadata\", \"content\".");
+ }
+
+ if (!isNonEmptyString(cwd) || !path.isAbsolute(cwd)) {
+ errors.push("'cwd' must be an absolute path.");
+ }
+
+ if (typeof errorOnUnmatchedPattern !== "boolean") {
+ errors.push("'errorOnUnmatchedPattern' must be a boolean.");
+ }
+
+ if (typeof fix !== "boolean" && typeof fix !== "function") {
+ errors.push("'fix' must be a boolean or a function.");
+ }
+
+ if (fixTypes !== null && !isFixTypeArray(fixTypes)) {
+ errors.push("'fixTypes' must be an array of any of \"directive\", \"problem\", \"suggestion\", and \"layout\".");
+ }
+
+ if (typeof globInputPaths !== "boolean") {
+ errors.push("'globInputPaths' must be a boolean.");
+ }
+
+ if (typeof ignore !== "boolean") {
+ errors.push("'ignore' must be a boolean.");
+ }
+
+ if (!isNonEmptyString(ignorePath) && ignorePath !== null) {
+ errors.push("'ignorePath' must be a non-empty string or null.");
+ }
+
+ if (typeof overrideConfig !== "object") {
+ errors.push("'overrideConfig' must be an object or null.");
+ }
+
+ if (!isNonEmptyString(overrideConfigFile) && overrideConfigFile !== null && overrideConfigFile !== true) {
+ errors.push("'overrideConfigFile' must be a non-empty string, null, or true.");
+ }
+
+ if (typeof plugins !== "object") {
+ errors.push("'plugins' must be an object or null.");
+ } else if (plugins !== null && Object.keys(plugins).includes("")) {
+ errors.push("'plugins' must not include an empty string.");
+ }
+
+ if (Array.isArray(plugins)) {
+ errors.push("'plugins' doesn't add plugins to configuration to load. Please use the 'overrideConfig.plugins' option instead.");
+ }
+
+ if (reportUnusedDisableDirectives !== "error" && reportUnusedDisableDirectives !== "warn" && reportUnusedDisableDirectives !== "off" && reportUnusedDisableDirectives !== null) {
+ errors.push("'reportUnusedDisableDirectives' must be any of \"error\", \"warn\", \"off\", and null.");
+ }
+
+ if (errors.length > 0) {
+ throw new ESLintInvalidOptionsError(errors);
+ }
+
+ return {
+ allowInlineConfig,
+ baseConfig,
+ cache,
+ cacheLocation,
+ cacheStrategy,
+ // when overrideConfigFile is true that means don't do config file lookup
+ configFile: overrideConfigFile === true ? false : overrideConfigFile,
+ overrideConfig,
+ cwd,
+ errorOnUnmatchedPattern,
+ fix,
+ fixTypes,
+ globInputPaths,
+ ignore,
+ ignorePath,
+ ignorePatterns,
+ reportUnusedDisableDirectives
+ };
+} //-----------------------------------------------------------------------------
+// Cache-related helpers
+//-----------------------------------------------------------------------------
+
+/**
+ * return the cacheFile to be used by eslint, based on whether the provided parameter is
+ * a directory or looks like a directory (ends in `path.sep`), in which case the file
+ * name will be the `cacheFile/.cache_hashOfCWD`
+ *
+ * if cacheFile points to a file or looks like a file then in will just use that file
+ * @param {string} cacheFile The name of file to be used to store the cache
+ * @param {string} cwd Current working directory
+ * @returns {string} the resolved path to the cache file
+ */
+
+
+function getCacheFile(cacheFile, cwd) {
+ /*
+ * make sure the path separators are normalized for the environment/os
+ * keeping the trailing path separator if present
+ */
+ const normalizedCacheFile = path.normalize(cacheFile);
+ const resolvedCacheFile = path.resolve(cwd, normalizedCacheFile);
+ const looksLikeADirectory = normalizedCacheFile.slice(-1) === path.sep;
+ /**
+ * return the name for the cache file in case the provided parameter is a directory
+ * @returns {string} the resolved path to the cacheFile
+ */
+
+ function getCacheFileForDirectory() {
+ return path.join(resolvedCacheFile, `.cache_${hash(cwd)}`);
+ }
+
+ let fileStats;
+
+ try {
+ fileStats = fs.lstatSync(resolvedCacheFile);
+ } catch {
+ fileStats = null;
+ }
+ /*
+ * in case the file exists we need to verify if the provided path
+ * is a directory or a file. If it is a directory we want to create a file
+ * inside that directory
+ */
+
+
+ if (fileStats) {
+ /*
+ * is a directory or is a file, but the original file the user provided
+ * looks like a directory but `path.resolve` removed the `last path.sep`
+ * so we need to still treat this like a directory
+ */
+ if (fileStats.isDirectory() || looksLikeADirectory) {
+ return getCacheFileForDirectory();
+ } // is file so just use that file
+
+
+ return resolvedCacheFile;
+ }
+ /*
+ * here we known the file or directory doesn't exist,
+ * so we will try to infer if its a directory if it looks like a directory
+ * for the current operating system.
+ */
+ // if the last character passed is a path separator we assume is a directory
+
+
+ if (looksLikeADirectory) {
+ return getCacheFileForDirectory();
+ }
+
+ return resolvedCacheFile;
+} //-----------------------------------------------------------------------------
+// Exports
+//-----------------------------------------------------------------------------
+
+
+module.exports = {
+ isGlobPattern,
+ directoryExists,
+ fileExists,
+ findFiles,
+ isNonEmptyString,
+ isArrayOfNonEmptyString,
+ createIgnoreResult,
+ isErrorMessage,
+ processOptions,
+ getCacheFile
+};
+
+/***/ }),
+/* 1022 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+
+
+const fs = __webpack_require__(971);
+
+const arrayUnion = __webpack_require__(1023);
+
+const merge2 = __webpack_require__(1024);
+
+const fastGlob = __webpack_require__(1026);
+
+const dirGlob = __webpack_require__(1097);
+
+const gitignore = __webpack_require__(1099);
+
+const {
+ FilterStream,
+ UniqueStream
+} = __webpack_require__(1101);
+
+const DEFAULT_FILTER = () => false;
+
+const isNegative = pattern => pattern[0] === '!';
+
+const assertPatternsInput = patterns => {
+ if (!patterns.every(pattern => typeof pattern === 'string')) {
+ throw new TypeError('Patterns must be a string or an array of strings');
+ }
+};
+
+const checkCwdOption = function () {
+ let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+
+ if (!options.cwd) {
+ return;
+ }
+
+ let stat;
+
+ try {
+ stat = fs.statSync(options.cwd);
+ } catch {
+ return;
+ }
+
+ if (!stat.isDirectory()) {
+ throw new Error('The `cwd` option must be a path to a directory');
+ }
+};
+
+const getPathString = p => p.stats instanceof fs.Stats ? p.path : p;
+
+const generateGlobTasks = (patterns, taskOptions) => {
+ patterns = arrayUnion([].concat(patterns));
+ assertPatternsInput(patterns);
+ checkCwdOption(taskOptions);
+ const globTasks = [];
+ taskOptions = {
+ ignore: [],
+ expandDirectories: true,
+ ...taskOptions
+ };
+
+ for (const [index, pattern] of patterns.entries()) {
+ if (isNegative(pattern)) {
+ continue;
+ }
+
+ const ignore = patterns.slice(index).filter(pattern => isNegative(pattern)).map(pattern => pattern.slice(1));
+ const options = { ...taskOptions,
+ ignore: taskOptions.ignore.concat(ignore)
+ };
+ globTasks.push({
+ pattern,
+ options
+ });
+ }
+
+ return globTasks;
+};
+
+const globDirs = (task, fn) => {
+ let options = {};
+
+ if (task.options.cwd) {
+ options.cwd = task.options.cwd;
+ }
+
+ if (Array.isArray(task.options.expandDirectories)) {
+ options = { ...options,
+ files: task.options.expandDirectories
+ };
+ } else if (typeof task.options.expandDirectories === 'object') {
+ options = { ...options,
+ ...task.options.expandDirectories
+ };
+ }
+
+ return fn(task.pattern, options);
+};
+
+const getPattern = (task, fn) => task.options.expandDirectories ? globDirs(task, fn) : [task.pattern];
+
+const getFilterSync = options => {
+ return options && options.gitignore ? gitignore.sync({
+ cwd: options.cwd,
+ ignore: options.ignore
+ }) : DEFAULT_FILTER;
+};
+
+const globToTask = task => glob => {
+ const {
+ options
+ } = task;
+
+ if (options.ignore && Array.isArray(options.ignore) && options.expandDirectories) {
+ options.ignore = dirGlob.sync(options.ignore);
+ }
+
+ return {
+ pattern: glob,
+ options
+ };
+};
+
+module.exports = async (patterns, options) => {
+ const globTasks = generateGlobTasks(patterns, options);
+
+ const getFilter = async () => {
+ return options && options.gitignore ? gitignore({
+ cwd: options.cwd,
+ ignore: options.ignore
+ }) : DEFAULT_FILTER;
+ };
+
+ const getTasks = async () => {
+ const tasks = await Promise.all(globTasks.map(async task => {
+ const globs = await getPattern(task, dirGlob);
+ return Promise.all(globs.map(globToTask(task)));
+ }));
+ return arrayUnion(...tasks);
+ };
+
+ const [filter, tasks] = await Promise.all([getFilter(), getTasks()]);
+ const paths = await Promise.all(tasks.map(task => fastGlob(task.pattern, task.options)));
+ return arrayUnion(...paths).filter(path_ => !filter(getPathString(path_)));
+};
+
+module.exports.sync = (patterns, options) => {
+ const globTasks = generateGlobTasks(patterns, options);
+ const tasks = [];
+
+ for (const task of globTasks) {
+ const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));
+ tasks.push(...newTask);
+ }
+
+ const filter = getFilterSync(options);
+ let matches = [];
+
+ for (const task of tasks) {
+ matches = arrayUnion(matches, fastGlob.sync(task.pattern, task.options));
+ }
+
+ return matches.filter(path_ => !filter(path_));
+};
+
+module.exports.stream = (patterns, options) => {
+ const globTasks = generateGlobTasks(patterns, options);
+ const tasks = [];
+
+ for (const task of globTasks) {
+ const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));
+ tasks.push(...newTask);
+ }
+
+ const filter = getFilterSync(options);
+ const filterStream = new FilterStream(p => !filter(p));
+ const uniqueStream = new UniqueStream();
+ return merge2(tasks.map(task => fastGlob.stream(task.pattern, task.options))).pipe(filterStream).pipe(uniqueStream);
+};
+
+module.exports.generateGlobTasks = generateGlobTasks;
+
+module.exports.hasMagic = (patterns, options) => [].concat(patterns).some(pattern => fastGlob.isDynamicPattern(pattern, options));
+
+module.exports.gitignore = gitignore;
+
+/***/ }),
+/* 1023 */
+/***/ ((module) => {
+
+"use strict";
+
+
+module.exports = function () {
+ return [...new Set([].concat(...arguments))];
+};
+
+/***/ }),
+/* 1024 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+
+/*
+ * merge2
+ * https://github.com/teambition/merge2
+ *
+ * Copyright (c) 2014-2020 Teambition
+ * Licensed under the MIT license.
+ */
+
+const Stream = __webpack_require__(1025);
+
+const PassThrough = Stream.PassThrough;
+const slice = Array.prototype.slice;
+module.exports = merge2;
+
+function merge2() {
+ const streamsQueue = [];
+ const args = slice.call(arguments);
+ let merging = false;
+ let options = args[args.length - 1];
+
+ if (options && !Array.isArray(options) && options.pipe == null) {
+ args.pop();
+ } else {
+ options = {};
+ }
+
+ const doEnd = options.end !== false;
+ const doPipeError = options.pipeError === true;
+
+ if (options.objectMode == null) {
+ options.objectMode = true;
+ }
+
+ if (options.highWaterMark == null) {
+ options.highWaterMark = 64 * 1024;
+ }
+
+ const mergedStream = PassThrough(options);
+
+ function addStream() {
+ for (let i = 0, len = arguments.length; i < len; i++) {
+ streamsQueue.push(pauseStreams(arguments[i], options));
+ }
+
+ mergeStream();
+ return this;
+ }
+
+ function mergeStream() {
+ if (merging) {
+ return;
+ }
+
+ merging = true;
+ let streams = streamsQueue.shift();
+
+ if (!streams) {
+ process.nextTick(endStream);
+ return;
+ }
+
+ if (!Array.isArray(streams)) {
+ streams = [streams];
+ }
+
+ let pipesCount = streams.length + 1;
+
+ function next() {
+ if (--pipesCount > 0) {
+ return;
+ }
+
+ merging = false;
+ mergeStream();
+ }
+
+ function pipe(stream) {
+ function onend() {
+ stream.removeListener('merge2UnpipeEnd', onend);
+ stream.removeListener('end', onend);
+
+ if (doPipeError) {
+ stream.removeListener('error', onerror);
+ }
+
+ next();
+ }
+
+ function onerror(err) {
+ mergedStream.emit('error', err);
+ } // skip ended stream
+
+
+ if (stream._readableState.endEmitted) {
+ return next();
+ }
+
+ stream.on('merge2UnpipeEnd', onend);
+ stream.on('end', onend);
+
+ if (doPipeError) {
+ stream.on('error', onerror);
+ }
+
+ stream.pipe(mergedStream, {
+ end: false
+ }); // compatible for old stream
+
+ stream.resume();
+ }
+
+ for (let i = 0; i < streams.length; i++) {
+ pipe(streams[i]);
+ }
+
+ next();
+ }
+
+ function endStream() {
+ merging = false; // emit 'queueDrain' when all streams merged.
+
+ mergedStream.emit('queueDrain');
+
+ if (doEnd) {
+ mergedStream.end();
+ }
+ }
+
+ mergedStream.setMaxListeners(0);
+ mergedStream.add = addStream;
+ mergedStream.on('unpipe', function (stream) {
+ stream.emit('merge2UnpipeEnd');
+ });
+
+ if (args.length) {
+ addStream.apply(null, args);
+ }
+
+ return mergedStream;
+} // check and pause streams for pipe.
+
+
+function pauseStreams(streams, options) {
+ if (!Array.isArray(streams)) {
+ // Backwards-compat with old-style streams
+ if (!streams._readableState && streams.pipe) {
+ streams = streams.pipe(PassThrough(options));
+ }
+
+ if (!streams._readableState || !streams.pause || !streams.pipe) {
+ throw new Error('Only readable stream can be merged.');
+ }
+
+ streams.pause();
+ } else {
+ for (let i = 0, len = streams.length; i < len; i++) {
+ streams[i] = pauseStreams(streams[i], options);
+ }
+ }
+
+ return streams;
+}
+
+/***/ }),
+/* 1025 */
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("stream");
+
+/***/ }),
+/* 1026 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+
+
+const taskManager = __webpack_require__(1027);
+
+const patternManager = __webpack_require__(1054);
+
+const async_1 = __webpack_require__(1055);
+
+const stream_1 = __webpack_require__(1093);
+
+const sync_1 = __webpack_require__(1094);
+
+const settings_1 = __webpack_require__(1096);
+
+const utils = __webpack_require__(1028);
+
+async function FastGlob(source, options) {
+ assertPatternsInput(source);
+ const works = getWorks(source, async_1.default, options);
+ const result = await Promise.all(works);
+ return utils.array.flatten(result);
+} // https://github.com/typescript-eslint/typescript-eslint/issues/60
+// eslint-disable-next-line no-redeclare
+
+
+(function (FastGlob) {
+ function sync(source, options) {
+ assertPatternsInput(source);
+ const works = getWorks(source, sync_1.default, options);
+ return utils.array.flatten(works);
+ }
+
+ FastGlob.sync = sync;
+
+ function stream(source, options) {
+ assertPatternsInput(source);
+ const works = getWorks(source, stream_1.default, options);
+ /**\r
+ * The stream returned by the provider cannot work with an asynchronous iterator.\r
+ * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.\r
+ * This affects performance (+25%). I don't see best solution right now.\r
+ */
+
+ return utils.stream.merge(works);
+ }
+
+ FastGlob.stream = stream;
+
+ function generateTasks(source, options) {
+ assertPatternsInput(source);
+ const patterns = patternManager.transform([].concat(source));
+ const settings = new settings_1.default(options);
+ return taskManager.generate(patterns, settings);
+ }
+
+ FastGlob.generateTasks = generateTasks;
+
+ function isDynamicPattern(source, options) {
+ assertPatternsInput(source);
+ const settings = new settings_1.default(options);
+ return utils.pattern.isDynamicPattern(source, settings);
+ }
+
+ FastGlob.isDynamicPattern = isDynamicPattern;
+
+ function escapePath(source) {
+ assertPatternsInput(source);
+ return utils.path.escape(source);
+ }
+
+ FastGlob.escapePath = escapePath;
+})(FastGlob || (FastGlob = {}));
+
+function getWorks(source, _Provider, options) {
+ const patterns = patternManager.transform([].concat(source));
+ const settings = new settings_1.default(options);
+ const tasks = taskManager.generate(patterns, settings);
+ const provider = new _Provider(settings);
+ return tasks.map(provider.read, provider);
+}
+
+function assertPatternsInput(input) {
+ const source = [].concat(input);
+ const isValidSource = source.every(item => utils.string.isString(item) && !utils.string.isEmpty(item));
+
+ if (!isValidSource) {
+ throw new TypeError('Patterns must be a string (non empty) or an array of strings');
+ }
+}
+
+module.exports = FastGlob;
+
+/***/ }),
+/* 1027 */
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0;
+
+const utils = __webpack_require__(1028);
+
+function generate(patterns, settings) {
+ const positivePatterns = getPositivePatterns(patterns);
+ const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore);
+ const staticPatterns = positivePatterns.filter(pattern => utils.pattern.isStaticPattern(pattern, settings));
+ const dynamicPatterns = positivePatterns.filter(pattern => utils.pattern.isDynamicPattern(pattern, settings));
+ const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns,
+ /* dynamic */
+ false);
+ const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns,
+ /* dynamic */
+ true);
+ return staticTasks.concat(dynamicTasks);
+}
+
+exports.generate = generate;
+/**\r
+ * Returns tasks grouped by basic pattern directories.\r
+ *\r
+ * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately.\r
+ * This is necessary because directory traversal starts at the base directory and goes deeper.\r
+ */
+
+function convertPatternsToTasks(positive, negative, dynamic) {
+ const tasks = [];
+ const patternsOutsideCurrentDirectory = utils.pattern.getPatternsOutsideCurrentDirectory(positive);
+ const patternsInsideCurrentDirectory = utils.pattern.getPatternsInsideCurrentDirectory(positive);
+ const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory);
+ const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory);
+ tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic));
+ /*\r
+ * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory\r
+ * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest.\r
+ */
+
+ if ('.' in insideCurrentDirectoryGroup) {
+ tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic));
+ } else {
+ tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic));
+ }
+
+ return tasks;
+}
+
+exports.convertPatternsToTasks = convertPatternsToTasks;
+
+function getPositivePatterns(patterns) {
+ return utils.pattern.getPositivePatterns(patterns);
+}
+
+exports.getPositivePatterns = getPositivePatterns;
+
+function getNegativePatternsAsPositive(patterns, ignore) {
+ const negative = utils.pattern.getNegativePatterns(patterns).concat(ignore);
+ const positive = negative.map(utils.pattern.convertToPositivePattern);
+ return positive;
+}
+
+exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
+
+function groupPatternsByBaseDirectory(patterns) {
+ const group = {};
+ return patterns.reduce((collection, pattern) => {
+ const base = utils.pattern.getBaseDirectory(pattern);
+
+ if (base in collection) {
+ collection[base].push(pattern);
+ } else {
+ collection[base] = [pattern];
+ }
+
+ return collection;
+ }, group);
+}
+
+exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
+
+function convertPatternGroupsToTasks(positive, negative, dynamic) {
+ return Object.keys(positive).map(base => {
+ return convertPatternGroupToTask(base, positive[base], negative, dynamic);
+ });
+}
+
+exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
+
+function convertPatternGroupToTask(base, positive, negative, dynamic) {
+ return {
+ dynamic,
+ positive,
+ negative,
+ base,
+ patterns: [].concat(positive, negative.map(utils.pattern.convertToNegativePattern))
+ };
+}
+
+exports.convertPatternGroupToTask = convertPatternGroupToTask;
+
+/***/ }),
+/* 1028 */
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0;
+
+const array = __webpack_require__(1029);
+
+exports.array = array;
+
+const errno = __webpack_require__(1030);
+
+exports.errno = errno;
+
+const fs = __webpack_require__(1031);
+
+exports.fs = fs;
+
+const path = __webpack_require__(1032);
+
+exports.path = path;
+
+const pattern = __webpack_require__(1033);
+
+exports.pattern = pattern;
+
+const stream = __webpack_require__(1052);
+
+exports.stream = stream;
+
+const string = __webpack_require__(1053);
+
+exports.string = string;
+
+/***/ }),
+/* 1029 */
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";