Commit d27c335f authored by Rosanny Sihombing's avatar Rosanny Sihombing
Browse files

update required modules

parent e7c08cdb
/**
* @fileoverview Config file operations. This file must be usable in the browser,
* so no Node-specific code can be here.
* @author Nicholas C. Zakas
*/
"use strict";
//------------------------------------------------------------------------------
// 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
//------------------------------------------------------------------------------
module.exports = {
/**
* 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.
*/
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}
*/
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.
*/
isErrorSeverity(ruleConfig) {
return module.exports.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.
*/
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.
*/
isEverySeverityValid(config) {
return Object.keys(config).every(ruleId => this.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
*/
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')`);
}
}
};
/**
* @fileoverview Validates configs.
* @author Brandon Mills
*/
"use strict";
/* eslint class-methods-use-this: "off" */
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const
util = require("util"),
configSchema = require("../../conf/config-schema"),
BuiltInEnvironments = require("../../conf/environments"),
ConfigOps = require("./config-ops"),
{ emitDeprecationWarning } = require("./deprecation-warnings");
const ajv = require("./ajv")();
const ruleValidators = new WeakMap();
const noop = Function.prototype;
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
let validateSchema;
const severityMap = {
error: 2,
warn: 1,
off: 0
};
const validated = new WeakSet();
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
module.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.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) || BuiltInEnvironments.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 {
ConfigOps.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 Provide the function that emits deprecation warnings.
* @author Toru Nagashima <http://github.com/mysticatea>
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const path = require("path");
//------------------------------------------------------------------------------
// 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.relative(process.cwd(), source);
const message = deprecationWarningMessages[errorCode];
process.emitWarning(
`${message} (found in "${rel}")`,
"DeprecationWarning",
errorCode
);
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = {
emitDeprecationWarning
};
/**
* @fileoverview Common helpers for naming of plugins, formatters and configs
*/
"use strict";
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] : "";
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = {
normalizePackageName,
getShorthandName,
getNamespaceFromTerm
};
/**
* Utility for resolving a module relative to another module
* @author Teddy Katz
*/
"use strict";
const Module = require("module");
/*
* `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.
*/
// eslint-disable-next-line node/no-unsupported-features/node-builtins, node/no-deprecated-api
const createRequire = Module.createRequire || Module.createRequireFromPath;
module.exports = {
/**
* 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`
*/
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;
}
}
};
/**
* @fileoverview Define common types for input completion.
* @author Toru Nagashima <https://github.com/mysticatea>
*/
"use strict";
/** @type {any} */
module.exports = {};
/** @typedef {boolean | "off" | "readable" | "readonly" | "writable" | "writeable"} GlobalConf */
/** @typedef {0 | 1 | 2 | "off" | "warn" | "error"} SeverityConf */
/** @typedef {SeverityConf | [SeverityConf, ...any[]]} RuleConf */
/**
* @typedef {Object} EcmaFeatures
* @property {boolean} [globalReturn] Enabling `return` statements at the top-level.
* @property {boolean} [jsx] Enabling JSX syntax.
* @property {boolean} [impliedStrict] Enabling strict mode always.
*/
/**
* @typedef {Object} ParserOptions
* @property {EcmaFeatures} [ecmaFeatures] The optional features.
* @property {3|5|6|7|8|9|10|11|12|2015|2016|2017|2018|2019|2020|2021} [ecmaVersion] The ECMAScript version (or revision number).
* @property {"script"|"module"} [sourceType] The source code type.
*/
/**
* @typedef {Object} ConfigData
* @property {Record<string, boolean>} [env] The environment settings.
* @property {string | string[]} [extends] The path to other config files or the package name of shareable configs.
* @property {Record<string, GlobalConf>} [globals] The global variable settings.
* @property {string | string[]} [ignorePatterns] The glob patterns that ignore to lint.
* @property {boolean} [noInlineConfig] The flag that disables directive comments.
* @property {OverrideConfigData[]} [overrides] The override settings per kind of files.
* @property {string} [parser] The path to a parser or the package name of a parser.
* @property {ParserOptions} [parserOptions] The parser options.
* @property {string[]} [plugins] The plugin specifiers.
* @property {string} [processor] The processor specifier.
* @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments.
* @property {boolean} [root] The root flag.
* @property {Record<string, RuleConf>} [rules] The rule settings.
* @property {Object} [settings] The shared settings.
*/
/**
* @typedef {Object} OverrideConfigData
* @property {Record<string, boolean>} [env] The environment settings.
* @property {string | string[]} [excludedFiles] The glob pattarns for excluded files.
* @property {string | string[]} [extends] The path to other config files or the package name of shareable configs.
* @property {string | string[]} files The glob patterns for target files.
* @property {Record<string, GlobalConf>} [globals] The global variable settings.
* @property {boolean} [noInlineConfig] The flag that disables directive comments.
* @property {OverrideConfigData[]} [overrides] The override settings per kind of files.
* @property {string} [parser] The path to a parser or the package name of a parser.
* @property {ParserOptions} [parserOptions] The parser options.
* @property {string[]} [plugins] The plugin specifiers.
* @property {string} [processor] The processor specifier.
* @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments.
* @property {Record<string, RuleConf>} [rules] The rule settings.
* @property {Object} [settings] The shared settings.
*/
/**
* @typedef {Object} ParseResult
* @property {Object} ast The AST.
* @property {ScopeManager} [scopeManager] The scope manager of the AST.
* @property {Record<string, any>} [services] The services that the parser provides.
* @property {Record<string, string[]>} [visitorKeys] The visitor keys of the AST.
*/
/**
* @typedef {Object} Parser
* @property {(text:string, options:ParserOptions) => Object} parse The definition of global variables.
* @property {(text:string, options:ParserOptions) => ParseResult} [parseForESLint] The parser options that will be enabled under this environment.
*/
/**
* @typedef {Object} Environment
* @property {Record<string, GlobalConf>} [globals] The definition of global variables.
* @property {ParserOptions} [parserOptions] The parser options that will be enabled under this environment.
*/
/**
* @typedef {Object} LintMessage
* @property {number} column The 1-based column number.
* @property {number} [endColumn] The 1-based column number of the end location.
* @property {number} [endLine] The 1-based line number of the end location.
* @property {boolean} fatal If `true` then this is a fatal error.
* @property {{range:[number,number], text:string}} [fix] Information for autofix.
* @property {number} line The 1-based line number.
* @property {string} message The error message.
* @property {string|null} ruleId The ID of the rule which makes this message.
* @property {0|1|2} severity The severity of this message.
* @property {Array<{desc?: string, messageId?: string, fix: {range: [number, number], text: string}}>} [suggestions] Information for suggestions.
*/
/**
* @typedef {Object} SuggestionResult
* @property {string} desc A short description.
* @property {string} [messageId] Id referencing a message for the description.
* @property {{ text: string, range: number[] }} fix fix result info
*/
/**
* @typedef {Object} Processor
* @property {(text:string, filename:string) => Array<string | { text:string, filename:string }>} [preprocess] The function to extract code blocks.
* @property {(messagesList:LintMessage[][], filename:string) => LintMessage[]} [postprocess] The function to merge messages.
* @property {boolean} [supportsAutofix] If `true` then it means the processor supports autofix.
*/
/**
* @typedef {Object} RuleMetaDocs
* @property {string} category The category of the rule.
* @property {string} description The description of the rule.
* @property {boolean} recommended If `true` then the rule is included in `eslint:recommended` preset.
* @property {string} url The URL of the rule documentation.
*/
/**
* @typedef {Object} RuleMeta
* @property {boolean} [deprecated] If `true` then the rule has been deprecated.
* @property {RuleMetaDocs} docs The document information of the rule.
* @property {"code"|"whitespace"} [fixable] The autofix type.
* @property {Record<string,string>} [messages] The messages the rule reports.
* @property {string[]} [replacedBy] The IDs of the alternative rules.
* @property {Array|Object} schema The option schema of the rule.
* @property {"problem"|"suggestion"|"layout"} type The rule type.
*/
/**
* @typedef {Object} Rule
* @property {Function} create The factory of the rule.
* @property {RuleMeta} meta The meta data of the rule.
*/
/**
* @typedef {Object} Plugin
* @property {Record<string, ConfigData>} [configs] The definition of plugin configs.
* @property {Record<string, Environment>} [environments] The definition of plugin environments.
* @property {Record<string, Processor>} [processors] The definition of plugin processors.
* @property {Record<string, Function | Rule>} [rules] The definition of plugin rules.
*/
/**
* Information of deprecated rules.
* @typedef {Object} DeprecatedRuleInfo
* @property {string} ruleId The rule ID.
* @property {string[]} replacedBy The rule IDs that replace this deprecated rule.
*/
{
"builtin": {
"AggregateError": false,
"Array": false,
"ArrayBuffer": false,
"Atomics": false,
"BigInt": false,
"BigInt64Array": false,
"BigUint64Array": false,
"Boolean": false,
"constructor": false,
"DataView": false,
"Date": false,
"decodeURI": false,
"decodeURIComponent": false,
"encodeURI": false,
"encodeURIComponent": false,
"Error": false,
"escape": false,
"eval": false,
"EvalError": false,
"FinalizationRegistry": false,
"Float32Array": false,
"Float64Array": false,
"Function": false,
"globalThis": false,
"hasOwnProperty": false,
"Infinity": false,
"Int16Array": false,
"Int32Array": false,
"Int8Array": false,
"isFinite": false,
"isNaN": false,
"isPrototypeOf": false,
"JSON": false,
"Map": false,
"Math": false,
"NaN": false,
"Number": false,
"Object": false,
"parseFloat": false,
"parseInt": false,
"Promise": false,
"propertyIsEnumerable": false,
"Proxy": false,
"RangeError": false,
"ReferenceError": false,
"Reflect": false,
"RegExp": false,
"Set": false,
"SharedArrayBuffer": false,
"String": false,
"Symbol": false,
"SyntaxError": false,
"toLocaleString": false,
"toString": false,
"TypeError": false,
"Uint16Array": false,
"Uint32Array": false,
"Uint8Array": false,
"Uint8ClampedArray": false,
"undefined": false,
"unescape": false,
"URIError": false,
"valueOf": false,
"WeakMap": false,
"WeakRef": false,
"WeakSet": false
},
"es5": {
"Array": false,
"Boolean": false,
"constructor": false,
"Date": false,
"decodeURI": false,
"decodeURIComponent": false,
"encodeURI": false,
"encodeURIComponent": false,
"Error": false,
"escape": false,
"eval": false,
"EvalError": false,
"Function": false,
"hasOwnProperty": false,
"Infinity": false,
"isFinite": false,
"isNaN": false,
"isPrototypeOf": false,
"JSON": false,
"Math": false,
"NaN": false,
"Number": false,
"Object": false,
"parseFloat": false,
"parseInt": false,
"propertyIsEnumerable": false,
"RangeError": false,
"ReferenceError": false,
"RegExp": false,
"String": false,
"SyntaxError": false,
"toLocaleString": false,
"toString": false,
"TypeError": false,
"undefined": false,
"unescape": false,
"URIError": false,
"valueOf": false
},
"es2015": {
"Array": false,
"ArrayBuffer": false,
"Boolean": false,
"constructor": false,
"DataView": false,
"Date": false,
"decodeURI": false,
"decodeURIComponent": false,
"encodeURI": false,
"encodeURIComponent": false,
"Error": false,
"escape": false,
"eval": false,
"EvalError": false,
"Float32Array": false,
"Float64Array": false,
"Function": false,
"hasOwnProperty": false,
"Infinity": false,
"Int16Array": false,
"Int32Array": false,
"Int8Array": false,
"isFinite": false,
"isNaN": false,
"isPrototypeOf": false,
"JSON": false,
"Map": false,
"Math": false,
"NaN": false,
"Number": false,
"Object": false,
"parseFloat": false,
"parseInt": false,
"Promise": false,
"propertyIsEnumerable": false,
"Proxy": false,
"RangeError": false,
"ReferenceError": false,
"Reflect": false,
"RegExp": false,
"Set": false,
"String": false,
"Symbol": false,
"SyntaxError": false,
"toLocaleString": false,
"toString": false,
"TypeError": false,
"Uint16Array": false,
"Uint32Array": false,
"Uint8Array": false,
"Uint8ClampedArray": false,
"undefined": false,
"unescape": false,
"URIError": false,
"valueOf": false,
"WeakMap": false,
"WeakSet": false
},
"es2017": {
"Array": false,
"ArrayBuffer": false,
"Atomics": false,
"Boolean": false,
"constructor": false,
"DataView": false,
"Date": false,
"decodeURI": false,
"decodeURIComponent": false,
"encodeURI": false,
"encodeURIComponent": false,
"Error": false,
"escape": false,
"eval": false,
"EvalError": false,
"Float32Array": false,
"Float64Array": false,
"Function": false,
"hasOwnProperty": false,
"Infinity": false,
"Int16Array": false,
"Int32Array": false,
"Int8Array": false,
"isFinite": false,
"isNaN": false,
"isPrototypeOf": false,
"JSON": false,
"Map": false,
"Math": false,
"NaN": false,
"Number": false,
"Object": false,
"parseFloat": false,
"parseInt": false,
"Promise": false,
"propertyIsEnumerable": false,
"Proxy": false,
"RangeError": false,
"ReferenceError": false,
"Reflect": false,
"RegExp": false,
"Set": false,
"SharedArrayBuffer": false,
"String": false,
"Symbol": false,
"SyntaxError": false,
"toLocaleString": false,
"toString": false,
"TypeError": false,
"Uint16Array": false,
"Uint32Array": false,
"Uint8Array": false,
"Uint8ClampedArray": false,
"undefined": false,
"unescape": false,
"URIError": false,
"valueOf": false,
"WeakMap": false,
"WeakSet": false
},
"es2020": {
"Array": false,
"ArrayBuffer": false,
"Atomics": false,
"BigInt": false,
"BigInt64Array": false,
"BigUint64Array": false,
"Boolean": false,
"constructor": false,
"DataView": false,
"Date": false,
"decodeURI": false,
"decodeURIComponent": false,
"encodeURI": false,
"encodeURIComponent": false,
"Error": false,
"escape": false,
"eval": false,
"EvalError": false,
"Float32Array": false,
"Float64Array": false,
"Function": false,
"globalThis": false,
"hasOwnProperty": false,
"Infinity": false,
"Int16Array": false,
"Int32Array": false,
"Int8Array": false,
"isFinite": false,
"isNaN": false,
"isPrototypeOf": false,
"JSON": false,
"Map": false,
"Math": false,
"NaN": false,
"Number": false,
"Object": false,
"parseFloat": false,
"parseInt": false,
"Promise": false,
"propertyIsEnumerable": false,
"Proxy": false,
"RangeError": false,
"ReferenceError": false,
"Reflect": false,
"RegExp": false,
"Set": false,
"SharedArrayBuffer": false,
"String": false,
"Symbol": false,
"SyntaxError": false,
"toLocaleString": false,
"toString": false,
"TypeError": false,
"Uint16Array": false,
"Uint32Array": false,
"Uint8Array": false,
"Uint8ClampedArray": false,
"undefined": false,
"unescape": false,
"URIError": false,
"valueOf": false,
"WeakMap": false,
"WeakSet": false
},
"es2021": {
"AggregateError": false,
"Array": false,
"ArrayBuffer": false,
"Atomics": false,
"BigInt": false,
"BigInt64Array": false,
"BigUint64Array": false,
"Boolean": false,
"constructor": false,
"DataView": false,
"Date": false,
"decodeURI": false,
"decodeURIComponent": false,
"encodeURI": false,
"encodeURIComponent": false,
"Error": false,
"escape": false,
"eval": false,
"EvalError": false,
"FinalizationRegistry": false,
"Float32Array": false,
"Float64Array": false,
"Function": false,
"globalThis": false,
"hasOwnProperty": false,
"Infinity": false,
"Int16Array": false,
"Int32Array": false,
"Int8Array": false,
"isFinite": false,
"isNaN": false,
"isPrototypeOf": false,
"JSON": false,
"Map": false,
"Math": false,
"NaN": false,
"Number": false,
"Object": false,
"parseFloat": false,
"parseInt": false,
"Promise": false,
"propertyIsEnumerable": false,
"Proxy": false,
"RangeError": false,
"ReferenceError": false,
"Reflect": false,
"RegExp": false,
"Set": false,
"SharedArrayBuffer": false,
"String": false,
"Symbol": false,
"SyntaxError": false,
"toLocaleString": false,
"toString": false,
"TypeError": false,
"Uint16Array": false,
"Uint32Array": false,
"Uint8Array": false,
"Uint8ClampedArray": false,
"undefined": false,
"unescape": false,
"URIError": false,
"valueOf": false,
"WeakMap": false,
"WeakRef": false,
"WeakSet": false
},
"browser": {
"AbortController": false,
"AbortSignal": false,
"addEventListener": false,
"alert": false,
"AnalyserNode": false,
"Animation": false,
"AnimationEffectReadOnly": false,
"AnimationEffectTiming": false,
"AnimationEffectTimingReadOnly": false,
"AnimationEvent": false,
"AnimationPlaybackEvent": false,
"AnimationTimeline": false,
"applicationCache": false,
"ApplicationCache": false,
"ApplicationCacheErrorEvent": false,
"atob": false,
"Attr": false,
"Audio": false,
"AudioBuffer": false,
"AudioBufferSourceNode": false,
"AudioContext": false,
"AudioDestinationNode": false,
"AudioListener": false,
"AudioNode": false,
"AudioParam": false,
"AudioProcessingEvent": false,
"AudioScheduledSourceNode": false,
"AudioWorkletGlobalScope": false,
"AudioWorkletNode": false,
"AudioWorkletProcessor": false,
"BarProp": false,
"BaseAudioContext": false,
"BatteryManager": false,
"BeforeUnloadEvent": false,
"BiquadFilterNode": false,
"Blob": false,
"BlobEvent": false,
"blur": false,
"BroadcastChannel": false,
"btoa": false,
"BudgetService": false,
"ByteLengthQueuingStrategy": false,
"Cache": false,
"caches": false,
"CacheStorage": false,
"cancelAnimationFrame": false,
"cancelIdleCallback": false,
"CanvasCaptureMediaStreamTrack": false,
"CanvasGradient": false,
"CanvasPattern": false,
"CanvasRenderingContext2D": false,
"ChannelMergerNode": false,
"ChannelSplitterNode": false,
"CharacterData": false,
"clearInterval": false,
"clearTimeout": false,
"clientInformation": false,
"ClipboardEvent": false,
"close": false,
"closed": false,
"CloseEvent": false,
"Comment": false,
"CompositionEvent": false,
"confirm": false,
"console": false,
"ConstantSourceNode": false,
"ConvolverNode": false,
"CountQueuingStrategy": false,
"createImageBitmap": false,
"Credential": false,
"CredentialsContainer": false,
"crypto": false,
"Crypto": false,
"CryptoKey": false,
"CSS": false,
"CSSConditionRule": false,
"CSSFontFaceRule": false,
"CSSGroupingRule": false,
"CSSImportRule": false,
"CSSKeyframeRule": false,
"CSSKeyframesRule": false,
"CSSMatrixComponent": false,
"CSSMediaRule": false,
"CSSNamespaceRule": false,
"CSSPageRule": false,
"CSSPerspective": false,
"CSSRotate": false,
"CSSRule": false,
"CSSRuleList": false,
"CSSScale": false,
"CSSSkew": false,
"CSSSkewX": false,
"CSSSkewY": false,
"CSSStyleDeclaration": false,
"CSSStyleRule": false,
"CSSStyleSheet": false,
"CSSSupportsRule": false,
"CSSTransformValue": false,
"CSSTranslate": false,
"CustomElementRegistry": false,
"customElements": false,
"CustomEvent": false,
"DataTransfer": false,
"DataTransferItem": false,
"DataTransferItemList": false,
"defaultstatus": false,
"defaultStatus": false,
"DelayNode": false,
"DeviceMotionEvent": false,
"DeviceOrientationEvent": false,
"devicePixelRatio": false,
"dispatchEvent": false,
"document": false,
"Document": false,
"DocumentFragment": false,
"DocumentType": false,
"DOMError": false,
"DOMException": false,
"DOMImplementation": false,
"DOMMatrix": false,
"DOMMatrixReadOnly": false,
"DOMParser": false,
"DOMPoint": false,
"DOMPointReadOnly": false,
"DOMQuad": false,
"DOMRect": false,
"DOMRectList": false,
"DOMRectReadOnly": false,
"DOMStringList": false,
"DOMStringMap": false,
"DOMTokenList": false,
"DragEvent": false,
"DynamicsCompressorNode": false,
"Element": false,
"ErrorEvent": false,
"event": false,
"Event": false,
"EventSource": false,
"EventTarget": false,
"external": false,
"fetch": false,
"File": false,
"FileList": false,
"FileReader": false,
"find": false,
"focus": false,
"FocusEvent": false,
"FontFace": false,
"FontFaceSetLoadEvent": false,
"FormData": false,
"frameElement": false,
"frames": false,
"GainNode": false,
"Gamepad": false,
"GamepadButton": false,
"GamepadEvent": false,
"getComputedStyle": false,
"getSelection": false,
"HashChangeEvent": false,
"Headers": false,
"history": false,
"History": false,
"HTMLAllCollection": false,
"HTMLAnchorElement": false,
"HTMLAreaElement": false,
"HTMLAudioElement": false,
"HTMLBaseElement": false,
"HTMLBodyElement": false,
"HTMLBRElement": false,
"HTMLButtonElement": false,
"HTMLCanvasElement": false,
"HTMLCollection": false,
"HTMLContentElement": false,
"HTMLDataElement": false,
"HTMLDataListElement": false,
"HTMLDetailsElement": false,
"HTMLDialogElement": false,
"HTMLDirectoryElement": false,
"HTMLDivElement": false,
"HTMLDListElement": false,
"HTMLDocument": false,
"HTMLElement": false,
"HTMLEmbedElement": false,
"HTMLFieldSetElement": false,
"HTMLFontElement": false,
"HTMLFormControlsCollection": false,
"HTMLFormElement": false,
"HTMLFrameElement": false,
"HTMLFrameSetElement": false,
"HTMLHeadElement": false,
"HTMLHeadingElement": false,
"HTMLHRElement": false,
"HTMLHtmlElement": false,
"HTMLIFrameElement": false,
"HTMLImageElement": false,
"HTMLInputElement": false,
"HTMLLabelElement": false,
"HTMLLegendElement": false,
"HTMLLIElement": false,
"HTMLLinkElement": false,
"HTMLMapElement": false,
"HTMLMarqueeElement": false,
"HTMLMediaElement": false,
"HTMLMenuElement": false,
"HTMLMetaElement": false,
"HTMLMeterElement": false,
"HTMLModElement": false,
"HTMLObjectElement": false,
"HTMLOListElement": false,
"HTMLOptGroupElement": false,
"HTMLOptionElement": false,
"HTMLOptionsCollection": false,
"HTMLOutputElement": false,
"HTMLParagraphElement": false,
"HTMLParamElement": false,
"HTMLPictureElement": false,
"HTMLPreElement": false,
"HTMLProgressElement": false,
"HTMLQuoteElement": false,
"HTMLScriptElement": false,
"HTMLSelectElement": false,
"HTMLShadowElement": false,
"HTMLSlotElement": false,
"HTMLSourceElement": false,
"HTMLSpanElement": false,
"HTMLStyleElement": false,
"HTMLTableCaptionElement": false,
"HTMLTableCellElement": false,
"HTMLTableColElement": false,
"HTMLTableElement": false,
"HTMLTableRowElement": false,
"HTMLTableSectionElement": false,
"HTMLTemplateElement": false,
"HTMLTextAreaElement": false,
"HTMLTimeElement": false,
"HTMLTitleElement": false,
"HTMLTrackElement": false,
"HTMLUListElement": false,
"HTMLUnknownElement": false,
"HTMLVideoElement": false,
"IDBCursor": false,
"IDBCursorWithValue": false,
"IDBDatabase": false,
"IDBFactory": false,
"IDBIndex": false,
"IDBKeyRange": false,
"IDBObjectStore": false,
"IDBOpenDBRequest": false,
"IDBRequest": false,
"IDBTransaction": false,
"IDBVersionChangeEvent": false,
"IdleDeadline": false,
"IIRFilterNode": false,
"Image": false,
"ImageBitmap": false,
"ImageBitmapRenderingContext": false,
"ImageCapture": false,
"ImageData": false,
"indexedDB": false,
"innerHeight": false,
"innerWidth": false,
"InputEvent": false,
"IntersectionObserver": false,
"IntersectionObserverEntry": false,
"Intl": false,
"isSecureContext": false,
"KeyboardEvent": false,
"KeyframeEffect": false,
"KeyframeEffectReadOnly": false,
"length": false,
"localStorage": false,
"location": true,
"Location": false,
"locationbar": false,
"matchMedia": false,
"MediaDeviceInfo": false,
"MediaDevices": false,
"MediaElementAudioSourceNode": false,
"MediaEncryptedEvent": false,
"MediaError": false,
"MediaKeyMessageEvent": false,
"MediaKeySession": false,
"MediaKeyStatusMap": false,
"MediaKeySystemAccess": false,
"MediaList": false,
"MediaMetadata": false,
"MediaQueryList": false,
"MediaQueryListEvent": false,
"MediaRecorder": false,
"MediaSettingsRange": false,
"MediaSource": false,
"MediaStream": false,
"MediaStreamAudioDestinationNode": false,
"MediaStreamAudioSourceNode": false,
"MediaStreamEvent": false,
"MediaStreamTrack": false,
"MediaStreamTrackEvent": false,
"menubar": false,
"MessageChannel": false,
"MessageEvent": false,
"MessagePort": false,
"MIDIAccess": false,
"MIDIConnectionEvent": false,
"MIDIInput": false,
"MIDIInputMap": false,
"MIDIMessageEvent": false,
"MIDIOutput": false,
"MIDIOutputMap": false,
"MIDIPort": false,
"MimeType": false,
"MimeTypeArray": false,
"MouseEvent": false,
"moveBy": false,
"moveTo": false,
"MutationEvent": false,
"MutationObserver": false,
"MutationRecord": false,
"name": false,
"NamedNodeMap": false,
"NavigationPreloadManager": false,
"navigator": false,
"Navigator": false,
"NetworkInformation": false,
"Node": false,
"NodeFilter": false,
"NodeIterator": false,
"NodeList": false,
"Notification": false,
"OfflineAudioCompletionEvent": false,
"OfflineAudioContext": false,
"offscreenBuffering": false,
"OffscreenCanvas": true,
"OffscreenCanvasRenderingContext2D": false,
"onabort": true,
"onafterprint": true,
"onanimationend": true,
"onanimationiteration": true,
"onanimationstart": true,
"onappinstalled": true,
"onauxclick": true,
"onbeforeinstallprompt": true,
"onbeforeprint": true,
"onbeforeunload": true,
"onblur": true,
"oncancel": true,
"oncanplay": true,
"oncanplaythrough": true,
"onchange": true,
"onclick": true,
"onclose": true,
"oncontextmenu": true,
"oncuechange": true,
"ondblclick": true,
"ondevicemotion": true,
"ondeviceorientation": true,
"ondeviceorientationabsolute": true,
"ondrag": true,
"ondragend": true,
"ondragenter": true,
"ondragleave": true,
"ondragover": true,
"ondragstart": true,
"ondrop": true,
"ondurationchange": true,
"onemptied": true,
"onended": true,
"onerror": true,
"onfocus": true,
"ongotpointercapture": true,
"onhashchange": true,
"oninput": true,
"oninvalid": true,
"onkeydown": true,
"onkeypress": true,
"onkeyup": true,
"onlanguagechange": true,
"onload": true,
"onloadeddata": true,
"onloadedmetadata": true,
"onloadstart": true,
"onlostpointercapture": true,
"onmessage": true,
"onmessageerror": true,
"onmousedown": true,
"onmouseenter": true,
"onmouseleave": true,
"onmousemove": true,
"onmouseout": true,
"onmouseover": true,
"onmouseup": true,
"onmousewheel": true,
"onoffline": true,
"ononline": true,
"onpagehide": true,
"onpageshow": true,
"onpause": true,
"onplay": true,
"onplaying": true,
"onpointercancel": true,
"onpointerdown": true,
"onpointerenter": true,
"onpointerleave": true,
"onpointermove": true,
"onpointerout": true,
"onpointerover": true,
"onpointerup": true,
"onpopstate": true,
"onprogress": true,
"onratechange": true,
"onrejectionhandled": true,
"onreset": true,
"onresize": true,
"onscroll": true,
"onsearch": true,
"onseeked": true,
"onseeking": true,
"onselect": true,
"onstalled": true,
"onstorage": true,
"onsubmit": true,
"onsuspend": true,
"ontimeupdate": true,
"ontoggle": true,
"ontransitionend": true,
"onunhandledrejection": true,
"onunload": true,
"onvolumechange": true,
"onwaiting": true,
"onwheel": true,
"open": false,
"openDatabase": false,
"opener": false,
"Option": false,
"origin": false,
"OscillatorNode": false,
"outerHeight": false,
"outerWidth": false,
"OverconstrainedError": false,
"PageTransitionEvent": false,
"pageXOffset": false,
"pageYOffset": false,
"PannerNode": false,
"parent": false,
"Path2D": false,
"PaymentAddress": false,
"PaymentRequest": false,
"PaymentRequestUpdateEvent": false,
"PaymentResponse": false,
"performance": false,
"Performance": false,
"PerformanceEntry": false,
"PerformanceLongTaskTiming": false,
"PerformanceMark": false,
"PerformanceMeasure": false,
"PerformanceNavigation": false,
"PerformanceNavigationTiming": false,
"PerformanceObserver": false,
"PerformanceObserverEntryList": false,
"PerformancePaintTiming": false,
"PerformanceResourceTiming": false,
"PerformanceTiming": false,
"PeriodicWave": false,
"Permissions": false,
"PermissionStatus": false,
"personalbar": false,
"PhotoCapabilities": false,
"Plugin": false,
"PluginArray": false,
"PointerEvent": false,
"PopStateEvent": false,
"postMessage": false,
"Presentation": false,
"PresentationAvailability": false,
"PresentationConnection": false,
"PresentationConnectionAvailableEvent": false,
"PresentationConnectionCloseEvent": false,
"PresentationConnectionList": false,
"PresentationReceiver": false,
"PresentationRequest": false,
"print": false,
"ProcessingInstruction": false,
"ProgressEvent": false,
"PromiseRejectionEvent": false,
"prompt": false,
"PushManager": false,
"PushSubscription": false,
"PushSubscriptionOptions": false,
"queueMicrotask": false,
"RadioNodeList": false,
"Range": false,
"ReadableStream": false,
"registerProcessor": false,
"RemotePlayback": false,
"removeEventListener": false,
"reportError": false,
"Request": false,
"requestAnimationFrame": false,
"requestIdleCallback": false,
"resizeBy": false,
"ResizeObserver": false,
"ResizeObserverEntry": false,
"resizeTo": false,
"Response": false,
"RTCCertificate": false,
"RTCDataChannel": false,
"RTCDataChannelEvent": false,
"RTCDtlsTransport": false,
"RTCIceCandidate": false,
"RTCIceGatherer": false,
"RTCIceTransport": false,
"RTCPeerConnection": false,
"RTCPeerConnectionIceEvent": false,
"RTCRtpContributingSource": false,
"RTCRtpReceiver": false,
"RTCRtpSender": false,
"RTCSctpTransport": false,
"RTCSessionDescription": false,
"RTCStatsReport": false,
"RTCTrackEvent": false,
"screen": false,
"Screen": false,
"screenLeft": false,
"ScreenOrientation": false,
"screenTop": false,
"screenX": false,
"screenY": false,
"ScriptProcessorNode": false,
"scroll": false,
"scrollbars": false,
"scrollBy": false,
"scrollTo": false,
"scrollX": false,
"scrollY": false,
"SecurityPolicyViolationEvent": false,
"Selection": false,
"self": false,
"ServiceWorker": false,
"ServiceWorkerContainer": false,
"ServiceWorkerRegistration": false,
"sessionStorage": false,
"setInterval": false,
"setTimeout": false,
"ShadowRoot": false,
"SharedWorker": false,
"SourceBuffer": false,
"SourceBufferList": false,
"speechSynthesis": false,
"SpeechSynthesisEvent": false,
"SpeechSynthesisUtterance": false,
"StaticRange": false,
"status": false,
"statusbar": false,
"StereoPannerNode": false,
"stop": false,
"Storage": false,
"StorageEvent": false,
"StorageManager": false,
"structuredClone": false,
"styleMedia": false,
"StyleSheet": false,
"StyleSheetList": false,
"SubtleCrypto": false,
"SVGAElement": false,
"SVGAngle": false,
"SVGAnimatedAngle": false,
"SVGAnimatedBoolean": false,
"SVGAnimatedEnumeration": false,
"SVGAnimatedInteger": false,
"SVGAnimatedLength": false,
"SVGAnimatedLengthList": false,
"SVGAnimatedNumber": false,
"SVGAnimatedNumberList": false,
"SVGAnimatedPreserveAspectRatio": false,
"SVGAnimatedRect": false,
"SVGAnimatedString": false,
"SVGAnimatedTransformList": false,
"SVGAnimateElement": false,
"SVGAnimateMotionElement": false,
"SVGAnimateTransformElement": false,
"SVGAnimationElement": false,
"SVGCircleElement": false,
"SVGClipPathElement": false,
"SVGComponentTransferFunctionElement": false,
"SVGDefsElement": false,
"SVGDescElement": false,
"SVGDiscardElement": false,
"SVGElement": false,
"SVGEllipseElement": false,
"SVGFEBlendElement": false,
"SVGFEColorMatrixElement": false,
"SVGFEComponentTransferElement": false,
"SVGFECompositeElement": false,
"SVGFEConvolveMatrixElement": false,
"SVGFEDiffuseLightingElement": false,
"SVGFEDisplacementMapElement": false,
"SVGFEDistantLightElement": false,
"SVGFEDropShadowElement": false,
"SVGFEFloodElement": false,
"SVGFEFuncAElement": false,
"SVGFEFuncBElement": false,
"SVGFEFuncGElement": false,
"SVGFEFuncRElement": false,
"SVGFEGaussianBlurElement": false,
"SVGFEImageElement": false,
"SVGFEMergeElement": false,
"SVGFEMergeNodeElement": false,
"SVGFEMorphologyElement": false,
"SVGFEOffsetElement": false,
"SVGFEPointLightElement": false,
"SVGFESpecularLightingElement": false,
"SVGFESpotLightElement": false,
"SVGFETileElement": false,
"SVGFETurbulenceElement": false,
"SVGFilterElement": false,
"SVGForeignObjectElement": false,
"SVGGElement": false,
"SVGGeometryElement": false,
"SVGGradientElement": false,
"SVGGraphicsElement": false,
"SVGImageElement": false,
"SVGLength": false,
"SVGLengthList": false,
"SVGLinearGradientElement": false,
"SVGLineElement": false,
"SVGMarkerElement": false,
"SVGMaskElement": false,
"SVGMatrix": false,
"SVGMetadataElement": false,
"SVGMPathElement": false,
"SVGNumber": false,
"SVGNumberList": false,
"SVGPathElement": false,
"SVGPatternElement": false,
"SVGPoint": false,
"SVGPointList": false,
"SVGPolygonElement": false,
"SVGPolylineElement": false,
"SVGPreserveAspectRatio": false,
"SVGRadialGradientElement": false,
"SVGRect": false,
"SVGRectElement": false,
"SVGScriptElement": false,
"SVGSetElement": false,
"SVGStopElement": false,
"SVGStringList": false,
"SVGStyleElement": false,
"SVGSVGElement": false,
"SVGSwitchElement": false,
"SVGSymbolElement": false,
"SVGTextContentElement": false,
"SVGTextElement": false,
"SVGTextPathElement": false,
"SVGTextPositioningElement": false,
"SVGTitleElement": false,
"SVGTransform": false,
"SVGTransformList": false,
"SVGTSpanElement": false,
"SVGUnitTypes": false,
"SVGUseElement": false,
"SVGViewElement": false,
"TaskAttributionTiming": false,
"Text": false,
"TextDecoder": false,
"TextEncoder": false,
"TextEvent": false,
"TextMetrics": false,
"TextTrack": false,
"TextTrackCue": false,
"TextTrackCueList": false,
"TextTrackList": false,
"TimeRanges": false,
"toolbar": false,
"top": false,
"Touch": false,
"TouchEvent": false,
"TouchList": false,
"TrackEvent": false,
"TransitionEvent": false,
"TreeWalker": false,
"UIEvent": false,
"URL": false,
"URLSearchParams": false,
"ValidityState": false,
"visualViewport": false,
"VisualViewport": false,
"VTTCue": false,
"WaveShaperNode": false,
"WebAssembly": false,
"WebGL2RenderingContext": false,
"WebGLActiveInfo": false,
"WebGLBuffer": false,
"WebGLContextEvent": false,
"WebGLFramebuffer": false,
"WebGLProgram": false,
"WebGLQuery": false,
"WebGLRenderbuffer": false,
"WebGLRenderingContext": false,
"WebGLSampler": false,
"WebGLShader": false,
"WebGLShaderPrecisionFormat": false,
"WebGLSync": false,
"WebGLTexture": false,
"WebGLTransformFeedback": false,
"WebGLUniformLocation": false,
"WebGLVertexArrayObject": false,
"WebSocket": false,
"WheelEvent": false,
"window": false,
"Window": false,
"Worker": false,
"WritableStream": false,
"XMLDocument": false,
"XMLHttpRequest": false,
"XMLHttpRequestEventTarget": false,
"XMLHttpRequestUpload": false,
"XMLSerializer": false,
"XPathEvaluator": false,
"XPathExpression": false,
"XPathResult": false,
"XSLTProcessor": false
},
"worker": {
"addEventListener": false,
"applicationCache": false,
"atob": false,
"Blob": false,
"BroadcastChannel": false,
"btoa": false,
"Cache": false,
"caches": false,
"clearInterval": false,
"clearTimeout": false,
"close": true,
"console": false,
"fetch": false,
"FileReaderSync": false,
"FormData": false,
"Headers": false,
"IDBCursor": false,
"IDBCursorWithValue": false,
"IDBDatabase": false,
"IDBFactory": false,
"IDBIndex": false,
"IDBKeyRange": false,
"IDBObjectStore": false,
"IDBOpenDBRequest": false,
"IDBRequest": false,
"IDBTransaction": false,
"IDBVersionChangeEvent": false,
"ImageData": false,
"importScripts": true,
"indexedDB": false,
"location": false,
"MessageChannel": false,
"MessagePort": false,
"name": false,
"navigator": false,
"Notification": false,
"onclose": true,
"onconnect": true,
"onerror": true,
"onlanguagechange": true,
"onmessage": true,
"onoffline": true,
"ononline": true,
"onrejectionhandled": true,
"onunhandledrejection": true,
"performance": false,
"Performance": false,
"PerformanceEntry": false,
"PerformanceMark": false,
"PerformanceMeasure": false,
"PerformanceNavigation": false,
"PerformanceResourceTiming": false,
"PerformanceTiming": false,
"postMessage": true,
"Promise": false,
"queueMicrotask": false,
"removeEventListener": false,
"reportError": false,
"Request": false,
"Response": false,
"self": true,
"ServiceWorkerRegistration": false,
"setInterval": false,
"setTimeout": false,
"TextDecoder": false,
"TextEncoder": false,
"URL": false,
"URLSearchParams": false,
"WebSocket": false,
"Worker": false,
"WorkerGlobalScope": false,
"XMLHttpRequest": false
},
"node": {
"__dirname": false,
"__filename": false,
"AbortController": false,
"AbortSignal": false,
"atob": false,
"btoa": false,
"Buffer": false,
"clearImmediate": false,
"clearInterval": false,
"clearTimeout": false,
"console": false,
"DOMException": false,
"Event": false,
"EventTarget": false,
"exports": true,
"fetch": false,
"global": false,
"Intl": false,
"MessageChannel": false,
"MessageEvent": false,
"MessagePort": false,
"module": false,
"performance": false,
"process": false,
"queueMicrotask": false,
"require": false,
"setImmediate": false,
"setInterval": false,
"setTimeout": false,
"structuredClone": false,
"TextDecoder": false,
"TextEncoder": false,
"URL": false,
"URLSearchParams": false
},
"nodeBuiltin": {
"AbortController": false,
"AbortSignal": false,
"atob": false,
"btoa": false,
"Buffer": false,
"clearImmediate": false,
"clearInterval": false,
"clearTimeout": false,
"console": false,
"DOMException": false,
"Event": false,
"EventTarget": false,
"fetch": false,
"global": false,
"Intl": false,
"MessageChannel": false,
"MessageEvent": false,
"MessagePort": false,
"performance": false,
"process": false,
"queueMicrotask": false,
"setImmediate": false,
"setInterval": false,
"setTimeout": false,
"structuredClone": false,
"TextDecoder": false,
"TextEncoder": false,
"URL": false,
"URLSearchParams": false
},
"commonjs": {
"exports": true,
"global": false,
"module": false,
"require": false
},
"amd": {
"define": false,
"require": false
},
"mocha": {
"after": false,
"afterEach": false,
"before": false,
"beforeEach": false,
"context": false,
"describe": false,
"it": false,
"mocha": false,
"run": false,
"setup": false,
"specify": false,
"suite": false,
"suiteSetup": false,
"suiteTeardown": false,
"teardown": false,
"test": false,
"xcontext": false,
"xdescribe": false,
"xit": false,
"xspecify": false
},
"jasmine": {
"afterAll": false,
"afterEach": false,
"beforeAll": false,
"beforeEach": false,
"describe": false,
"expect": false,
"expectAsync": false,
"fail": false,
"fdescribe": false,
"fit": false,
"it": false,
"jasmine": false,
"pending": false,
"runs": false,
"spyOn": false,
"spyOnAllFunctions": false,
"spyOnProperty": false,
"waits": false,
"waitsFor": false,
"xdescribe": false,
"xit": false
},
"jest": {
"afterAll": false,
"afterEach": false,
"beforeAll": false,
"beforeEach": false,
"describe": false,
"expect": false,
"fdescribe": false,
"fit": false,
"it": false,
"jest": false,
"pit": false,
"require": false,
"test": false,
"xdescribe": false,
"xit": false,
"xtest": false
},
"qunit": {
"asyncTest": false,
"deepEqual": false,
"equal": false,
"expect": false,
"module": false,
"notDeepEqual": false,
"notEqual": false,
"notOk": false,
"notPropEqual": false,
"notStrictEqual": false,
"ok": false,
"propEqual": false,
"QUnit": false,
"raises": false,
"start": false,
"stop": false,
"strictEqual": false,
"test": false,
"throws": false
},
"phantomjs": {
"console": true,
"exports": true,
"phantom": true,
"require": true,
"WebPage": true
},
"couch": {
"emit": false,
"exports": false,
"getRow": false,
"log": false,
"module": false,
"provides": false,
"require": false,
"respond": false,
"send": false,
"start": false,
"sum": false
},
"rhino": {
"defineClass": false,
"deserialize": false,
"gc": false,
"help": false,
"importClass": false,
"importPackage": false,
"java": false,
"load": false,
"loadClass": false,
"Packages": false,
"print": false,
"quit": false,
"readFile": false,
"readUrl": false,
"runCommand": false,
"seal": false,
"serialize": false,
"spawn": false,
"sync": false,
"toint32": false,
"version": false
},
"nashorn": {
"__DIR__": false,
"__FILE__": false,
"__LINE__": false,
"com": false,
"edu": false,
"exit": false,
"java": false,
"Java": false,
"javafx": false,
"JavaImporter": false,
"javax": false,
"JSAdapter": false,
"load": false,
"loadWithNewGlobal": false,
"org": false,
"Packages": false,
"print": false,
"quit": false
},
"wsh": {
"ActiveXObject": false,
"CollectGarbage": false,
"Debug": false,
"Enumerator": false,
"GetObject": false,
"RuntimeObject": false,
"ScriptEngine": false,
"ScriptEngineBuildVersion": false,
"ScriptEngineMajorVersion": false,
"ScriptEngineMinorVersion": false,
"VBArray": false,
"WScript": false,
"WSH": false
},
"jquery": {
"$": false,
"jQuery": false
},
"yui": {
"YAHOO": false,
"YAHOO_config": false,
"YUI": false,
"YUI_config": false
},
"shelljs": {
"cat": false,
"cd": false,
"chmod": false,
"config": false,
"cp": false,
"dirs": false,
"echo": false,
"env": false,
"error": false,
"exec": false,
"exit": false,
"find": false,
"grep": false,
"ln": false,
"ls": false,
"mkdir": false,
"mv": false,
"popd": false,
"pushd": false,
"pwd": false,
"rm": false,
"sed": false,
"set": false,
"target": false,
"tempdir": false,
"test": false,
"touch": false,
"which": false
},
"prototypejs": {
"$": false,
"$$": false,
"$A": false,
"$break": false,
"$continue": false,
"$F": false,
"$H": false,
"$R": false,
"$w": false,
"Abstract": false,
"Ajax": false,
"Autocompleter": false,
"Builder": false,
"Class": false,
"Control": false,
"Draggable": false,
"Draggables": false,
"Droppables": false,
"Effect": false,
"Element": false,
"Enumerable": false,
"Event": false,
"Field": false,
"Form": false,
"Hash": false,
"Insertion": false,
"ObjectRange": false,
"PeriodicalExecuter": false,
"Position": false,
"Prototype": false,
"Scriptaculous": false,
"Selector": false,
"Sortable": false,
"SortableObserver": false,
"Sound": false,
"Template": false,
"Toggle": false,
"Try": false
},
"meteor": {
"$": false,
"Accounts": false,
"AccountsClient": false,
"AccountsCommon": false,
"AccountsServer": false,
"App": false,
"Assets": false,
"Blaze": false,
"check": false,
"Cordova": false,
"DDP": false,
"DDPRateLimiter": false,
"DDPServer": false,
"Deps": false,
"EJSON": false,
"Email": false,
"HTTP": false,
"Log": false,
"Match": false,
"Meteor": false,
"Mongo": false,
"MongoInternals": false,
"Npm": false,
"Package": false,
"Plugin": false,
"process": false,
"Random": false,
"ReactiveDict": false,
"ReactiveVar": false,
"Router": false,
"ServiceConfiguration": false,
"Session": false,
"share": false,
"Spacebars": false,
"Template": false,
"Tinytest": false,
"Tracker": false,
"UI": false,
"Utils": false,
"WebApp": false,
"WebAppInternals": false
},
"mongo": {
"_isWindows": false,
"_rand": false,
"BulkWriteResult": false,
"cat": false,
"cd": false,
"connect": false,
"db": false,
"getHostName": false,
"getMemInfo": false,
"hostname": false,
"ISODate": false,
"listFiles": false,
"load": false,
"ls": false,
"md5sumFile": false,
"mkdir": false,
"Mongo": false,
"NumberInt": false,
"NumberLong": false,
"ObjectId": false,
"PlanCache": false,
"print": false,
"printjson": false,
"pwd": false,
"quit": false,
"removeFile": false,
"rs": false,
"sh": false,
"UUID": false,
"version": false,
"WriteResult": false
},
"applescript": {
"$": false,
"Application": false,
"Automation": false,
"console": false,
"delay": false,
"Library": false,
"ObjC": false,
"ObjectSpecifier": false,
"Path": false,
"Progress": false,
"Ref": false
},
"serviceworker": {
"addEventListener": false,
"applicationCache": false,
"atob": false,
"Blob": false,
"BroadcastChannel": false,
"btoa": false,
"Cache": false,
"caches": false,
"CacheStorage": false,
"clearInterval": false,
"clearTimeout": false,
"Client": false,
"clients": false,
"Clients": false,
"close": true,
"console": false,
"ExtendableEvent": false,
"ExtendableMessageEvent": false,
"fetch": false,
"FetchEvent": false,
"FileReaderSync": false,
"FormData": false,
"Headers": false,
"IDBCursor": false,
"IDBCursorWithValue": false,
"IDBDatabase": false,
"IDBFactory": false,
"IDBIndex": false,
"IDBKeyRange": false,
"IDBObjectStore": false,
"IDBOpenDBRequest": false,
"IDBRequest": false,
"IDBTransaction": false,
"IDBVersionChangeEvent": false,
"ImageData": false,
"importScripts": false,
"indexedDB": false,
"location": false,
"MessageChannel": false,
"MessagePort": false,
"name": false,
"navigator": false,
"Notification": false,
"onclose": true,
"onconnect": true,
"onerror": true,
"onfetch": true,
"oninstall": true,
"onlanguagechange": true,
"onmessage": true,
"onmessageerror": true,
"onnotificationclick": true,
"onnotificationclose": true,
"onoffline": true,
"ononline": true,
"onpush": true,
"onpushsubscriptionchange": true,
"onrejectionhandled": true,
"onsync": true,
"onunhandledrejection": true,
"performance": false,
"Performance": false,
"PerformanceEntry": false,
"PerformanceMark": false,
"PerformanceMeasure": false,
"PerformanceNavigation": false,
"PerformanceResourceTiming": false,
"PerformanceTiming": false,
"postMessage": true,
"Promise": false,
"queueMicrotask": false,
"registration": false,
"removeEventListener": false,
"Request": false,
"Response": false,
"self": false,
"ServiceWorker": false,
"ServiceWorkerContainer": false,
"ServiceWorkerGlobalScope": false,
"ServiceWorkerMessageEvent": false,
"ServiceWorkerRegistration": false,
"setInterval": false,
"setTimeout": false,
"skipWaiting": false,
"TextDecoder": false,
"TextEncoder": false,
"URL": false,
"URLSearchParams": false,
"WebSocket": false,
"WindowClient": false,
"Worker": false,
"WorkerGlobalScope": false,
"XMLHttpRequest": false
},
"atomtest": {
"advanceClock": false,
"atom": false,
"fakeClearInterval": false,
"fakeClearTimeout": false,
"fakeSetInterval": false,
"fakeSetTimeout": false,
"resetTimeouts": false,
"waitsForPromise": false
},
"embertest": {
"andThen": false,
"click": false,
"currentPath": false,
"currentRouteName": false,
"currentURL": false,
"fillIn": false,
"find": false,
"findAll": false,
"findWithAssert": false,
"keyEvent": false,
"pauseTest": false,
"resumeTest": false,
"triggerEvent": false,
"visit": false,
"wait": false
},
"protractor": {
"$": false,
"$$": false,
"browser": false,
"by": false,
"By": false,
"DartObject": false,
"element": false,
"protractor": false
},
"shared-node-browser": {
"AbortController": false,
"AbortSignal": false,
"atob": false,
"btoa": false,
"clearInterval": false,
"clearTimeout": false,
"console": false,
"DOMException": false,
"Event": false,
"EventTarget": false,
"fetch": false,
"Intl": false,
"MessageChannel": false,
"MessageEvent": false,
"MessagePort": false,
"performance": false,
"queueMicrotask": false,
"setInterval": false,
"setTimeout": false,
"structuredClone": false,
"TextDecoder": false,
"TextEncoder": false,
"URL": false,
"URLSearchParams": false
},
"webextensions": {
"browser": false,
"chrome": false,
"opr": false
},
"greasemonkey": {
"cloneInto": false,
"createObjectIn": false,
"exportFunction": false,
"GM": false,
"GM_addElement": false,
"GM_addStyle": false,
"GM_addValueChangeListener": false,
"GM_deleteValue": false,
"GM_download": false,
"GM_getResourceText": false,
"GM_getResourceURL": false,
"GM_getTab": false,
"GM_getTabs": false,
"GM_getValue": false,
"GM_info": false,
"GM_listValues": false,
"GM_log": false,
"GM_notification": false,
"GM_openInTab": false,
"GM_registerMenuCommand": false,
"GM_removeValueChangeListener": false,
"GM_saveTab": false,
"GM_setClipboard": false,
"GM_setValue": false,
"GM_unregisterMenuCommand": false,
"GM_xmlhttpRequest": false,
"unsafeWindow": false
},
"devtools": {
"$": false,
"$_": false,
"$$": false,
"$0": false,
"$1": false,
"$2": false,
"$3": false,
"$4": false,
"$x": false,
"chrome": false,
"clear": false,
"copy": false,
"debug": false,
"dir": false,
"dirxml": false,
"getEventListeners": false,
"inspect": false,
"keys": false,
"monitor": false,
"monitorEvents": false,
"profile": false,
"profileEnd": false,
"queryObjects": false,
"table": false,
"undebug": false,
"unmonitor": false,
"unmonitorEvents": false,
"values": false
}
}
import {ReadonlyDeep} from 'type-fest';
import globalsJson = require('./globals.json');
declare const globals: ReadonlyDeep<typeof globalsJson>;
export = globals;
'use strict';
module.exports = require('./globals.json');
Copyright 2019 - present Christopher J. Brody and other contributors, as listed in: https://github.com/xmldom/xmldom/graphs/contributors
Copyright 2012 - 2017 @jindw <jindw@xidea.org> and other contributors, as listed in: https://github.com/jindw/xmldom/graphs/contributors
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
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:
......
{
"name": "globals",
"version": "13.16.0",
"description": "Global identifiers from different JavaScript environments",
"license": "MIT",
"repository": "sindresorhus/globals",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"engines": {
"node": ">=8"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js",
"index.d.ts",
"globals.json"
],
"keywords": [
"globals",
"global",
"identifiers",
"variables",
"vars",
"jshint",
"eslint",
"environments"
],
"dependencies": {
"type-fest": "^0.20.2"
},
"devDependencies": {
"ava": "^2.4.0",
"tsd": "^0.14.0",
"xo": "^0.36.1"
},
"xo": {
"ignores": [
"get-browser-globals.js"
],
"rules": {
"node/no-unsupported-features/es-syntax": "off"
}
},
"tsd": {
"compilerOptions": {
"resolveJsonModule": true
}
}
}
# globals
> Global identifiers from different JavaScript environments
It's just a [JSON file](globals.json), so use it in any environment.
This package is used by ESLint.
**This package [no longer accepts](https://github.com/sindresorhus/globals/issues/82) new environments. If you need it for ESLint, just [create a plugin](http://eslint.org/docs/developer-guide/working-with-plugins#environments-in-plugins).**
## Install
```
$ npm install globals
```
## Usage
```js
const globals = require('globals');
console.log(globals.browser);
/*
{
addEventListener: false,
applicationCache: false,
ArrayBuffer: false,
atob: false,
}
*/
```
Each global is given a value of `true` or `false`. A value of `true` indicates that the variable may be overwritten. A value of `false` indicates that the variable should be considered read-only. This information is used by static analysis tools to flag incorrect behavior. We assume all variables should be `false` unless we hear otherwise.
For Node.js this package provides two sets of globals:
- `globals.nodeBuiltin`: Globals available to all code running in Node.js.
These will usually be available as properties on the `global` object and include `process`, `Buffer`, but not CommonJS arguments like `require`.
See: https://nodejs.org/api/globals.html
- `globals.node`: A combination of the globals from `nodeBuiltin` plus all CommonJS arguments ("CommonJS module scope").
See: https://nodejs.org/api/modules.html#modules_the_module_scope
When analyzing code that is known to run outside of a CommonJS wrapper, for example, JavaScript modules, `nodeBuiltin` can find accidental CommonJS references.
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-globals?utm_source=npm-globals&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>
# `node-ignore` 4 ChangeLog
# 4.x
## 2018-06-22, Version 4.0.0
- **SEMVER-MAJOR**: Drop support for node < 6 by default.
- **FEATURE**: supports the missing character ranges and sets, such as `*.[a-z]` and `*.[jJ][pP][gG]`
- **FEATURE**: new option: `ignorecase` to make `ignore` case sensitive.
- **FEATURE**: supports question mark which matches a single character.
- **PATCH**: fixes typescript declaration.
## ~ 2018-08-09, Version 4.0.1 - 4.0.5
- **PATCH**: updates README.md about frequent asked quesions from github issues.
## 2018-08-12, Version 4.0.6
- **PATCH**: `Object.prototype` methods will not ruin the result any more.
Copyright (c) 2013 Kael Zhang <i@kael.me>, contributors
http://kael.me/
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.
\ No newline at end of file
<table><thead>
<tr>
<th>Linux</th>
<th>OS X</th>
<th>Windows</th>
<th>Coverage</th>
<th>Downloads</th>
</tr>
</thead><tbody><tr>
<td colspan="2" align="center">
<a href="https://travis-ci.org/kaelzhang/node-ignore">
<img
src="https://travis-ci.org/kaelzhang/node-ignore.svg?branch=master"
alt="Build Status" /></a>
</td>
<td align="center">
<a href="https://ci.appveyor.com/project/kaelzhang/node-ignore">
<img
src="https://ci.appveyor.com/api/projects/status/github/kaelzhang/node-ignore?branch=master&svg=true"
alt="Windows Build Status" /></a>
</td>
<td align="center">
<a href="https://codecov.io/gh/kaelzhang/node-ignore">
<img
src="https://codecov.io/gh/kaelzhang/node-ignore/branch/master/graph/badge.svg"
alt="Coverage Status" /></a>
</td>
<td align="center">
<a href="https://www.npmjs.org/package/ignore">
<img
src="http://img.shields.io/npm/dm/ignore.svg"
alt="npm module downloads per month" /></a>
</td>
</tr></tbody></table>
# ignore
`ignore` is a manager, filter and parser which implemented in pure JavaScript according to the .gitignore [spec](http://git-scm.com/docs/gitignore).
Pay attention that [`minimatch`](https://www.npmjs.org/package/minimatch) does not work in the gitignore way. To filter filenames according to .gitignore file, I recommend this module.
##### Tested on
- Linux + Node: `0.8` - `7.x`
- Windows + Node: `0.10` - `7.x`, node < `0.10` is not tested due to the lack of support of appveyor.
Actually, `ignore` does not rely on any versions of node specially.
Since `4.0.0`, ignore will no longer support `node < 6` by default, to use in node < 6, `require('ignore/legacy')`. For details, see [CHANGELOG](https://github.com/kaelzhang/node-ignore/blob/master/CHANGELOG.md).
## Table Of Main Contents
- [Usage](#usage)
- [`Pathname` Conventions](#pathname-conventions)
- [Guide for 2.x -> 3.x](#upgrade-2x---3x)
- [Guide for 3.x -> 4.x](#upgrade-3x---4x)
- See Also:
- [`glob-gitignore`](https://www.npmjs.com/package/glob-gitignore) matches files using patterns and filters them according to gitignore rules.
## Usage
```js
import ignore from 'ignore'
const ig = ignore().add(['.abc/*', '!.abc/d/'])
```
### Filter the given paths
```js
const paths = [
'.abc/a.js', // filtered out
'.abc/d/e.js' // included
]
ig.filter(paths) // ['.abc/d/e.js']
ig.ignores('.abc/a.js') // true
```
### As the filter function
```js
paths.filter(ig.createFilter()); // ['.abc/d/e.js']
```
### Win32 paths will be handled
```js
ig.filter(['.abc\\a.js', '.abc\\d\\e.js'])
// if the code above runs on windows, the result will be
// ['.abc\\d\\e.js']
```
## Why another ignore?
- `ignore` is a standalone module, and is much simpler so that it could easy work with other programs, unlike [isaacs](https://npmjs.org/~isaacs)'s [fstream-ignore](https://npmjs.org/package/fstream-ignore) which must work with the modules of the fstream family.
- `ignore` only contains utility methods to filter paths according to the specified ignore rules, so
- `ignore` never try to find out ignore rules by traversing directories or fetching from git configurations.
- `ignore` don't cares about sub-modules of git projects.
- Exactly according to [gitignore man page](http://git-scm.com/docs/gitignore), fixes some known matching issues of fstream-ignore, such as:
- '`/*.js`' should only match '`a.js`', but not '`abc/a.js`'.
- '`**/foo`' should match '`foo`' anywhere.
- Prevent re-including a file if a parent directory of that file is excluded.
- Handle trailing whitespaces:
- `'a '`(one space) should not match `'a '`(two spaces).
- `'a \ '` matches `'a '`
- All test cases are verified with the result of `git check-ignore`.
# Methods
## .add(pattern: string | Ignore): this
## .add(patterns: Array<string | Ignore>): this
- **pattern** `String | Ignore` An ignore pattern string, or the `Ignore` instance
- **patterns** `Array<String | Ignore>` Array of ignore patterns.
Adds a rule or several rules to the current manager.
Returns `this`
Notice that a line starting with `'#'`(hash) is treated as a comment. Put a backslash (`'\'`) in front of the first hash for patterns that begin with a hash, if you want to ignore a file with a hash at the beginning of the filename.
```js
ignore().add('#abc').ignores('#abc') // false
ignore().add('\#abc').ignores('#abc') // true
```
`pattern` could either be a line of ignore pattern or a string of multiple ignore patterns, which means we could just `ignore().add()` the content of a ignore file:
```js
ignore()
.add(fs.readFileSync(filenameOfGitignore).toString())
.filter(filenames)
```
`pattern` could also be an `ignore` instance, so that we could easily inherit the rules of another `Ignore` instance.
## <strike>.addIgnoreFile(path)</strike>
REMOVED in `3.x` for now.
To upgrade `ignore@2.x` up to `3.x`, use
```js
import fs from 'fs'
if (fs.existsSync(filename)) {
ignore().add(fs.readFileSync(filename).toString())
}
```
instead.
## .filter(paths: Array<Pathname>): Array<Pathname>
```ts
type Pathname = string
```
Filters the given array of pathnames, and returns the filtered array.
- **paths** `Array.<Pathname>` The array of `pathname`s to be filtered.
### `Pathname` Conventions:
#### 1. `Pathname` should be a `path.relative()`d pathname
`Pathname` should be a string that have been `path.join()`ed, or the return value of `path.relative()` to the current directory.
```js
// WRONG
ig.ignores('./abc')
// WRONG, for it will never happen.
// If the gitignore rule locates at the root directory,
// `'/abc'` should be changed to `'abc'`.
// ```
// path.relative('/', '/abc') -> 'abc'
// ```
ig.ignores('/abc')
// Right
ig.ignores('abc')
// Right
ig.ignores(path.join('./abc')) // path.join('./abc') -> 'abc'
```
In other words, each `Pathname` here should be a relative path to the directory of the gitignore rules.
Suppose the dir structure is:
```
/path/to/your/repo
|-- a
| |-- a.js
|
|-- .b
|
|-- .c
|-- .DS_store
```
Then the `paths` might be like this:
```js
[
'a/a.js'
'.b',
'.c/.DS_store'
]
```
Usually, you could use [`glob`](http://npmjs.org/package/glob) with `option.mark = true` to fetch the structure of the current directory:
```js
import glob from 'glob'
glob('**', {
// Adds a / character to directory matches.
mark: true
}, (err, files) => {
if (err) {
return console.error(err)
}
let filtered = ignore().add(patterns).filter(files)
console.log(filtered)
})
```
#### 2. filenames and dirnames
`node-ignore` does NO `fs.stat` during path matching, so for the example below:
```js
ig.add('config/')
// `ig` does NOT know if 'config' is a normal file, directory or something
ig.ignores('config') // And it returns `false`
ig.ignores('config/') // returns `true`
```
Specially for people who develop some library based on `node-ignore`, it is important to understand that.
## .ignores(pathname: Pathname): boolean
> new in 3.2.0
Returns `Boolean` whether `pathname` should be ignored.
```js
ig.ignores('.abc/a.js') // true
```
## .createFilter()
Creates a filter function which could filter an array of paths with `Array.prototype.filter`.
Returns `function(path)` the filter function.
## `options.ignorecase` since 4.0.0
Similar as the `core.ignorecase` option of [git-config](https://git-scm.com/docs/git-config), `node-ignore` will be case insensitive if `options.ignorecase` is set to `true` (default value), otherwise case sensitive.
```js
const ig = ignore({
ignorecase: false
})
ig.add('*.png')
ig.ignores('*.PNG') // false
```
****
# Upgrade Guide
## Upgrade 2.x -> 3.x
- All `options` of 2.x are unnecessary and removed, so just remove them.
- `ignore()` instance is no longer an [`EventEmitter`](nodejs.org/api/events.html), and all events are unnecessary and removed.
- `.addIgnoreFile()` is removed, see the [.addIgnoreFile](#addignorefilepath) section for details.
## Upgrade 3.x -> 4.x
Since `4.0.0`, `ignore` will no longer support node < 6, to use `ignore` in node < 6:
```js
var ignore = require('ignore/legacy')
```
****
# Collaborators
- [@whitecolor](https://github.com/whitecolor) *Alex*
- [@SamyPesse](https://github.com/SamyPesse) *Samy Pessé*
- [@azproduction](https://github.com/azproduction) *Mikhail Davydov*
- [@TrySound](https://github.com/TrySound) *Bogdan Chadkin*
- [@JanMattner](https://github.com/JanMattner) *Jan Mattner*
- [@ntwb](https://github.com/ntwb) *Stephen Edgar*
- [@kasperisager](https://github.com/kasperisager) *Kasper Isager*
- [@sandersn](https://github.com/sandersn) *Nathan Shively-Sanders*
interface Ignore {
/**
* Adds a rule rules to the current manager.
* @param {string | Ignore} pattern
* @returns IgnoreBase
*/
add(pattern: string | Ignore): Ignore
/**
* Adds several rules to the current manager.
* @param {string[]} patterns
* @returns IgnoreBase
*/
add(patterns: (string | Ignore)[]): Ignore
/**
* Filters the given array of pathnames, and returns the filtered array.
* NOTICE that each path here should be a relative path to the root of your repository.
* @param paths the array of paths to be filtered.
* @returns The filtered array of paths
*/
filter(paths: string[]): string[]
/**
* Creates a filter function which could filter
* an array of paths with Array.prototype.filter.
*/
createFilter(): (path: string) => boolean
/**
* Returns Boolean whether pathname should be ignored.
* @param {string} pathname a path to check
* @returns boolean
*/
ignores(pathname: string): boolean
}
interface Options {
ignorecase?: boolean
}
/**
* Creates new ignore manager.
*/
declare function ignore(options?: Options): Ignore
export default ignore
// A simple implementation of make-array
function make_array (subject) {
return Array.isArray(subject)
? subject
: [subject]
}
const REGEX_BLANK_LINE = /^\s+$/
const REGEX_LEADING_EXCAPED_EXCLAMATION = /^\\!/
const REGEX_LEADING_EXCAPED_HASH = /^\\#/
const SLASH = '/'
const KEY_IGNORE = typeof Symbol !== 'undefined'
? Symbol.for('node-ignore')
/* istanbul ignore next */
: 'node-ignore'
const define = (object, key, value) =>
Object.defineProperty(object, key, {value})
const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g
// Sanitize the range of a regular expression
// The cases are complicated, see test cases for details
const sanitizeRange = range => range.replace(
REGEX_REGEXP_RANGE,
(match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0)
? match
// Invalid range (out of order) which is ok for gitignore rules but
// fatal for JavaScript regular expression, so eliminate it.
: ''
)
// > If the pattern ends with a slash,
// > it is removed for the purpose of the following description,
// > but it would only find a match with a directory.
// > In other words, foo/ will match a directory foo and paths underneath it,
// > but will not match a regular file or a symbolic link foo
// > (this is consistent with the way how pathspec works in general in Git).
// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
// you could use option `mark: true` with `glob`
// '`foo/`' should not continue with the '`..`'
const DEFAULT_REPLACER_PREFIX = [
// > Trailing spaces are ignored unless they are quoted with backslash ("\")
[
// (a\ ) -> (a )
// (a ) -> (a)
// (a \ ) -> (a )
/\\?\s+$/,
match => match.indexOf('\\') === 0
? ' '
: ''
],
// replace (\ ) with ' '
[
/\\\s/g,
() => ' '
],
// Escape metacharacters
// which is written down by users but means special for regular expressions.
// > There are 12 characters with special meanings:
// > - the backslash \,
// > - the caret ^,
// > - the dollar sign $,
// > - the period or dot .,
// > - the vertical bar or pipe symbol |,
// > - the question mark ?,
// > - the asterisk or star *,
// > - the plus sign +,
// > - the opening parenthesis (,
// > - the closing parenthesis ),
// > - and the opening square bracket [,
// > - the opening curly brace {,
// > These special characters are often called "metacharacters".
[
/[\\^$.|*+(){]/g,
match => `\\${match}`
],
[
// > [abc] matches any character inside the brackets
// > (in this case a, b, or c);
/\[([^\]/]*)($|\])/g,
(match, p1, p2) => p2 === ']'
? `[${sanitizeRange(p1)}]`
: `\\${match}`
],
[
// > a question mark (?) matches a single character
/(?!\\)\?/g,
() => '[^/]'
],
// leading slash
[
// > A leading slash matches the beginning of the pathname.
// > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
// A leading slash matches the beginning of the pathname
/^\//,
() => '^'
],
// replace special metacharacter slash after the leading slash
[
/\//g,
() => '\\/'
],
[
// > A leading "**" followed by a slash means match in all directories.
// > For example, "**/foo" matches file or directory "foo" anywhere,
// > the same as pattern "foo".
// > "**/foo/bar" matches file or directory "bar" anywhere that is directly
// > under directory "foo".
// Notice that the '*'s have been replaced as '\\*'
/^\^*\\\*\\\*\\\//,
// '**/foo' <-> 'foo'
() => '^(?:.*\\/)?'
]
]
const DEFAULT_REPLACER_SUFFIX = [
// starting
[
// there will be no leading '/'
// (which has been replaced by section "leading slash")
// If starts with '**', adding a '^' to the regular expression also works
/^(?=[^^])/,
function startingReplacer () {
return !/\/(?!$)/.test(this)
// > If the pattern does not contain a slash /,
// > Git treats it as a shell glob pattern
// Actually, if there is only a trailing slash,
// git also treats it as a shell glob pattern
? '(?:^|\\/)'
// > Otherwise, Git treats the pattern as a shell glob suitable for
// > consumption by fnmatch(3)
: '^'
}
],
// two globstars
[
// Use lookahead assertions so that we could match more than one `'/**'`
/\\\/\\\*\\\*(?=\\\/|$)/g,
// Zero, one or several directories
// should not use '*', or it will be replaced by the next replacer
// Check if it is not the last `'/**'`
(match, index, str) => index + 6 < str.length
// case: /**/
// > A slash followed by two consecutive asterisks then a slash matches
// > zero or more directories.
// > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
// '/**/'
? '(?:\\/[^\\/]+)*'
// case: /**
// > A trailing `"/**"` matches everything inside.
// #21: everything inside but it should not include the current folder
: '\\/.+'
],
// intermediate wildcards
[
// Never replace escaped '*'
// ignore rule '\*' will match the path '*'
// 'abc.*/' -> go
// 'abc.*' -> skip this rule
/(^|[^\\]+)\\\*(?=.+)/g,
// '*.js' matches '.js'
// '*.js' doesn't match 'abc'
(match, p1) => `${p1}[^\\/]*`
],
// trailing wildcard
[
/(\^|\\\/)?\\\*$/,
(match, p1) => {
const prefix = p1
// '\^':
// '/*' does not match ''
// '/*' does not match everything
// '\\\/':
// 'abc/*' does not match 'abc/'
? `${p1}[^/]+`
// 'a*' matches 'a'
// 'a*' matches 'aa'
: '[^/]*'
return `${prefix}(?=$|\\/$)`
}
],
[
// unescape
/\\\\\\/g,
() => '\\'
]
]
const POSITIVE_REPLACERS = [
...DEFAULT_REPLACER_PREFIX,
// 'f'
// matches
// - /f(end)
// - /f/
// - (start)f(end)
// - (start)f/
// doesn't match
// - oof
// - foo
// pseudo:
// -> (^|/)f(/|$)
// ending
[
// 'js' will not match 'js.'
// 'ab' will not match 'abc'
/(?:[^*/])$/,
// 'js*' will not match 'a.js'
// 'js/' will not match 'a.js'
// 'js' will match 'a.js' and 'a.js/'
match => `${match}(?=$|\\/)`
],
...DEFAULT_REPLACER_SUFFIX
]
const NEGATIVE_REPLACERS = [
...DEFAULT_REPLACER_PREFIX,
// #24, #38
// The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore)
// A negative pattern without a trailing wildcard should not
// re-include the things inside that directory.
// eg:
// ['node_modules/*', '!node_modules']
// should ignore `node_modules/a.js`
[
/(?:[^*])$/,
match => `${match}(?=$|\\/$)`
],
...DEFAULT_REPLACER_SUFFIX
]
// A simple cache, because an ignore rule only has only one certain meaning
const cache = Object.create(null)
// @param {pattern}
const make_regex = (pattern, negative, ignorecase) => {
const r = cache[pattern]
if (r) {
return r
}
const replacers = negative
? NEGATIVE_REPLACERS
: POSITIVE_REPLACERS
const source = replacers.reduce(
(prev, current) => prev.replace(current[0], current[1].bind(pattern)),
pattern
)
return cache[pattern] = ignorecase
? new RegExp(source, 'i')
: new RegExp(source)
}
// > A blank line matches no files, so it can serve as a separator for readability.
const checkPattern = pattern => pattern
&& typeof pattern === 'string'
&& !REGEX_BLANK_LINE.test(pattern)
// > A line starting with # serves as a comment.
&& pattern.indexOf('#') !== 0
const createRule = (pattern, ignorecase) => {
const origin = pattern
let negative = false
// > An optional prefix "!" which negates the pattern;
if (pattern.indexOf('!') === 0) {
negative = true
pattern = pattern.substr(1)
}
pattern = pattern
// > Put a backslash ("\") in front of the first "!" for patterns that
// > begin with a literal "!", for example, `"\!important!.txt"`.
.replace(REGEX_LEADING_EXCAPED_EXCLAMATION, '!')
// > Put a backslash ("\") in front of the first hash for patterns that
// > begin with a hash.
.replace(REGEX_LEADING_EXCAPED_HASH, '#')
const regex = make_regex(pattern, negative, ignorecase)
return {
origin,
pattern,
negative,
regex
}
}
class IgnoreBase {
constructor ({
ignorecase = true
} = {}) {
this._rules = []
this._ignorecase = ignorecase
define(this, KEY_IGNORE, true)
this._initCache()
}
_initCache () {
this._cache = Object.create(null)
}
// @param {Array.<string>|string|Ignore} pattern
add (pattern) {
this._added = false
if (typeof pattern === 'string') {
pattern = pattern.split(/\r?\n/g)
}
make_array(pattern).forEach(this._addPattern, this)
// Some rules have just added to the ignore,
// making the behavior changed.
if (this._added) {
this._initCache()
}
return this
}
// legacy
addPattern (pattern) {
return this.add(pattern)
}
_addPattern (pattern) {
// #32
if (pattern && pattern[KEY_IGNORE]) {
this._rules = this._rules.concat(pattern._rules)
this._added = true
return
}
if (checkPattern(pattern)) {
const rule = createRule(pattern, this._ignorecase)
this._added = true
this._rules.push(rule)
}
}
filter (paths) {
return make_array(paths).filter(path => this._filter(path))
}
createFilter () {
return path => this._filter(path)
}
ignores (path) {
return !this._filter(path)
}
// @returns `Boolean` true if the `path` is NOT ignored
_filter (path, slices) {
if (!path) {
return false
}
if (path in this._cache) {
return this._cache[path]
}
if (!slices) {
// path/to/a.js
// ['path', 'to', 'a.js']
slices = path.split(SLASH)
}
slices.pop()
return this._cache[path] = slices.length
// > It is not possible to re-include a file if a parent directory of
// > that file is excluded.
// If the path contains a parent directory, check the parent first
? this._filter(slices.join(SLASH) + SLASH, slices)
&& this._test(path)
// Or only test the path
: this._test(path)
}
// @returns {Boolean} true if a file is NOT ignored
_test (path) {
// Explicitly define variable type by setting matched to `0`
let matched = 0
this._rules.forEach(rule => {
// if matched = true, then we only test negative rules
// if matched = false, then we test non-negative rules
if (!(matched ^ rule.negative)) {
matched = rule.negative ^ rule.regex.test(path)
}
})
return !matched
}
}
// Windows
// --------------------------------------------------------------
/* istanbul ignore if */
if (
// Detect `process` so that it can run in browsers.
typeof process !== 'undefined'
&& (
process.env && process.env.IGNORE_TEST_WIN32
|| process.platform === 'win32'
)
) {
const filter = IgnoreBase.prototype._filter
/* eslint no-control-regex: "off" */
const make_posix = str => /^\\\\\?\\/.test(str)
|| /[^\x00-\x80]+/.test(str)
? str
: str.replace(/\\/g, '/')
IgnoreBase.prototype._filter = function filterWin32 (path, slices) {
path = make_posix(path)
return filter.call(this, path, slices)
}
}
module.exports = options => new IgnoreBase(options)
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// A simple implementation of make-array
function make_array(subject) {
return Array.isArray(subject) ? subject : [subject];
}
var REGEX_BLANK_LINE = /^\s+$/;
var REGEX_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
var REGEX_LEADING_EXCAPED_HASH = /^\\#/;
var SLASH = '/';
var KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore')
/* istanbul ignore next */
: 'node-ignore';
var define = function define(object, key, value) {
return Object.defineProperty(object, key, { value });
};
var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
// Sanitize the range of a regular expression
// The cases are complicated, see test cases for details
var sanitizeRange = function sanitizeRange(range) {
return range.replace(REGEX_REGEXP_RANGE, function (match, from, to) {
return from.charCodeAt(0) <= to.charCodeAt(0) ? match
// Invalid range (out of order) which is ok for gitignore rules but
// fatal for JavaScript regular expression, so eliminate it.
: '';
});
};
// > If the pattern ends with a slash,
// > it is removed for the purpose of the following description,
// > but it would only find a match with a directory.
// > In other words, foo/ will match a directory foo and paths underneath it,
// > but will not match a regular file or a symbolic link foo
// > (this is consistent with the way how pathspec works in general in Git).
// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
// you could use option `mark: true` with `glob`
// '`foo/`' should not continue with the '`..`'
var DEFAULT_REPLACER_PREFIX = [
// > Trailing spaces are ignored unless they are quoted with backslash ("\")
[
// (a\ ) -> (a )
// (a ) -> (a)
// (a \ ) -> (a )
/\\?\s+$/, function (match) {
return match.indexOf('\\') === 0 ? ' ' : '';
}],
// replace (\ ) with ' '
[/\\\s/g, function () {
return ' ';
}],
// Escape metacharacters
// which is written down by users but means special for regular expressions.
// > There are 12 characters with special meanings:
// > - the backslash \,
// > - the caret ^,
// > - the dollar sign $,
// > - the period or dot .,
// > - the vertical bar or pipe symbol |,
// > - the question mark ?,
// > - the asterisk or star *,
// > - the plus sign +,
// > - the opening parenthesis (,
// > - the closing parenthesis ),
// > - and the opening square bracket [,
// > - the opening curly brace {,
// > These special characters are often called "metacharacters".
[/[\\^$.|*+(){]/g, function (match) {
return `\\${match}`;
}], [
// > [abc] matches any character inside the brackets
// > (in this case a, b, or c);
/\[([^\]/]*)($|\])/g, function (match, p1, p2) {
return p2 === ']' ? `[${sanitizeRange(p1)}]` : `\\${match}`;
}], [
// > a question mark (?) matches a single character
/(?!\\)\?/g, function () {
return '[^/]';
}],
// leading slash
[
// > A leading slash matches the beginning of the pathname.
// > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
// A leading slash matches the beginning of the pathname
/^\//, function () {
return '^';
}],
// replace special metacharacter slash after the leading slash
[/\//g, function () {
return '\\/';
}], [
// > A leading "**" followed by a slash means match in all directories.
// > For example, "**/foo" matches file or directory "foo" anywhere,
// > the same as pattern "foo".
// > "**/foo/bar" matches file or directory "bar" anywhere that is directly
// > under directory "foo".
// Notice that the '*'s have been replaced as '\\*'
/^\^*\\\*\\\*\\\//,
// '**/foo' <-> 'foo'
function () {
return '^(?:.*\\/)?';
}]];
var DEFAULT_REPLACER_SUFFIX = [
// starting
[
// there will be no leading '/'
// (which has been replaced by section "leading slash")
// If starts with '**', adding a '^' to the regular expression also works
/^(?=[^^])/, function startingReplacer() {
return !/\/(?!$)/.test(this)
// > If the pattern does not contain a slash /,
// > Git treats it as a shell glob pattern
// Actually, if there is only a trailing slash,
// git also treats it as a shell glob pattern
? '(?:^|\\/)'
// > Otherwise, Git treats the pattern as a shell glob suitable for
// > consumption by fnmatch(3)
: '^';
}],
// two globstars
[
// Use lookahead assertions so that we could match more than one `'/**'`
/\\\/\\\*\\\*(?=\\\/|$)/g,
// Zero, one or several directories
// should not use '*', or it will be replaced by the next replacer
// Check if it is not the last `'/**'`
function (match, index, str) {
return index + 6 < str.length
// case: /**/
// > A slash followed by two consecutive asterisks then a slash matches
// > zero or more directories.
// > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
// '/**/'
? '(?:\\/[^\\/]+)*'
// case: /**
// > A trailing `"/**"` matches everything inside.
// #21: everything inside but it should not include the current folder
: '\\/.+';
}],
// intermediate wildcards
[
// Never replace escaped '*'
// ignore rule '\*' will match the path '*'
// 'abc.*/' -> go
// 'abc.*' -> skip this rule
/(^|[^\\]+)\\\*(?=.+)/g,
// '*.js' matches '.js'
// '*.js' doesn't match 'abc'
function (match, p1) {
return `${p1}[^\\/]*`;
}],
// trailing wildcard
[/(\^|\\\/)?\\\*$/, function (match, p1) {
var prefix = p1
// '\^':
// '/*' does not match ''
// '/*' does not match everything
// '\\\/':
// 'abc/*' does not match 'abc/'
? `${p1}[^/]+`
// 'a*' matches 'a'
// 'a*' matches 'aa'
: '[^/]*';
return `${prefix}(?=$|\\/$)`;
}], [
// unescape
/\\\\\\/g, function () {
return '\\';
}]];
var POSITIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [
// 'f'
// matches
// - /f(end)
// - /f/
// - (start)f(end)
// - (start)f/
// doesn't match
// - oof
// - foo
// pseudo:
// -> (^|/)f(/|$)
// ending
[
// 'js' will not match 'js.'
// 'ab' will not match 'abc'
/(?:[^*/])$/,
// 'js*' will not match 'a.js'
// 'js/' will not match 'a.js'
// 'js' will match 'a.js' and 'a.js/'
function (match) {
return `${match}(?=$|\\/)`;
}]], DEFAULT_REPLACER_SUFFIX);
var NEGATIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [
// #24, #38
// The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore)
// A negative pattern without a trailing wildcard should not
// re-include the things inside that directory.
// eg:
// ['node_modules/*', '!node_modules']
// should ignore `node_modules/a.js`
[/(?:[^*])$/, function (match) {
return `${match}(?=$|\\/$)`;
}]], DEFAULT_REPLACER_SUFFIX);
// A simple cache, because an ignore rule only has only one certain meaning
var cache = Object.create(null);
// @param {pattern}
var make_regex = function make_regex(pattern, negative, ignorecase) {
var r = cache[pattern];
if (r) {
return r;
}
var replacers = negative ? NEGATIVE_REPLACERS : POSITIVE_REPLACERS;
var source = replacers.reduce(function (prev, current) {
return prev.replace(current[0], current[1].bind(pattern));
}, pattern);
return cache[pattern] = ignorecase ? new RegExp(source, 'i') : new RegExp(source);
};
// > A blank line matches no files, so it can serve as a separator for readability.
var checkPattern = function checkPattern(pattern) {
return pattern && typeof pattern === 'string' && !REGEX_BLANK_LINE.test(pattern)
// > A line starting with # serves as a comment.
&& pattern.indexOf('#') !== 0;
};
var createRule = function createRule(pattern, ignorecase) {
var origin = pattern;
var negative = false;
// > An optional prefix "!" which negates the pattern;
if (pattern.indexOf('!') === 0) {
negative = true;
pattern = pattern.substr(1);
}
pattern = pattern
// > Put a backslash ("\") in front of the first "!" for patterns that
// > begin with a literal "!", for example, `"\!important!.txt"`.
.replace(REGEX_LEADING_EXCAPED_EXCLAMATION, '!')
// > Put a backslash ("\") in front of the first hash for patterns that
// > begin with a hash.
.replace(REGEX_LEADING_EXCAPED_HASH, '#');
var regex = make_regex(pattern, negative, ignorecase);
return {
origin,
pattern,
negative,
regex
};
};
var IgnoreBase = function () {
function IgnoreBase() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$ignorecase = _ref.ignorecase,
ignorecase = _ref$ignorecase === undefined ? true : _ref$ignorecase;
_classCallCheck(this, IgnoreBase);
this._rules = [];
this._ignorecase = ignorecase;
define(this, KEY_IGNORE, true);
this._initCache();
}
_createClass(IgnoreBase, [{
key: '_initCache',
value: function _initCache() {
this._cache = Object.create(null);
}
// @param {Array.<string>|string|Ignore} pattern
}, {
key: 'add',
value: function add(pattern) {
this._added = false;
if (typeof pattern === 'string') {
pattern = pattern.split(/\r?\n/g);
}
make_array(pattern).forEach(this._addPattern, this);
// Some rules have just added to the ignore,
// making the behavior changed.
if (this._added) {
this._initCache();
}
return this;
}
// legacy
}, {
key: 'addPattern',
value: function addPattern(pattern) {
return this.add(pattern);
}
}, {
key: '_addPattern',
value: function _addPattern(pattern) {
// #32
if (pattern && pattern[KEY_IGNORE]) {
this._rules = this._rules.concat(pattern._rules);
this._added = true;
return;
}
if (checkPattern(pattern)) {
var rule = createRule(pattern, this._ignorecase);
this._added = true;
this._rules.push(rule);
}
}
}, {
key: 'filter',
value: function filter(paths) {
var _this = this;
return make_array(paths).filter(function (path) {
return _this._filter(path);
});
}
}, {
key: 'createFilter',
value: function createFilter() {
var _this2 = this;
return function (path) {
return _this2._filter(path);
};
}
}, {
key: 'ignores',
value: function ignores(path) {
return !this._filter(path);
}
// @returns `Boolean` true if the `path` is NOT ignored
}, {
key: '_filter',
value: function _filter(path, slices) {
if (!path) {
return false;
}
if (path in this._cache) {
return this._cache[path];
}
if (!slices) {
// path/to/a.js
// ['path', 'to', 'a.js']
slices = path.split(SLASH);
}
slices.pop();
return this._cache[path] = slices.length
// > It is not possible to re-include a file if a parent directory of
// > that file is excluded.
// If the path contains a parent directory, check the parent first
? this._filter(slices.join(SLASH) + SLASH, slices) && this._test(path)
// Or only test the path
: this._test(path);
}
// @returns {Boolean} true if a file is NOT ignored
}, {
key: '_test',
value: function _test(path) {
// Explicitly define variable type by setting matched to `0`
var matched = 0;
this._rules.forEach(function (rule) {
// if matched = true, then we only test negative rules
// if matched = false, then we test non-negative rules
if (!(matched ^ rule.negative)) {
matched = rule.negative ^ rule.regex.test(path);
}
});
return !matched;
}
}]);
return IgnoreBase;
}();
// Windows
// --------------------------------------------------------------
/* istanbul ignore if */
if (
// Detect `process` so that it can run in browsers.
typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) {
var filter = IgnoreBase.prototype._filter;
/* eslint no-control-regex: "off" */
var make_posix = function make_posix(str) {
return (/^\\\\\?\\/.test(str) || /[^\x00-\x80]+/.test(str) ? str : str.replace(/\\/g, '/')
);
};
IgnoreBase.prototype._filter = function filterWin32(path, slices) {
path = make_posix(path);
return filter.call(this, path, slices);
};
}
module.exports = function (options) {
return new IgnoreBase(options);
};
{
"name": "ignore",
"version": "4.0.6",
"description": "Ignore is a manager and filter for .gitignore rules.",
"files": [
"legacy.js",
"index.js",
"index.d.ts",
"LICENSE-MIT"
],
"scripts": {
"prepublish": "npm run build",
"build": "babel -o legacy.js index.js",
"test:lint": "eslint .",
"test:tsc": "tsc ./test/ts/simple.ts",
"test:git": "tap test/git-check-ignore.js",
"test:ignore": "tap test/ignore.js --coverage",
"test-no-cov": "npm run test:lint && npm run test:tsc && tap test/*.js --coverage",
"test": "npm run test-no-cov",
"posttest": "tap --coverage-report=html && codecov"
},
"repository": {
"type": "git",
"url": "git@github.com:kaelzhang/node-ignore.git"
},
"keywords": [
"ignore",
".gitignore",
"gitignore",
"npmignore",
"rules",
"manager",
"filter",
"regexp",
"regex",
"fnmatch",
"glob",
"asterisks",
"regular-expression"
],
"author": "kael",
"license": "MIT",
"bugs": {
"url": "https://github.com/kaelzhang/node-ignore/issues"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.7.0",
"codecov": "^3.0.4",
"eslint": "^5.3.0",
"eslint-config-ostai": "^1.3.2",
"eslint-plugin-import": "^2.13.0",
"mkdirp": "^0.5.1",
"pre-suf": "^1.1.0",
"rimraf": "^2.6.2",
"spawn-sync": "^2.0.0",
"tap": "^12.0.1",
"tmp": "0.0.33",
"typescript": "^3.0.1"
},
"engines": {
"node": ">= 4"
}
}
// Types that are compatible with all supported TypeScript versions.
// It's shared between all TypeScript version-specific definitions.
// Basic
export * from './source/basic';
// Utilities
export {Except} from './source/except';
export {Mutable} from './source/mutable';
export {Merge} from './source/merge';
export {MergeExclusive} from './source/merge-exclusive';
export {RequireAtLeastOne} from './source/require-at-least-one';
export {RequireExactlyOne} from './source/require-exactly-one';
export {PartialDeep} from './source/partial-deep';
export {ReadonlyDeep} from './source/readonly-deep';
export {LiteralUnion} from './source/literal-union';
export {Promisable} from './source/promisable';
export {Opaque} from './source/opaque';
export {SetOptional} from './source/set-optional';
export {SetRequired} from './source/set-required';
export {ValueOf} from './source/value-of';
export {PromiseValue} from './source/promise-value';
export {AsyncReturnType} from './source/async-return-type';
export {ConditionalExcept} from './source/conditional-except';
export {ConditionalKeys} from './source/conditional-keys';
export {ConditionalPick} from './source/conditional-pick';
export {UnionToIntersection} from './source/union-to-intersection';
export {Stringified} from './source/stringified';
export {FixedLengthArray} from './source/fixed-length-array';
export {IterableElement} from './source/iterable-element';
export {Entry} from './source/entry';
export {Entries} from './source/entries';
export {SetReturnType} from './source/set-return-type';
export {Asyncify} from './source/asyncify';
// Miscellaneous
export {PackageJson} from './source/package-json';
export {TsConfigJson} from './source/tsconfig-json';
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment