mirror of
https://github.com/nodejs/node.git
synced 2026-11-27 17:52:27 -05:00
tools: update ESLint to 7.0.0-alpha.0
Update ESLint to 7.0.0-alpha.0 PR-URL: https://github.com/nodejs/node/pull/31400 Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com> Reviewed-By: Rich Trott <rtrott@gmail.com>
This commit is contained in:
1 parent
8fe70e88fe
commit
394fa1f356
336 files changed
+10384
-16071
No files matched your search
+2
-2
@@ -39,7 +39,7 @@ ESLint is a tool for identifying and reporting on patterns found in ECMAScript/J
|
||||
|
||||
## <a name="installation-and-usage"></a>Installation and Usage
|
||||
|
||||
Prerequisites: [Node.js](https://nodejs.org/) (`^8.10.0`, `^10.13.0`, or `>=11.10.1`) built with SSL support. (If you are using an official Node.js distribution, SSL is always built in.)
|
||||
Prerequisites: [Node.js](https://nodejs.org/) (`^10.12.0`, or `>=12.0.0`) built with SSL support. (If you are using an official Node.js distribution, SSL is always built in.)
|
||||
|
||||
You can install ESLint using npm:
|
||||
|
||||
@@ -264,7 +264,7 @@ The following companies, organizations, and individuals support ESLint's ongoing
|
||||
<h3>Gold Sponsors</h3>
|
||||
<p><a href="https://www.shopify.com"><img src="https://images.opencollective.com/shopify/eeb91aa/logo.png" alt="Shopify" height="96"></a> <a href="http://engineering.salesforce.com"><img src="https://images.opencollective.com/salesforce/ca8f997/logo.png" alt="Salesforce" height="96"></a> <a href="https://badoo.com/team?utm_source=eslint"><img src="https://images.opencollective.com/badoo/2826a3b/logo.png" alt="Badoo" height="96"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="96"></a> <a href="https://opensource.facebook.com"><img src="https://images.opencollective.com/fbopensource/fbb8a5b/logo.png" alt="Facebook Open Source" height="96"></a></p><h3>Silver Sponsors</h3>
|
||||
<p><a href="https://www.ampproject.org/"><img src="https://images.opencollective.com/amp/c8a3b25/logo.png" alt="AMP Project" height="64"></a></p><h3>Bronze Sponsors</h3>
|
||||
<p><a href="https://uxplanet.org/top-ui-ux-design-agencies-user-experience-firms-8c54697e290"><img src="https://images.opencollective.com/ui-ux-design-agencies/cae5dfe/logo.png" alt="UI UX Design Agencies" height="32"></a> <a href="https://medium.com/@niksundin/best-web-design-companies-1872e445775f"><img src="https://images.opencollective.com/top-web-design-agencies/d92d747/logo.png" alt="Top Web Design Agencies" height="32"></a> <a href="https://www.bugsnag.com/platforms?utm_source=Open Collective&utm_medium=Website&utm_content=open-source&utm_campaign=2019-community&utm_term="><img src="https://images.opencollective.com/bugsnag-stability-monitoring/c2cef36/logo.png" alt="Bugsnag Stability Monitoring" height="32"></a> <a href="https://www.crosswordsolver.com"><img src="https://images.opencollective.com/crosswordsolver/d4481d6/logo.png" alt="Crosswordsolver" height="32"></a> <a href="https://www.codacy.com/?utm_source=eslint&utm_medium=cpm&utm_campaign=eslint-sponsorship"><img src="https://images.opencollective.com/codacy/ed22716/logo.png" alt="Codacy" height="32"></a> <a href="https://mixpanel.com"><img src="https://images.opencollective.com/mixpanel/cd682f7/logo.png" alt="Mixpanel" height="32"></a> <a href="https://www.vpsserver.com"><img src="https://images.opencollective.com/vpsservercom/logo.png" alt="VPS Server" height="32"></a> <a href="https://icons8.com"><img src="https://images.opencollective.com/icons8/0b37d14/logo.png" alt="Free Icons by Icons8" height="32"></a> <a href="https://edubirdie.com/"><img src="https://images.opencollective.com/edubirdie2/b1d51ab/logo.png" alt="EduBirdie" height="32"></a> <a href="https://clay.global"><img src="https://images.opencollective.com/clayglobal/2468f34/logo.png" alt="clay" height="32"></a> <a href="https://discordapp.com"><img src="https://images.opencollective.com/discordapp/7e3d9a9/logo.png" alt="Discord" height="32"></a> <a href="https://themeisle.com"><img src="https://images.opencollective.com/themeisle/d5592fe/logo.png" alt="ThemeIsle" height="32"></a> <a href="https://tekhattan.com"><img src="https://images.opencollective.com/tekhattan/bc73c28/logo.png" alt="TekHattan" height="32"></a> <a href="https://www.marfeel.com/"><img src="https://images.opencollective.com/marfeel/4b88e30/logo.png" alt="Marfeel" height="32"></a> <a href="http://www.firesticktricks.com"><img src="https://images.opencollective.com/fire-stick-tricks/b8fbe2c/logo.png" alt="Fire Stick Tricks" height="32"></a> <a href="https://jsheroes.io/"><img src="https://images.opencollective.com/jsheroes1/9fedf0b/logo.png" alt="JSHeroes " height="32"></a></p>
|
||||
<p><a href="https://icons8.com"><img src="https://images.opencollective.com/icons8/0b37d14/logo.png" alt="Free Icons by Icons8" height="32"></a> <a href="https://www.bonus.com.de/freispiele"><img src="https://images.opencollective.com/bonusfinder-deutschland/646169e/logo.png" alt="BonusFinder Deutschland" height="32"></a> <a href="https://edubirdie.com/"><img src="https://images.opencollective.com/edubirdie2/b1d51ab/logo.png" alt="EduBirdie" height="32"></a> <a href="https://www.bugsnag.com/platforms?utm_source=Open Collective&utm_medium=Website&utm_content=open-source&utm_campaign=2019-community&utm_term="><img src="https://images.opencollective.com/bugsnag-stability-monitoring/c2cef36/logo.png" alt="Bugsnag Stability Monitoring" height="32"></a> <a href="https://www.crosswordsolver.com"><img src="https://images.opencollective.com/crosswordsolver/d4481d6/logo.png" alt="Crosswordsolver" height="32"></a> <a href="https://www.codacy.com/?utm_source=eslint&utm_medium=cpm&utm_campaign=eslint-sponsorship"><img src="https://images.opencollective.com/codacy/ed22716/logo.png" alt="Codacy" height="32"></a> <a href="https://mixpanel.com"><img src="https://images.opencollective.com/mixpanel/cd682f7/logo.png" alt="Mixpanel" height="32"></a> <a href="https://www.vpsserver.com"><img src="https://images.opencollective.com/vpsservercom/logo.png" alt="VPS Server" height="32"></a> <a href="https://medium.com/@niksundin/best-web-design-companies-1872e445775f"><img src="https://images.opencollective.com/top-web-design-agencies/d92d747/logo.png" alt="Top Web Design Agencies" height="32"></a> <a href="https://uxplanet.org/top-ui-ux-design-agencies-user-experience-firms-8c54697e290"><img src="https://images.opencollective.com/ui-ux-design-agencies/cae5dfe/logo.png" alt="UI UX Design Agencies" height="32"></a> <a href="https://clay.global"><img src="https://images.opencollective.com/clayglobal/2468f34/logo.png" alt="clay" height="32"></a> <a href="https://discordapp.com"><img src="https://images.opencollective.com/discordapp/7e3d9a9/logo.png" alt="Discord" height="32"></a> <a href="https://themeisle.com"><img src="https://images.opencollective.com/themeisle/d5592fe/logo.png" alt="ThemeIsle" height="32"></a> <a href="https://tekhattan.com"><img src="https://images.opencollective.com/tekhattan/bc73c28/logo.png" alt="TekHattan" height="32"></a> <a href="https://www.marfeel.com/"><img src="https://images.opencollective.com/marfeel/4b88e30/logo.png" alt="Marfeel" height="32"></a> <a href="http://www.firesticktricks.com"><img src="https://images.opencollective.com/fire-stick-tricks/b8fbe2c/logo.png" alt="Fire Stick Tricks" height="32"></a> <a href="https://jsheroes.io/"><img src="https://images.opencollective.com/jsheroes1/9fedf0b/logo.png" alt="JSHeroes " height="32"></a></p>
|
||||
<!--sponsorsend-->
|
||||
|
||||
## <a name="technology-sponsors"></a>Technology Sponsors
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ module.exports = {
|
||||
useEslintrc: true,
|
||||
envs: [],
|
||||
globals: [],
|
||||
extensions: [".js"],
|
||||
extensions: null,
|
||||
ignore: true,
|
||||
ignorePath: void 0,
|
||||
cache: false,
|
||||
|
||||
+39
-6
@@ -26,6 +26,7 @@
|
||||
const os = require("os");
|
||||
const path = require("path");
|
||||
const { validateConfigArray } = require("../shared/config-validator");
|
||||
const { emitDeprecationWarning } = require("../shared/deprecation-warnings");
|
||||
const { ConfigArrayFactory } = require("./config-array-factory");
|
||||
const { ConfigArray, ConfigDependency, IgnorePattern } = require("./config-array");
|
||||
const loadRules = require("./load-rules");
|
||||
@@ -105,6 +106,7 @@ function createBaseConfigArray({
|
||||
*/
|
||||
if (rulePaths && rulePaths.length > 0) {
|
||||
baseConfigArray.push({
|
||||
type: "config",
|
||||
name: "--rulesdir",
|
||||
filePath: "",
|
||||
plugins: {
|
||||
@@ -290,10 +292,11 @@ class CascadingConfigArrayFactory {
|
||||
/**
|
||||
* Load and normalize config files from the ancestor directories.
|
||||
* @param {string} directoryPath The path to a leaf directory.
|
||||
* @param {boolean} configsExistInSubdirs `true` if configurations exist in subdirectories.
|
||||
* @returns {ConfigArray} The loaded config.
|
||||
* @private
|
||||
*/
|
||||
_loadConfigInAncestors(directoryPath) {
|
||||
_loadConfigInAncestors(directoryPath, configsExistInSubdirs = false) {
|
||||
const {
|
||||
baseConfigArray,
|
||||
configArrayFactory,
|
||||
@@ -320,6 +323,16 @@ class CascadingConfigArrayFactory {
|
||||
// Consider this is root.
|
||||
if (directoryPath === homePath && cwd !== homePath) {
|
||||
debug("Stop traversing because of considered root.");
|
||||
if (configsExistInSubdirs) {
|
||||
const filePath = ConfigArrayFactory.getPathToConfigFileInDirectory(directoryPath);
|
||||
|
||||
if (filePath) {
|
||||
emitDeprecationWarning(
|
||||
filePath,
|
||||
"ESLINT_PERSONAL_CONFIG_SUPPRESS"
|
||||
);
|
||||
}
|
||||
}
|
||||
return this._cacheConfig(directoryPath, baseConfigArray);
|
||||
}
|
||||
|
||||
@@ -344,7 +357,10 @@ class CascadingConfigArrayFactory {
|
||||
// Load from the ancestors and merge it.
|
||||
const parentPath = path.dirname(directoryPath);
|
||||
const parentConfigArray = parentPath && parentPath !== directoryPath
|
||||
? this._loadConfigInAncestors(parentPath)
|
||||
? this._loadConfigInAncestors(
|
||||
parentPath,
|
||||
configsExistInSubdirs || configArray.length > 0
|
||||
)
|
||||
: baseConfigArray;
|
||||
|
||||
if (configArray.length > 0) {
|
||||
@@ -400,12 +416,29 @@ class CascadingConfigArrayFactory {
|
||||
configArray.every(c => !c.filePath) &&
|
||||
cliConfigArray.every(c => !c.filePath) // `--config` option can be a file.
|
||||
) {
|
||||
debug("Loading the config file of the home directory.");
|
||||
const homePath = os.homedir();
|
||||
|
||||
finalConfigArray = configArrayFactory.loadInDirectory(
|
||||
os.homedir(),
|
||||
{ name: "PersonalConfig", parent: finalConfigArray }
|
||||
debug("Loading the config file of the home directory:", homePath);
|
||||
|
||||
const personalConfigArray = configArrayFactory.loadInDirectory(
|
||||
homePath,
|
||||
{ name: "PersonalConfig" }
|
||||
);
|
||||
|
||||
if (
|
||||
personalConfigArray.length > 0 &&
|
||||
!directoryPath.startsWith(homePath)
|
||||
) {
|
||||
const lastElement =
|
||||
personalConfigArray[personalConfigArray.length - 1];
|
||||
|
||||
emitDeprecationWarning(
|
||||
lastElement.filePath,
|
||||
"ESLINT_PERSONAL_CONFIG_LOAD"
|
||||
);
|
||||
}
|
||||
|
||||
finalConfigArray = finalConfigArray.concat(personalConfigArray);
|
||||
}
|
||||
|
||||
// Apply CLI options.
|
||||
|
||||
+7
-9
@@ -57,7 +57,7 @@ const validFixTypes = new Set(["problem", "suggestion", "layout"]);
|
||||
* @property {string} configFile The configuration file to use.
|
||||
* @property {string} cwd The value to use for the current working directory.
|
||||
* @property {string[]} envs An array of environments to load.
|
||||
* @property {string[]} extensions An array of file extensions to check.
|
||||
* @property {string[]|null} extensions An array of file extensions to check.
|
||||
* @property {boolean|Function} fix Execute in autofix mode. If a function, should return a boolean.
|
||||
* @property {string[]} fixTypes Array of rule types to apply fixes for.
|
||||
* @property {string[]} globals An array of global variables to declare.
|
||||
@@ -201,7 +201,7 @@ function calculateStatsPerRun(results) {
|
||||
* @param {boolean} config.fix If `true` then it does fix.
|
||||
* @param {boolean} config.allowInlineConfig If `true` then it uses directive comments.
|
||||
* @param {boolean} config.reportUnusedDisableDirectives If `true` then it reports unused `eslint-disable` comments.
|
||||
* @param {RegExp} config.extensionRegExp The `RegExp` object that tests if a file path has the allowed file extensions.
|
||||
* @param {FileEnumerator} config.fileEnumerator The file enumerator to check if a path is a target or not.
|
||||
* @param {Linter} config.linter The linter instance to verify.
|
||||
* @returns {LintResult} The result of linting.
|
||||
* @private
|
||||
@@ -214,7 +214,7 @@ function verifyText({
|
||||
fix,
|
||||
allowInlineConfig,
|
||||
reportUnusedDisableDirectives,
|
||||
extensionRegExp,
|
||||
fileEnumerator,
|
||||
linter
|
||||
}) {
|
||||
const filePath = providedFilePath || "<text>";
|
||||
@@ -238,13 +238,11 @@ function verifyText({
|
||||
|
||||
/**
|
||||
* Check if the linter should adopt a given code block or not.
|
||||
* Currently, the linter adopts code blocks if the name matches `--ext` option.
|
||||
* In the future, `overrides` in the configuration would affect the adoption (https://github.com/eslint/rfcs/pull/20).
|
||||
* @param {string} blockFilename The virtual filename of a code block.
|
||||
* @returns {boolean} `true` if the linter should adopt the code block.
|
||||
*/
|
||||
filterCodeBlock(blockFilename) {
|
||||
return extensionRegExp.test(blockFilename);
|
||||
return fileEnumerator.isTargetPath(blockFilename);
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -704,7 +702,7 @@ class CLIEngine {
|
||||
return patterns.filter(Boolean);
|
||||
}
|
||||
|
||||
const extensions = options.extensions.map(ext => ext.replace(/^\./u, ""));
|
||||
const extensions = (options.extensions || [".js"]).map(ext => ext.replace(/^\./u, ""));
|
||||
const dirSuffix = `/**/*.{${extensions.join(",")}}`;
|
||||
|
||||
return patterns.filter(Boolean).map(pathname => {
|
||||
@@ -803,7 +801,7 @@ class CLIEngine {
|
||||
fix,
|
||||
allowInlineConfig,
|
||||
reportUnusedDisableDirectives,
|
||||
extensionRegExp: fileEnumerator.extensionRegExp,
|
||||
fileEnumerator,
|
||||
linter
|
||||
});
|
||||
|
||||
@@ -891,7 +889,7 @@ class CLIEngine {
|
||||
fix,
|
||||
allowInlineConfig,
|
||||
reportUnusedDisableDirectives,
|
||||
extensionRegExp: fileEnumerator.extensionRegExp,
|
||||
fileEnumerator,
|
||||
linter
|
||||
}));
|
||||
}
|
||||
|
||||
+27
-1
@@ -436,6 +436,29 @@ class ConfigArrayFactory {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a config file on a given directory exists or not.
|
||||
* @param {string} directoryPath The path to a directory.
|
||||
* @returns {string | null} The path to the found config file. If not found then null.
|
||||
*/
|
||||
static getPathToConfigFileInDirectory(directoryPath) {
|
||||
for (const filename of configFilenames) {
|
||||
const filePath = path.join(directoryPath, filename);
|
||||
|
||||
if (fs.existsSync(filePath)) {
|
||||
if (filename === "package.json") {
|
||||
try {
|
||||
loadPackageJSONConfigFile(filePath);
|
||||
return filePath;
|
||||
} catch (error) { /* ignore */ }
|
||||
} else {
|
||||
return filePath;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load `.eslintignore` file.
|
||||
* @param {string} filePath The path to a `.eslintignore` file to load.
|
||||
@@ -542,7 +565,7 @@ class ConfigArrayFactory {
|
||||
*/
|
||||
*_normalizeESLintIgnoreData(ignorePatterns, filePath, name) {
|
||||
const elements = this._normalizeObjectConfigData(
|
||||
{ ignorePatterns },
|
||||
{ type: "ignore", ignorePatterns },
|
||||
filePath,
|
||||
name
|
||||
);
|
||||
@@ -644,6 +667,7 @@ class ConfigArrayFactory {
|
||||
root,
|
||||
rules,
|
||||
settings,
|
||||
type = "config",
|
||||
overrides: overrideList = []
|
||||
},
|
||||
filePath,
|
||||
@@ -675,6 +699,7 @@ class ConfigArrayFactory {
|
||||
yield {
|
||||
|
||||
// Debug information.
|
||||
type,
|
||||
name,
|
||||
filePath,
|
||||
|
||||
@@ -1024,6 +1049,7 @@ class ConfigArrayFactory {
|
||||
if (processorId.startsWith(".")) {
|
||||
yield* this._normalizeObjectConfigData(
|
||||
{
|
||||
type: "implicit-processor",
|
||||
files: [`*${processorId}`],
|
||||
processor: `${pluginId}/${processorId}`
|
||||
},
|
||||
|
||||
+19
@@ -454,6 +454,25 @@ class ConfigArray extends Array {
|
||||
|
||||
return cache.get(cacheKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a given path is an additional lint target.
|
||||
* @param {string} filePath The absolute path to the target file.
|
||||
* @returns {boolean} `true` if the file is an additional lint target.
|
||||
*/
|
||||
isAdditionalTargetPath(filePath) {
|
||||
for (const { criteria, type } of this) {
|
||||
if (
|
||||
type === "config" &&
|
||||
criteria &&
|
||||
!criteria.endsWithWildcard &&
|
||||
criteria.test(filePath)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const exportObject = {
|
||||
|
||||
+36
-8
@@ -96,14 +96,22 @@ class OverrideTester {
|
||||
static create(files, excludedFiles, basePath) {
|
||||
const includePatterns = normalizePatterns(files);
|
||||
const excludePatterns = normalizePatterns(excludedFiles);
|
||||
const allPatterns = includePatterns.concat(excludePatterns);
|
||||
let endsWithWildcard = false;
|
||||
|
||||
if (allPatterns.length === 0) {
|
||||
if (includePatterns.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Rejects absolute paths or relative paths to parents.
|
||||
for (const pattern of allPatterns) {
|
||||
for (const pattern of includePatterns) {
|
||||
if (path.isAbsolute(pattern) || pattern.includes("..")) {
|
||||
throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);
|
||||
}
|
||||
if (pattern.endsWith("*")) {
|
||||
endsWithWildcard = true;
|
||||
}
|
||||
}
|
||||
for (const pattern of excludePatterns) {
|
||||
if (path.isAbsolute(pattern) || pattern.includes("..")) {
|
||||
throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);
|
||||
}
|
||||
@@ -112,7 +120,11 @@ class OverrideTester {
|
||||
const includes = toMatcher(includePatterns);
|
||||
const excludes = toMatcher(excludePatterns);
|
||||
|
||||
return new OverrideTester([{ includes, excludes }], basePath);
|
||||
return new OverrideTester(
|
||||
[{ includes, excludes }],
|
||||
basePath,
|
||||
endsWithWildcard
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -125,28 +137,44 @@ class OverrideTester {
|
||||
*/
|
||||
static and(a, b) {
|
||||
if (!b) {
|
||||
return a && new OverrideTester(a.patterns, a.basePath);
|
||||
return a && new OverrideTester(
|
||||
a.patterns,
|
||||
a.basePath,
|
||||
a.endsWithWildcard
|
||||
);
|
||||
}
|
||||
if (!a) {
|
||||
return new OverrideTester(b.patterns, b.basePath);
|
||||
return new OverrideTester(
|
||||
b.patterns,
|
||||
b.basePath,
|
||||
b.endsWithWildcard
|
||||
);
|
||||
}
|
||||
|
||||
assert.strictEqual(a.basePath, b.basePath);
|
||||
return new OverrideTester(a.patterns.concat(b.patterns), a.basePath);
|
||||
return new OverrideTester(
|
||||
a.patterns.concat(b.patterns),
|
||||
a.basePath,
|
||||
a.endsWithWildcard || b.endsWithWildcard
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize this instance.
|
||||
* @param {Pattern[]} patterns The matchers.
|
||||
* @param {string} basePath The base path.
|
||||
* @param {boolean} endsWithWildcard If `true` then a pattern ends with `*`.
|
||||
*/
|
||||
constructor(patterns, basePath) {
|
||||
constructor(patterns, basePath, endsWithWildcard = false) {
|
||||
|
||||
/** @type {Pattern[]} */
|
||||
this.patterns = patterns;
|
||||
|
||||
/** @type {string} */
|
||||
this.basePath = basePath;
|
||||
|
||||
/** @type {boolean} */
|
||||
this.endsWithWildcard = endsWithWildcard;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+66
-30
@@ -88,7 +88,7 @@ const IGNORED = 2;
|
||||
* @typedef {Object} FileEnumeratorInternalSlots
|
||||
* @property {CascadingConfigArrayFactory} configArrayFactory The factory for config arrays.
|
||||
* @property {string} cwd The base directory to start lookup.
|
||||
* @property {RegExp} extensionRegExp The RegExp to test if a string ends with specific file extensions.
|
||||
* @property {RegExp|null} extensionRegExp The RegExp to test if a string ends with specific file extensions.
|
||||
* @property {boolean} globInputPaths Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file.
|
||||
* @property {boolean} ignoreFlag The flag to check ignored files.
|
||||
* @property {(filePath:string, dot:boolean) => boolean} defaultIgnores The default predicate function to ignore files.
|
||||
@@ -127,12 +127,12 @@ function statSafeSync(filePath) {
|
||||
/**
|
||||
* Get filenames in a given path to a directory.
|
||||
* @param {string} directoryPath The path to target directory.
|
||||
* @returns {string[]} The filenames.
|
||||
* @returns {import("fs").Dirent[]} The filenames.
|
||||
* @private
|
||||
*/
|
||||
function readdirSafeSync(directoryPath) {
|
||||
try {
|
||||
return fs.readdirSync(directoryPath);
|
||||
return fs.readdirSync(directoryPath, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
/* istanbul ignore next */
|
||||
if (error.code !== "ENOENT") {
|
||||
@@ -142,6 +142,27 @@ function readdirSafeSync(directoryPath) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a `RegExp` object to detect extensions.
|
||||
* @param {string[] | null} extensions The extensions to create.
|
||||
* @returns {RegExp | null} The created `RegExp` object or null.
|
||||
*/
|
||||
function createExtensionRegExp(extensions) {
|
||||
if (extensions) {
|
||||
const normalizedExts = extensions.map(ext => escapeRegExp(
|
||||
ext.startsWith(".")
|
||||
? ext.slice(1)
|
||||
: ext
|
||||
));
|
||||
|
||||
return new RegExp(
|
||||
`.\\.(?:${normalizedExts.join("|")})$`,
|
||||
"u"
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The error type when no files match a glob.
|
||||
*/
|
||||
@@ -188,7 +209,7 @@ class FileEnumerator {
|
||||
constructor({
|
||||
cwd = process.cwd(),
|
||||
configArrayFactory = new CascadingConfigArrayFactory({ cwd }),
|
||||
extensions = [".js"],
|
||||
extensions = null,
|
||||
globInputPaths = true,
|
||||
errorOnUnmatchedPattern = true,
|
||||
ignore = true
|
||||
@@ -197,17 +218,7 @@ class FileEnumerator {
|
||||
configArrayFactory,
|
||||
cwd,
|
||||
defaultIgnores: IgnorePattern.createDefaultIgnore(cwd),
|
||||
extensionRegExp: new RegExp(
|
||||
`.\\.(?:${extensions
|
||||
.map(ext => escapeRegExp(
|
||||
ext.startsWith(".")
|
||||
? ext.slice(1)
|
||||
: ext
|
||||
))
|
||||
.join("|")
|
||||
})$`,
|
||||
"u"
|
||||
),
|
||||
extensionRegExp: createExtensionRegExp(extensions),
|
||||
globInputPaths,
|
||||
errorOnUnmatchedPattern,
|
||||
ignoreFlag: ignore
|
||||
@@ -215,11 +226,36 @@ class FileEnumerator {
|
||||
}
|
||||
|
||||
/**
|
||||
* The `RegExp` object that tests if a file path has the allowed file extensions.
|
||||
* @type {RegExp}
|
||||
* Check if a given file is target or not.
|
||||
* @param {string} filePath The path to a candidate file.
|
||||
* @param {ConfigArray} [providedConfig] Optional. The configuration for the file.
|
||||
* @returns {boolean} `true` if the file is a target.
|
||||
*/
|
||||
get extensionRegExp() {
|
||||
return internalSlotsMap.get(this).extensionRegExp;
|
||||
isTargetPath(filePath, providedConfig) {
|
||||
const {
|
||||
configArrayFactory,
|
||||
extensionRegExp
|
||||
} = internalSlotsMap.get(this);
|
||||
|
||||
// If `--ext` option is present, use it.
|
||||
if (extensionRegExp) {
|
||||
return extensionRegExp.test(filePath);
|
||||
}
|
||||
|
||||
// `.js` file is target by default.
|
||||
if (filePath.endsWith(".js")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// use `overrides[].files` to check additional targets.
|
||||
const config =
|
||||
providedConfig ||
|
||||
configArrayFactory.getConfigArrayForFile(
|
||||
filePath,
|
||||
{ ignoreNotFoundError: true }
|
||||
);
|
||||
|
||||
return config.isAdditionalTargetPath(filePath);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -380,18 +416,17 @@ class FileEnumerator {
|
||||
*/
|
||||
*_iterateFilesRecursive(directoryPath, options) {
|
||||
debug(`Enter the directory: ${directoryPath}`);
|
||||
const { configArrayFactory, extensionRegExp } = internalSlotsMap.get(this);
|
||||
const { configArrayFactory } = internalSlotsMap.get(this);
|
||||
|
||||
/** @type {ConfigArray|null} */
|
||||
let config = null;
|
||||
|
||||
// Enumerate the files of this directory.
|
||||
for (const filename of readdirSafeSync(directoryPath)) {
|
||||
const filePath = path.join(directoryPath, filename);
|
||||
const stat = statSafeSync(filePath); // TODO: Use `withFileTypes` in the future.
|
||||
for (const entry of readdirSafeSync(directoryPath)) {
|
||||
const filePath = path.join(directoryPath, entry.name);
|
||||
|
||||
// Check if the file is matched.
|
||||
if (stat && stat.isFile()) {
|
||||
if (entry.isFile()) {
|
||||
if (!config) {
|
||||
config = configArrayFactory.getConfigArrayForFile(
|
||||
filePath,
|
||||
@@ -404,29 +439,30 @@ class FileEnumerator {
|
||||
{ ignoreNotFoundError: true }
|
||||
);
|
||||
}
|
||||
const ignored = this._isIgnoredFile(filePath, { ...options, config });
|
||||
const flag = ignored ? IGNORED_SILENTLY : NONE;
|
||||
const matched = options.selector
|
||||
|
||||
// Started with a glob pattern; choose by the pattern.
|
||||
? options.selector.match(filePath)
|
||||
|
||||
// Started with a directory path; choose by file extensions.
|
||||
: extensionRegExp.test(filePath);
|
||||
: this.isTargetPath(filePath, config);
|
||||
|
||||
if (matched) {
|
||||
debug(`Yield: ${filename}${ignored ? " but ignored" : ""}`);
|
||||
const ignored = this._isIgnoredFile(filePath, { ...options, config });
|
||||
const flag = ignored ? IGNORED_SILENTLY : NONE;
|
||||
|
||||
debug(`Yield: ${entry.name}${ignored ? " but ignored" : ""}`);
|
||||
yield {
|
||||
config: configArrayFactory.getConfigArrayForFile(filePath),
|
||||
filePath,
|
||||
flag
|
||||
};
|
||||
} else {
|
||||
debug(`Didn't match: ${filename}`);
|
||||
debug(`Didn't match: ${entry.name}`);
|
||||
}
|
||||
|
||||
// Dive into the sub directory.
|
||||
} else if (options.recursive && stat && stat.isDirectory()) {
|
||||
} else if (options.recursive && entry.isDirectory()) {
|
||||
if (!config) {
|
||||
config = configArrayFactory.getConfigArrayForFile(
|
||||
filePath,
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@ function getMessageType(message) {
|
||||
* @private
|
||||
*/
|
||||
function pathWithoutExt(filePath) {
|
||||
return path.posix.join(path.posix.dirname(filePath), path.basename(filePath, path.extname(filePath)));
|
||||
return path.join(path.dirname(filePath), path.basename(filePath, path.extname(filePath)));
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
+1
-2
@@ -17,7 +17,6 @@
|
||||
|
||||
const fs = require("fs"),
|
||||
path = require("path"),
|
||||
mkdirp = require("mkdirp"),
|
||||
{ CLIEngine } = require("./cli-engine"),
|
||||
options = require("./options"),
|
||||
log = require("./shared/logging"),
|
||||
@@ -115,7 +114,7 @@ function printResults(engine, results, format, outputFile) {
|
||||
}
|
||||
|
||||
try {
|
||||
mkdirp.sync(path.dirname(filePath));
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.writeFileSync(filePath, output);
|
||||
} catch (ex) {
|
||||
log.error("There was a problem writing the output file:\n%s", ex);
|
||||
|
||||
+15
-3
@@ -267,6 +267,15 @@ function createDisableDirectives(options) {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the ignored part from a given directive comment and trim it.
|
||||
* @param {string} value The comment text to strip.
|
||||
* @returns {string} The stripped text.
|
||||
*/
|
||||
function stripDirectiveComment(value) {
|
||||
return value.split(/\s-{2,}\s/u)[0].trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses comments in file to extract file-specific config of rules, globals
|
||||
* and environments and merges them with global config; also code blocks
|
||||
@@ -286,7 +295,7 @@ function getDirectiveComments(filename, ast, ruleMapper, warnInlineConfig) {
|
||||
const disableDirectives = [];
|
||||
|
||||
ast.comments.filter(token => token.type !== "Shebang").forEach(comment => {
|
||||
const trimmedCommentText = comment.value.trim();
|
||||
const trimmedCommentText = stripDirectiveComment(comment.value);
|
||||
const match = /^(eslint(?:-env|-enable|-disable(?:(?:-next)?-line)?)?|exported|globals?)(?:\s|$)/u.exec(trimmedCommentText);
|
||||
|
||||
if (!match) {
|
||||
@@ -444,8 +453,11 @@ function findEslintEnv(text) {
|
||||
|
||||
eslintEnvPattern.lastIndex = 0;
|
||||
|
||||
while ((match = eslintEnvPattern.exec(text))) {
|
||||
retv = Object.assign(retv || {}, commentParser.parseListConfig(match[1]));
|
||||
while ((match = eslintEnvPattern.exec(text)) !== null) {
|
||||
retv = Object.assign(
|
||||
retv || {},
|
||||
commentParser.parseListConfig(stripDirectiveComment(match[1]))
|
||||
);
|
||||
}
|
||||
|
||||
return retv;
|
||||
|
||||
+51
-2
@@ -50,6 +50,52 @@ const
|
||||
|
||||
const ajv = require("../shared/ajv")({ strictDefaults: true });
|
||||
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Typedefs
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A test case that is expected to pass lint.
|
||||
* @typedef {Object} ValidTestCase
|
||||
* @property {string} code Code for the test case.
|
||||
* @property {any[]} [options] Options for the test case.
|
||||
* @property {{ [name: string]: any }} [settings] Settings for the test case.
|
||||
* @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames.
|
||||
* @property {string} [parser] The absolute path for the parser.
|
||||
* @property {{ [name: string]: any }} [parserOptions] Options for the parser.
|
||||
* @property {{ [name: string]: "readonly" | "writable" | "off" }} [globals] The additional global variables.
|
||||
* @property {{ [name: string]: boolean }} [env] Environments for the test case.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A test case that is expected to fail lint.
|
||||
* @typedef {Object} InvalidTestCase
|
||||
* @property {string} code Code for the test case.
|
||||
* @property {number | Array<TestCaseError | string | RegExp>} errors Expected errors.
|
||||
* @property {string | null} [output] The expected code after autofixes are applied. If set to `null`, the test runner will assert that no autofix is suggested.
|
||||
* @property {any[]} [options] Options for the test case.
|
||||
* @property {{ [name: string]: any }} [settings] Settings for the test case.
|
||||
* @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames.
|
||||
* @property {string} [parser] The absolute path for the parser.
|
||||
* @property {{ [name: string]: any }} [parserOptions] Options for the parser.
|
||||
* @property {{ [name: string]: "readonly" | "writable" | "off" }} [globals] The additional global variables.
|
||||
* @property {{ [name: string]: boolean }} [env] Environments for the test case.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A description of a reported error used in a rule tester test.
|
||||
* @typedef {Object} TestCaseError
|
||||
* @property {string | RegExp} [message] Message.
|
||||
* @property {string} [messageId] Message ID.
|
||||
* @property {string} [type] The type of the reported AST node.
|
||||
* @property {{ [name: string]: string }} [data] The data used to fill the message template.
|
||||
* @property {number} [line] The 1-based line number of the reported start location.
|
||||
* @property {number} [column] The 1-based column number of the reported start location.
|
||||
* @property {number} [endLine] The 1-based line number of the reported end location.
|
||||
* @property {number} [endColumn] The 1-based column number of the reported end location.
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Private Members
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -128,7 +174,7 @@ function freezeDeeply(x) {
|
||||
*/
|
||||
function sanitize(text) {
|
||||
return text.replace(
|
||||
/[\u0000-\u0009|\u000b-\u001a]/gu, // eslint-disable-line no-control-regex
|
||||
/[\u0000-\u0009\u000b-\u001a]/gu, // eslint-disable-line no-control-regex
|
||||
c => `\\u${c.codePointAt(0).toString(16).padStart(4, "0")}`
|
||||
);
|
||||
}
|
||||
@@ -273,7 +319,10 @@ class RuleTester {
|
||||
* Adds a new rule test to execute.
|
||||
* @param {string} ruleName The name of the rule to run.
|
||||
* @param {Function} rule The rule to test.
|
||||
* @param {Object} test The collection of tests to run.
|
||||
* @param {{
|
||||
* valid: (ValidTestCase | string)[],
|
||||
* invalid: InvalidTestCase[]
|
||||
* }} test The collection of tests to run.
|
||||
* @returns {void}
|
||||
*/
|
||||
run(ruleName, rule, test) {
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ const astUtils = require("./utils/ast-utils");
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u;
|
||||
const TARGET_METHODS = /^(?:every|filter|find(?:Index)?|map|reduce(?:Right)?|some|sort)$/u;
|
||||
const TARGET_METHODS = /^(?:every|filter|find(?:Index)?|flatMap|map|reduce(?:Right)?|some|sort)$/u;
|
||||
|
||||
/**
|
||||
* Checks a given code path segment is reachable.
|
||||
|
||||
+63
-21
@@ -24,28 +24,52 @@ module.exports = {
|
||||
|
||||
fixable: "whitespace",
|
||||
|
||||
schema: [
|
||||
{
|
||||
oneOf: [
|
||||
{
|
||||
enum: ["always", "never", "consistent"]
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
multiline: {
|
||||
type: "boolean"
|
||||
},
|
||||
minItems: {
|
||||
type: ["integer", "null"],
|
||||
minimum: 0
|
||||
}
|
||||
schema: {
|
||||
definitions: {
|
||||
basicConfig: {
|
||||
oneOf: [
|
||||
{
|
||||
enum: ["always", "never", "consistent"]
|
||||
},
|
||||
additionalProperties: false
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
multiline: {
|
||||
type: "boolean"
|
||||
},
|
||||
minItems: {
|
||||
type: ["integer", "null"],
|
||||
minimum: 0
|
||||
}
|
||||
},
|
||||
additionalProperties: false
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
items: [
|
||||
{
|
||||
oneOf: [
|
||||
{
|
||||
$ref: "#/definitions/basicConfig"
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
ArrayExpression: {
|
||||
$ref: "#/definitions/basicConfig"
|
||||
},
|
||||
ArrayPattern: {
|
||||
$ref: "#/definitions/basicConfig"
|
||||
}
|
||||
},
|
||||
additionalProperties: false,
|
||||
minProperties: 1
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
messages: {
|
||||
unexpectedLineBreak: "There should be no linebreak here.",
|
||||
@@ -93,6 +117,20 @@ module.exports = {
|
||||
* @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object.
|
||||
*/
|
||||
function normalizeOptions(options) {
|
||||
if (options && (options.ArrayExpression || options.ArrayPattern)) {
|
||||
let expressionOptions, patternOptions;
|
||||
|
||||
if (options.ArrayExpression) {
|
||||
expressionOptions = normalizeOptionValue(options.ArrayExpression);
|
||||
}
|
||||
|
||||
if (options.ArrayPattern) {
|
||||
patternOptions = normalizeOptionValue(options.ArrayPattern);
|
||||
}
|
||||
|
||||
return { ArrayExpression: expressionOptions, ArrayPattern: patternOptions };
|
||||
}
|
||||
|
||||
const value = normalizeOptionValue(options);
|
||||
|
||||
return { ArrayExpression: value, ArrayPattern: value };
|
||||
@@ -177,6 +215,10 @@ module.exports = {
|
||||
const normalizedOptions = normalizeOptions(context.options[0]);
|
||||
const options = normalizedOptions[node.type];
|
||||
|
||||
if (!options) {
|
||||
return;
|
||||
}
|
||||
|
||||
let elementBreak = false;
|
||||
|
||||
/*
|
||||
|
||||
+4
-4
@@ -67,7 +67,7 @@ module.exports = {
|
||||
function reportNoBeginningSpace(node, token, tokenAfter) {
|
||||
context.report({
|
||||
node,
|
||||
loc: token.loc.start,
|
||||
loc: { start: token.loc.end, end: tokenAfter.loc.start },
|
||||
messageId: "unexpectedSpaceAfter",
|
||||
data: {
|
||||
tokenValue: token.value
|
||||
@@ -88,7 +88,7 @@ module.exports = {
|
||||
function reportNoEndingSpace(node, token, tokenBefore) {
|
||||
context.report({
|
||||
node,
|
||||
loc: token.loc.start,
|
||||
loc: { start: tokenBefore.loc.end, end: token.loc.start },
|
||||
messageId: "unexpectedSpaceBefore",
|
||||
data: {
|
||||
tokenValue: token.value
|
||||
@@ -108,7 +108,7 @@ module.exports = {
|
||||
function reportRequiredBeginningSpace(node, token) {
|
||||
context.report({
|
||||
node,
|
||||
loc: token.loc.start,
|
||||
loc: token.loc,
|
||||
messageId: "missingSpaceAfter",
|
||||
data: {
|
||||
tokenValue: token.value
|
||||
@@ -128,7 +128,7 @@ module.exports = {
|
||||
function reportRequiredEndingSpace(node, token) {
|
||||
context.report({
|
||||
node,
|
||||
loc: token.loc.start,
|
||||
loc: token.loc,
|
||||
messageId: "missingSpaceBefore",
|
||||
data: {
|
||||
tokenValue: token.value
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* @fileoverview Rule to enforce default clauses in switch statements to be last
|
||||
* @author Milos Djermanovic
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "suggestion",
|
||||
|
||||
docs: {
|
||||
description: "enforce default clauses in switch statements to be last",
|
||||
category: "Best Practices",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/default-case-last"
|
||||
},
|
||||
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
notLast: "Default clause should be the last clause."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
return {
|
||||
SwitchStatement(node) {
|
||||
const cases = node.cases,
|
||||
indexOfDefault = cases.findIndex(c => c.test === null);
|
||||
|
||||
if (indexOfDefault !== -1 && indexOfDefault !== cases.length - 1) {
|
||||
const defaultClause = cases[indexOfDefault];
|
||||
|
||||
context.report({ node: defaultClause, messageId: "notLast" });
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
+9
-6
@@ -61,9 +61,12 @@ module.exports = {
|
||||
* @returns {boolean} whether an error should be reported or not
|
||||
*/
|
||||
function shouldReport(effectiveParent, name) {
|
||||
return effectiveParent.type !== "CallExpression" &&
|
||||
return (
|
||||
effectiveParent.type !== "CallExpression" &&
|
||||
effectiveParent.type !== "NewExpression" &&
|
||||
isInvalid(name);
|
||||
effectiveParent.parent.type !== "ObjectPattern" &&
|
||||
isInvalid(name)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -98,11 +101,11 @@ module.exports = {
|
||||
report(node);
|
||||
}
|
||||
|
||||
// Report AssignmentExpressions only if they are the left side of the assignment
|
||||
// Report AssignmentExpressions only if they are the left side of the assignment
|
||||
} else if (effectiveParent.type === "AssignmentExpression" &&
|
||||
(effectiveParent.right.type !== "MemberExpression" ||
|
||||
effectiveParent.left.type === "MemberExpression" &&
|
||||
effectiveParent.left.property.name === node.name)) {
|
||||
effectiveParent.left.type === "MemberExpression" &&
|
||||
effectiveParent.left.property.name === node.name)) {
|
||||
if (isInvalid(name)) {
|
||||
report(node);
|
||||
}
|
||||
@@ -115,7 +118,7 @@ module.exports = {
|
||||
report(node);
|
||||
}
|
||||
|
||||
// Report anything that is a match and not a CallExpression
|
||||
// Report anything that is a match and not a CallExpression
|
||||
} else if (shouldReport(effectiveParent, name)) {
|
||||
report(node);
|
||||
}
|
||||
|
||||
+24
-6
@@ -540,8 +540,15 @@ module.exports = {
|
||||
]
|
||||
},
|
||||
outerIIFEBody: {
|
||||
type: "integer",
|
||||
minimum: 0
|
||||
oneOf: [
|
||||
{
|
||||
type: "integer",
|
||||
minimum: 0
|
||||
},
|
||||
{
|
||||
enum: ["off"]
|
||||
}
|
||||
]
|
||||
},
|
||||
MemberExpression: {
|
||||
oneOf: [
|
||||
@@ -590,6 +597,10 @@ module.exports = {
|
||||
type: "boolean",
|
||||
default: false
|
||||
},
|
||||
offsetTernaryExpressions: {
|
||||
type: "boolean",
|
||||
default: false
|
||||
},
|
||||
ignoredNodes: {
|
||||
type: "array",
|
||||
items: {
|
||||
@@ -922,7 +933,11 @@ module.exports = {
|
||||
|
||||
parameterParens.add(openingParen);
|
||||
parameterParens.add(closingParen);
|
||||
offsets.setDesiredOffset(openingParen, sourceCode.getTokenBefore(openingParen), 0);
|
||||
|
||||
const offsetAfterToken = node.callee.type === "TaggedTemplateExpression" ? sourceCode.getFirstToken(node.callee.quasi) : openingParen;
|
||||
const offsetToken = sourceCode.getTokenBefore(offsetAfterToken);
|
||||
|
||||
offsets.setDesiredOffset(openingParen, offsetToken, 0);
|
||||
|
||||
addElementListIndent(node.arguments, openingParen, closingParen, options.CallExpression.arguments);
|
||||
}
|
||||
@@ -1088,7 +1103,6 @@ module.exports = {
|
||||
},
|
||||
|
||||
"BlockStatement, ClassBody"(node) {
|
||||
|
||||
let blockIndentLevel;
|
||||
|
||||
if (node.parent && isOuterIIFE(node.parent)) {
|
||||
@@ -1108,6 +1122,7 @@ module.exports = {
|
||||
if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) {
|
||||
offsets.setDesiredOffset(sourceCode.getFirstToken(node), sourceCode.getFirstToken(node.parent), 0);
|
||||
}
|
||||
|
||||
addElementListIndent(node.body, sourceCode.getFirstToken(node), sourceCode.getLastToken(node), blockIndentLevel);
|
||||
},
|
||||
|
||||
@@ -1142,7 +1157,8 @@ module.exports = {
|
||||
offsets.setDesiredOffset(questionMarkToken, firstToken, 1);
|
||||
offsets.setDesiredOffset(colonToken, firstToken, 1);
|
||||
|
||||
offsets.setDesiredOffset(firstConsequentToken, firstToken, 1);
|
||||
offsets.setDesiredOffset(firstConsequentToken, firstToken,
|
||||
options.offsetTernaryExpressions ? 2 : 1);
|
||||
|
||||
/*
|
||||
* The alternate and the consequent should usually have the same indentation.
|
||||
@@ -1167,7 +1183,9 @@ module.exports = {
|
||||
* If `baz` were aligned with `bar` rather than being offset by 1 from `foo`, `baz` would end up
|
||||
* having no expected indentation.
|
||||
*/
|
||||
offsets.setDesiredOffset(firstAlternateToken, firstToken, 1);
|
||||
offsets.setDesiredOffset(firstAlternateToken, firstToken,
|
||||
firstAlternateToken.type === "Punctuator" &&
|
||||
options.offsetTernaryExpressions ? 2 : 1);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
+3
@@ -37,6 +37,7 @@ module.exports = new LazyLoadingRuleMap(Object.entries({
|
||||
"constructor-super": () => require("./constructor-super"),
|
||||
curly: () => require("./curly"),
|
||||
"default-case": () => require("./default-case"),
|
||||
"default-case-last": () => require("./default-case-last"),
|
||||
"default-param-last": () => require("./default-param-last"),
|
||||
"dot-location": () => require("./dot-location"),
|
||||
"dot-notation": () => require("./dot-notation"),
|
||||
@@ -178,6 +179,7 @@ module.exports = new LazyLoadingRuleMap(Object.entries({
|
||||
"no-prototype-builtins": () => require("./no-prototype-builtins"),
|
||||
"no-redeclare": () => require("./no-redeclare"),
|
||||
"no-regex-spaces": () => require("./no-regex-spaces"),
|
||||
"no-restricted-exports": () => require("./no-restricted-exports"),
|
||||
"no-restricted-globals": () => require("./no-restricted-globals"),
|
||||
"no-restricted-imports": () => require("./no-restricted-imports"),
|
||||
"no-restricted-modules": () => require("./no-restricted-modules"),
|
||||
@@ -215,6 +217,7 @@ module.exports = new LazyLoadingRuleMap(Object.entries({
|
||||
"no-unused-labels": () => require("./no-unused-labels"),
|
||||
"no-unused-vars": () => require("./no-unused-vars"),
|
||||
"no-use-before-define": () => require("./no-use-before-define"),
|
||||
"no-useless-backreference": () => require("./no-useless-backreference"),
|
||||
"no-useless-call": () => require("./no-useless-call"),
|
||||
"no-useless-catch": () => require("./no-useless-catch"),
|
||||
"no-useless-computed-key": () => require("./no-useless-computed-key"),
|
||||
|
||||
+1
-2
@@ -414,8 +414,7 @@ module.exports = {
|
||||
if (property.computed) {
|
||||
return sourceCode.getText().slice(key.range[0], key.range[1]);
|
||||
}
|
||||
|
||||
return property.key.name || property.key.value;
|
||||
return astUtils.getStaticPropertyName(property);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+43
-1
@@ -183,6 +183,21 @@ module.exports = {
|
||||
(end.line > lineNumber || (end.line === lineNumber && end.column === line.length));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a node is a JSXEmptyExpression contained in a single line JSXExpressionContainer.
|
||||
* @param {ASTNode} node A node to check.
|
||||
* @returns {boolean} True if the node is a JSXEmptyExpression contained in a single line JSXExpressionContainer.
|
||||
*/
|
||||
function isJSXEmptyExpressionInSingleLineContainer(node) {
|
||||
if (!node || !node.parent || node.type !== "JSXEmptyExpression" || node.parent.type !== "JSXExpressionContainer") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const parent = node.parent;
|
||||
|
||||
return parent.loc.start.line === parent.loc.end.line;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the line after the comment and any remaining trailing whitespace is
|
||||
* stripped.
|
||||
@@ -252,6 +267,33 @@ module.exports = {
|
||||
return acc;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of all comments in the source code.
|
||||
* If the element in the array is a JSXEmptyExpression contained with a single line JSXExpressionContainer,
|
||||
* the element is changed with JSXExpressionContainer node.
|
||||
* @returns {ASTNode[]} An array of comment nodes
|
||||
*/
|
||||
function getAllComments() {
|
||||
const comments = [];
|
||||
|
||||
sourceCode.getAllComments()
|
||||
.forEach(commentNode => {
|
||||
const containingNode = sourceCode.getNodeByRangeIndex(commentNode.range[0]);
|
||||
|
||||
if (isJSXEmptyExpressionInSingleLineContainer(containingNode)) {
|
||||
|
||||
// push a unique node only
|
||||
if (comments[comments.length - 1] !== containingNode.parent) {
|
||||
comments.push(containingNode.parent);
|
||||
}
|
||||
} else {
|
||||
comments.push(commentNode);
|
||||
}
|
||||
});
|
||||
|
||||
return comments;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the program for max length
|
||||
* @param {ASTNode} node Node to examine
|
||||
@@ -264,7 +306,7 @@ module.exports = {
|
||||
const lines = sourceCode.lines,
|
||||
|
||||
// list of comments to ignore
|
||||
comments = ignoreComments || maxCommentLength || ignoreTrailingComments ? sourceCode.getAllComments() : [];
|
||||
comments = ignoreComments || maxCommentLength || ignoreTrailingComments ? getAllComments() : [];
|
||||
|
||||
// we iterate over comments in parallel with the lines
|
||||
let commentsIndex = 0;
|
||||
|
||||
-3
@@ -54,9 +54,6 @@ const OPTIONS_OR_INTEGER_SCHEMA = {
|
||||
function getCommentLineNumbers(comments) {
|
||||
const map = new Map();
|
||||
|
||||
if (!comments) {
|
||||
return map;
|
||||
}
|
||||
comments.forEach(comment => {
|
||||
for (let i = comment.loc.start.line; i <= comment.loc.end.line; i++) {
|
||||
map.set(i, comment);
|
||||
|
||||
+3
-7
@@ -9,6 +9,8 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const astUtils = require("./utils/ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -160,13 +162,7 @@ module.exports = {
|
||||
let name = "";
|
||||
|
||||
if (node.callee.type === "MemberExpression") {
|
||||
const property = node.callee.property;
|
||||
|
||||
if (property.type === "Literal" && (typeof property.value === "string")) {
|
||||
name = property.value;
|
||||
} else if (property.type === "Identifier" && !node.callee.computed) {
|
||||
name = property.name;
|
||||
}
|
||||
name = astUtils.getStaticPropertyName(node.callee) || "";
|
||||
} else {
|
||||
name = node.callee.name;
|
||||
}
|
||||
|
||||
+3
-16
@@ -5,6 +5,8 @@
|
||||
|
||||
"use strict";
|
||||
|
||||
const astUtils = require("./utils/ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -53,21 +55,6 @@ module.exports = {
|
||||
return stateMap[key][isStatic ? "static" : "nonStatic"];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the name text of a given node.
|
||||
* @param {ASTNode} node A node to get the name.
|
||||
* @returns {string} The name text of the node.
|
||||
*/
|
||||
function getName(node) {
|
||||
switch (node.type) {
|
||||
case "Identifier": return node.name;
|
||||
case "Literal": return String(node.value);
|
||||
|
||||
/* istanbul ignore next: syntax error */
|
||||
default: return "";
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
// Initializes the stack of state of member declarations.
|
||||
@@ -91,7 +78,7 @@ module.exports = {
|
||||
return;
|
||||
}
|
||||
|
||||
const name = getName(node.key);
|
||||
const name = astUtils.getStaticPropertyName(node) || "";
|
||||
const state = getState(name, node.static);
|
||||
let isDuplicate = false;
|
||||
|
||||
|
||||
+123
-49
@@ -169,6 +169,28 @@ module.exports = {
|
||||
return ruleApplies(node) && isParenthesisedTwice(node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a node that is expected to be parenthesised is surrounded by
|
||||
* (potentially) invalid extra parentheses with considering precedence level of the node.
|
||||
* If the preference level of the node is not higher or equal to precedence lower limit, it also checks
|
||||
* whether the node is surrounded by parentheses twice or not.
|
||||
* @param {ASTNode} node The node to be checked.
|
||||
* @param {number} precedenceLowerLimit The lower limit of precedence.
|
||||
* @returns {boolean} True if the node is has an unexpected extra pair of parentheses.
|
||||
* @private
|
||||
*/
|
||||
function hasExcessParensWithPrecedence(node, precedenceLowerLimit) {
|
||||
if (ruleApplies(node) && isParenthesised(node)) {
|
||||
if (
|
||||
precedence(node) >= precedenceLowerLimit ||
|
||||
isParenthesisedTwice(node)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a node test expression is allowed to have a parenthesised assignment
|
||||
* @param {ASTNode} node The node to be checked.
|
||||
@@ -320,6 +342,17 @@ module.exports = {
|
||||
return node.type === "CallExpression" && node.callee.type === "FunctionExpression";
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the given node can be the assignment target in destructuring or the LHS of an assignment.
|
||||
* This is to avoid an autofix that could change behavior because parsers mistakenly allow invalid syntax,
|
||||
* such as `(a = b) = c` and `[(a = b) = c] = []`. Ideally, this function shouldn't be necessary.
|
||||
* @param {ASTNode} [node] The node to check
|
||||
* @returns {boolean} `true` if the given node can be a valid assignment target
|
||||
*/
|
||||
function canBeAssignmentTarget(node) {
|
||||
return node && (node.type === "Identifier" || node.type === "MemberExpression");
|
||||
}
|
||||
|
||||
/**
|
||||
* Report the node
|
||||
* @param {ASTNode} node node to evaluate
|
||||
@@ -370,17 +403,13 @@ module.exports = {
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate Unary update
|
||||
* Evaluate a argument of the node.
|
||||
* @param {ASTNode} node node to evaluate
|
||||
* @returns {void}
|
||||
* @private
|
||||
*/
|
||||
function checkUnaryUpdate(node) {
|
||||
if (node.type === "UnaryExpression" && node.argument.type === "BinaryExpression" && node.argument.operator === "**") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (hasExcessParens(node.argument) && precedence(node.argument) >= precedence(node)) {
|
||||
function checkArgumentWithPrecedence(node) {
|
||||
if (hasExcessParensWithPrecedence(node.argument, precedence(node))) {
|
||||
report(node.argument);
|
||||
}
|
||||
}
|
||||
@@ -411,25 +440,24 @@ module.exports = {
|
||||
function checkCallNew(node) {
|
||||
const callee = node.callee;
|
||||
|
||||
if (hasExcessParens(callee) && precedence(callee) >= precedence(node)) {
|
||||
if (hasExcessParensWithPrecedence(callee, precedence(node))) {
|
||||
const hasNewParensException = callee.type === "NewExpression" && !isNewExpressionWithParens(callee);
|
||||
|
||||
if (
|
||||
hasDoubleExcessParens(callee) ||
|
||||
!isIIFE(node) && !hasNewParensException && !(
|
||||
|
||||
/*
|
||||
* Allow extra parens around a new expression if
|
||||
* there are intervening parentheses.
|
||||
*/
|
||||
(callee.type === "MemberExpression" && doesMemberExpressionContainCallExpression(callee))
|
||||
// Allow extra parens around a new expression if they are intervening parentheses.
|
||||
node.type === "NewExpression" &&
|
||||
callee.type === "MemberExpression" &&
|
||||
doesMemberExpressionContainCallExpression(callee)
|
||||
)
|
||||
) {
|
||||
report(node.callee);
|
||||
}
|
||||
}
|
||||
node.arguments
|
||||
.filter(arg => hasExcessParens(arg) && precedence(arg) >= PRECEDENCE_OF_ASSIGNMENT_EXPR)
|
||||
.filter(arg => hasExcessParensWithPrecedence(arg, PRECEDENCE_OF_ASSIGNMENT_EXPR))
|
||||
.forEach(report);
|
||||
}
|
||||
|
||||
@@ -444,15 +472,26 @@ module.exports = {
|
||||
const leftPrecedence = precedence(node.left);
|
||||
const rightPrecedence = precedence(node.right);
|
||||
const isExponentiation = node.operator === "**";
|
||||
const shouldSkipLeft = (NESTED_BINARY && (node.left.type === "BinaryExpression" || node.left.type === "LogicalExpression")) ||
|
||||
node.left.type === "UnaryExpression" && isExponentiation;
|
||||
const shouldSkipLeft = NESTED_BINARY && (node.left.type === "BinaryExpression" || node.left.type === "LogicalExpression");
|
||||
const shouldSkipRight = NESTED_BINARY && (node.right.type === "BinaryExpression" || node.right.type === "LogicalExpression");
|
||||
|
||||
if (!shouldSkipLeft && hasExcessParens(node.left) && (leftPrecedence > prec || (leftPrecedence === prec && !isExponentiation))) {
|
||||
report(node.left);
|
||||
if (!shouldSkipLeft && hasExcessParens(node.left)) {
|
||||
if (
|
||||
!(node.left.type === "UnaryExpression" && isExponentiation) &&
|
||||
(leftPrecedence > prec || (leftPrecedence === prec && !isExponentiation)) ||
|
||||
isParenthesisedTwice(node.left)
|
||||
) {
|
||||
report(node.left);
|
||||
}
|
||||
}
|
||||
if (!shouldSkipRight && hasExcessParens(node.right) && (rightPrecedence > prec || (rightPrecedence === prec && isExponentiation))) {
|
||||
report(node.right);
|
||||
|
||||
if (!shouldSkipRight && hasExcessParens(node.right)) {
|
||||
if (
|
||||
(rightPrecedence > prec || (rightPrecedence === prec && isExponentiation)) ||
|
||||
isParenthesisedTwice(node.right)
|
||||
) {
|
||||
report(node.right);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -485,11 +524,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkSpreadOperator(node) {
|
||||
const hasExtraParens = precedence(node.argument) >= PRECEDENCE_OF_ASSIGNMENT_EXPR
|
||||
? hasExcessParens(node.argument)
|
||||
: hasDoubleExcessParens(node.argument);
|
||||
|
||||
if (hasExtraParens) {
|
||||
if (hasExcessParensWithPrecedence(node.argument, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
|
||||
report(node.argument);
|
||||
}
|
||||
}
|
||||
@@ -651,7 +686,13 @@ module.exports = {
|
||||
return {
|
||||
ArrayExpression(node) {
|
||||
node.elements
|
||||
.filter(e => e && hasExcessParens(e) && precedence(e) >= PRECEDENCE_OF_ASSIGNMENT_EXPR)
|
||||
.filter(e => e && hasExcessParensWithPrecedence(e, PRECEDENCE_OF_ASSIGNMENT_EXPR))
|
||||
.forEach(report);
|
||||
},
|
||||
|
||||
ArrayPattern(node) {
|
||||
node.elements
|
||||
.filter(e => canBeAssignmentTarget(e) && hasExcessParens(e))
|
||||
.forEach(report);
|
||||
},
|
||||
|
||||
@@ -674,18 +715,18 @@ module.exports = {
|
||||
if (astUtils.isOpeningParenToken(tokenBeforeFirst) && astUtils.isOpeningBraceToken(firstBodyToken)) {
|
||||
tokensToIgnore.add(firstBodyToken);
|
||||
}
|
||||
if (hasExcessParens(node.body) && precedence(node.body) >= PRECEDENCE_OF_ASSIGNMENT_EXPR) {
|
||||
if (hasExcessParensWithPrecedence(node.body, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
|
||||
report(node.body);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
AssignmentExpression(node) {
|
||||
if (isReturnAssignException(node)) {
|
||||
return;
|
||||
if (canBeAssignmentTarget(node.left) && hasExcessParens(node.left)) {
|
||||
report(node.left);
|
||||
}
|
||||
|
||||
if (hasExcessParens(node.right) && precedence(node.right) >= precedence(node)) {
|
||||
if (!isReturnAssignException(node) && hasExcessParensWithPrecedence(node.right, precedence(node))) {
|
||||
report(node.right);
|
||||
}
|
||||
},
|
||||
@@ -702,8 +743,8 @@ module.exports = {
|
||||
|
||||
ClassBody(node) {
|
||||
node.body
|
||||
.filter(member => member.type === "MethodDefinition" && member.computed &&
|
||||
member.key && hasExcessParens(member.key) && precedence(member.key) >= PRECEDENCE_OF_ASSIGNMENT_EXPR)
|
||||
.filter(member => member.type === "MethodDefinition" && member.computed && member.key)
|
||||
.filter(member => hasExcessParensWithPrecedence(member.key, PRECEDENCE_OF_ASSIGNMENT_EXPR))
|
||||
.forEach(member => report(member.key));
|
||||
},
|
||||
|
||||
@@ -711,16 +752,18 @@ module.exports = {
|
||||
if (isReturnAssignException(node)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (hasExcessParens(node.test) && precedence(node.test) >= precedence({ type: "LogicalExpression", operator: "||" })) {
|
||||
if (
|
||||
!isCondAssignException(node) &&
|
||||
hasExcessParensWithPrecedence(node.test, precedence({ type: "LogicalExpression", operator: "||" }))
|
||||
) {
|
||||
report(node.test);
|
||||
}
|
||||
|
||||
if (hasExcessParens(node.consequent) && precedence(node.consequent) >= PRECEDENCE_OF_ASSIGNMENT_EXPR) {
|
||||
if (hasExcessParensWithPrecedence(node.consequent, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
|
||||
report(node.consequent);
|
||||
}
|
||||
|
||||
if (hasExcessParens(node.alternate) && precedence(node.alternate) >= PRECEDENCE_OF_ASSIGNMENT_EXPR) {
|
||||
if (hasExcessParensWithPrecedence(node.alternate, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
|
||||
report(node.alternate);
|
||||
}
|
||||
},
|
||||
@@ -757,9 +800,19 @@ module.exports = {
|
||||
tokensToIgnore.add(firstLeftToken);
|
||||
}
|
||||
}
|
||||
if (!(node.type === "ForOfStatement" && node.right.type === "SequenceExpression") && hasExcessParens(node.right)) {
|
||||
|
||||
if (node.type === "ForOfStatement") {
|
||||
const hasExtraParens = node.right.type === "SequenceExpression"
|
||||
? hasDoubleExcessParens(node.right)
|
||||
: hasExcessParens(node.right);
|
||||
|
||||
if (hasExtraParens) {
|
||||
report(node.right);
|
||||
}
|
||||
} else if (hasExcessParens(node.right)) {
|
||||
report(node.right);
|
||||
}
|
||||
|
||||
if (hasExcessParens(node.left)) {
|
||||
report(node.left);
|
||||
}
|
||||
@@ -910,11 +963,17 @@ module.exports = {
|
||||
NewExpression: checkCallNew,
|
||||
|
||||
ObjectExpression(node) {
|
||||
node.properties
|
||||
.filter(property => property.value && hasExcessParensWithPrecedence(property.value, PRECEDENCE_OF_ASSIGNMENT_EXPR))
|
||||
.forEach(property => report(property.value));
|
||||
},
|
||||
|
||||
ObjectPattern(node) {
|
||||
node.properties
|
||||
.filter(property => {
|
||||
const value = property.value;
|
||||
|
||||
return value && hasExcessParens(value) && precedence(value) >= PRECEDENCE_OF_ASSIGNMENT_EXPR;
|
||||
return canBeAssignmentTarget(value) && hasExcessParens(value);
|
||||
}).forEach(property => report(property.value));
|
||||
},
|
||||
|
||||
@@ -922,12 +981,20 @@ module.exports = {
|
||||
if (node.computed) {
|
||||
const { key } = node;
|
||||
|
||||
if (key && hasExcessParens(key) && precedence(key) >= PRECEDENCE_OF_ASSIGNMENT_EXPR) {
|
||||
if (key && hasExcessParensWithPrecedence(key, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
|
||||
report(key);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
RestElement(node) {
|
||||
const argument = node.argument;
|
||||
|
||||
if (canBeAssignmentTarget(argument) && hasExcessParens(argument)) {
|
||||
report(argument);
|
||||
}
|
||||
},
|
||||
|
||||
ReturnStatement(node) {
|
||||
const returnToken = sourceCode.getFirstToken(node);
|
||||
|
||||
@@ -945,8 +1012,10 @@ module.exports = {
|
||||
},
|
||||
|
||||
SequenceExpression(node) {
|
||||
const precedenceOfNode = precedence(node);
|
||||
|
||||
node.expressions
|
||||
.filter(e => hasExcessParens(e) && precedence(e) >= precedence(node))
|
||||
.filter(e => hasExcessParensWithPrecedence(e, precedenceOfNode))
|
||||
.forEach(report);
|
||||
},
|
||||
|
||||
@@ -970,16 +1039,17 @@ module.exports = {
|
||||
}
|
||||
},
|
||||
|
||||
UnaryExpression: checkUnaryUpdate,
|
||||
UpdateExpression: checkUnaryUpdate,
|
||||
AwaitExpression: checkUnaryUpdate,
|
||||
UnaryExpression: checkArgumentWithPrecedence,
|
||||
UpdateExpression: checkArgumentWithPrecedence,
|
||||
AwaitExpression: checkArgumentWithPrecedence,
|
||||
|
||||
VariableDeclarator(node) {
|
||||
if (node.init && hasExcessParens(node.init) &&
|
||||
precedence(node.init) >= PRECEDENCE_OF_ASSIGNMENT_EXPR &&
|
||||
if (
|
||||
node.init && hasExcessParensWithPrecedence(node.init, PRECEDENCE_OF_ASSIGNMENT_EXPR) &&
|
||||
|
||||
// RegExp literal is allowed to have parens (#1589)
|
||||
!(node.init.type === "Literal" && node.init.regex)) {
|
||||
// RegExp literal is allowed to have parens (#1589)
|
||||
!(node.init.type === "Literal" && node.init.regex)
|
||||
) {
|
||||
report(node.init);
|
||||
}
|
||||
},
|
||||
@@ -1022,9 +1092,13 @@ module.exports = {
|
||||
},
|
||||
|
||||
AssignmentPattern(node) {
|
||||
const { right } = node;
|
||||
const { left, right } = node;
|
||||
|
||||
if (right && hasExcessParens(right) && precedence(right) >= PRECEDENCE_OF_ASSIGNMENT_EXPR) {
|
||||
if (canBeAssignmentTarget(left) && hasExcessParens(left)) {
|
||||
report(left);
|
||||
}
|
||||
|
||||
if (right && hasExcessParensWithPrecedence(right, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
|
||||
report(right);
|
||||
}
|
||||
}
|
||||
|
||||
+12
-2
@@ -22,7 +22,11 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-func-assign"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
isAFunction: "'{{name}}' is a function."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -34,7 +38,13 @@ module.exports = {
|
||||
*/
|
||||
function checkReference(references) {
|
||||
astUtils.getModifyingReferences(references).forEach(reference => {
|
||||
context.report({ node: reference.identifier, message: "'{{name}}' is a function.", data: { name: reference.identifier.name } });
|
||||
context.report({
|
||||
node: reference.identifier,
|
||||
messageId: "isAFunction",
|
||||
data: {
|
||||
name: reference.identifier.name
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+9
-3
@@ -32,7 +32,11 @@ module.exports = {
|
||||
},
|
||||
additionalProperties: false
|
||||
}
|
||||
]
|
||||
],
|
||||
|
||||
messages: {
|
||||
globalShouldNotBeModified: "Read-only global '{{name}}' should not be modified."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -60,8 +64,10 @@ module.exports = {
|
||||
) {
|
||||
context.report({
|
||||
node: identifier,
|
||||
message: "Read-only global '{{name}}' should not be modified.",
|
||||
data: identifier
|
||||
messageId: "globalShouldNotBeModified",
|
||||
data: {
|
||||
name: identifier.name
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+6
-2
@@ -187,7 +187,11 @@ module.exports = {
|
||||
}
|
||||
},
|
||||
additionalProperties: false
|
||||
}]
|
||||
}],
|
||||
|
||||
messages: {
|
||||
useRecommendation: "use `{{recommendation}}` instead."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -204,7 +208,7 @@ module.exports = {
|
||||
function report(node, recommendation, shouldFix) {
|
||||
context.report({
|
||||
node,
|
||||
message: "use `{{recommendation}}` instead.",
|
||||
messageId: "useRecommendation",
|
||||
data: {
|
||||
recommendation
|
||||
},
|
||||
|
||||
+9
-2
@@ -20,7 +20,11 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-implied-eval"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
impliedEval: "Implied eval. Consider passing a function instead of a string."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -107,7 +111,10 @@ module.exports = {
|
||||
// remove the entire substack, to avoid duplicate reports
|
||||
const substack = impliedEvalAncestorsStack.pop();
|
||||
|
||||
context.report({ node: substack[0], message: "Implied eval. Consider passing a function instead of a string." });
|
||||
context.report({
|
||||
node: substack[0],
|
||||
messageId: "impliedEval"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+9
-2
@@ -21,7 +21,11 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-inline-comments"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
unexpectedInlineComment: "Unexpected comment inline with code."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -64,7 +68,10 @@ module.exports = {
|
||||
return;
|
||||
}
|
||||
|
||||
context.report({ node, message: "Unexpected comment inline with code." });
|
||||
context.report({
|
||||
node,
|
||||
messageId: "unexpectedInlineComment"
|
||||
});
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
+6
-2
@@ -24,7 +24,11 @@ module.exports = {
|
||||
{
|
||||
enum: ["functions", "both"]
|
||||
}
|
||||
]
|
||||
],
|
||||
|
||||
messages: {
|
||||
moveDeclToRoot: "Move {{type}} declaration to {{body}} root."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -68,7 +72,7 @@ module.exports = {
|
||||
if (!valid) {
|
||||
context.report({
|
||||
node,
|
||||
message: "Move {{type}} declaration to {{body}} root.",
|
||||
messageId: "moveDeclToRoot",
|
||||
data: {
|
||||
type: (node.type === "FunctionDeclaration" ? "function" : "variable"),
|
||||
body: (body.type === "Program" ? "program" : "function body")
|
||||
|
||||
+2
@@ -40,6 +40,8 @@ module.exports = {
|
||||
},
|
||||
additionalProperties: false
|
||||
}]
|
||||
|
||||
// no messages, because the error text comes directly from the regexpp module
|
||||
},
|
||||
|
||||
create(context) {
|
||||
|
||||
+9
-2
@@ -37,7 +37,11 @@ module.exports = {
|
||||
},
|
||||
additionalProperties: false
|
||||
}
|
||||
]
|
||||
],
|
||||
|
||||
messages: {
|
||||
unexpectedThis: "Unexpected 'this'."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -130,7 +134,10 @@ module.exports = {
|
||||
const current = stack.getCurrent();
|
||||
|
||||
if (current && !current.valid) {
|
||||
context.report({ node, message: "Unexpected 'this'." });
|
||||
context.report({
|
||||
node,
|
||||
messageId: "unexpectedThis"
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
+15
-3
@@ -59,7 +59,11 @@ module.exports = {
|
||||
},
|
||||
additionalProperties: false
|
||||
}
|
||||
]
|
||||
],
|
||||
|
||||
messages: {
|
||||
noIrregularWhitespace: "Irregular whitespace not allowed."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -161,7 +165,11 @@ module.exports = {
|
||||
column: match.index
|
||||
};
|
||||
|
||||
errors.push({ node, message: "Irregular whitespace not allowed.", loc: location });
|
||||
errors.push({
|
||||
node,
|
||||
messageId: "noIrregularWhitespace",
|
||||
loc: location
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -186,7 +194,11 @@ module.exports = {
|
||||
column: sourceLines[lineIndex].length
|
||||
};
|
||||
|
||||
errors.push({ node, message: "Irregular whitespace not allowed.", loc: location });
|
||||
errors.push({
|
||||
node,
|
||||
messageId: "noIrregularWhitespace",
|
||||
loc: location
|
||||
});
|
||||
lastLineIndex = lineIndex;
|
||||
}
|
||||
}
|
||||
|
||||
+9
-2
@@ -20,7 +20,11 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-iterator"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
noIterator: "Reserved name '__iterator__'."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -32,7 +36,10 @@ module.exports = {
|
||||
if (node.property &&
|
||||
(node.property.type === "Identifier" && node.property.name === "__iterator__" && !node.computed) ||
|
||||
(node.property.type === "Literal" && node.property.value === "__iterator__")) {
|
||||
context.report({ node, message: "Reserved name '__iterator__'." });
|
||||
context.report({
|
||||
node,
|
||||
messageId: "noIterator"
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
+9
-2
@@ -26,7 +26,11 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-label-var"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
identifierClashWithLabel: "Found identifier with same name as label."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -62,7 +66,10 @@ module.exports = {
|
||||
* with the innermost scope.
|
||||
*/
|
||||
if (findIdentifier(scope, node.label.name)) {
|
||||
context.report({ node, message: "Found identifier with same name as label." });
|
||||
context.report({
|
||||
node,
|
||||
messageId: "identifierClashWithLabel"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+10
-4
@@ -40,7 +40,13 @@ module.exports = {
|
||||
},
|
||||
additionalProperties: false
|
||||
}
|
||||
]
|
||||
],
|
||||
|
||||
messages: {
|
||||
unexpectedLabel: "Unexpected labeled statement.",
|
||||
unexpectedLabelInBreak: "Unexpected label in break statement.",
|
||||
unexpectedLabelInContinue: "Unexpected label in continue statement."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -113,7 +119,7 @@ module.exports = {
|
||||
if (!isAllowed(scopeInfo.kind)) {
|
||||
context.report({
|
||||
node,
|
||||
message: "Unexpected labeled statement."
|
||||
messageId: "unexpectedLabel"
|
||||
});
|
||||
}
|
||||
|
||||
@@ -124,7 +130,7 @@ module.exports = {
|
||||
if (node.label && !isAllowed(getKind(node.label.name))) {
|
||||
context.report({
|
||||
node,
|
||||
message: "Unexpected label in break statement."
|
||||
messageId: "unexpectedLabelInBreak"
|
||||
});
|
||||
}
|
||||
},
|
||||
@@ -133,7 +139,7 @@ module.exports = {
|
||||
if (node.label && !isAllowed(getKind(node.label.name))) {
|
||||
context.report({
|
||||
node,
|
||||
message: "Unexpected label in continue statement."
|
||||
messageId: "unexpectedLabelInContinue"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+11
-3
@@ -20,7 +20,12 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-lone-blocks"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
redundantBlock: "Block is redundant.",
|
||||
redundantNestedBlock: "Nested block is redundant."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -35,9 +40,12 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function report(node) {
|
||||
const message = node.parent.type === "BlockStatement" ? "Nested block is redundant." : "Block is redundant.";
|
||||
const messageId = node.parent.type === "BlockStatement" ? "redundantNestedBlock" : "redundantBlock";
|
||||
|
||||
context.report({ node, message });
|
||||
context.report({
|
||||
node,
|
||||
messageId
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+6
-2
@@ -20,7 +20,11 @@ module.exports = {
|
||||
},
|
||||
|
||||
schema: [],
|
||||
fixable: "code"
|
||||
fixable: "code",
|
||||
|
||||
messages: {
|
||||
unexpectedLonelyIf: "Unexpected if as the only statement in an else block."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -38,7 +42,7 @@ module.exports = {
|
||||
parent === grandparent.alternate) {
|
||||
context.report({
|
||||
node,
|
||||
message: "Unexpected if as the only statement in an else block.",
|
||||
messageId: "unexpectedLonelyIf",
|
||||
fix(fixer) {
|
||||
const openingElseCurly = sourceCode.getFirstToken(parent);
|
||||
const closingElseCurly = sourceCode.getLastToken(parent);
|
||||
|
||||
+20
-12
@@ -5,10 +5,24 @@
|
||||
|
||||
"use strict";
|
||||
|
||||
const { isNumericLiteral } = require("./utils/ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Convert the value to bigint if it's a string. Otherwise return the value as-is.
|
||||
* @param {bigint|number|string} x The value to normalize.
|
||||
* @returns {bigint|number} The normalized value.
|
||||
*/
|
||||
function normalizeIgnoreValue(x) {
|
||||
if (typeof x === "string") {
|
||||
return BigInt(x.slice(0, -1));
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "suggestion",
|
||||
@@ -34,7 +48,10 @@ module.exports = {
|
||||
ignore: {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "number"
|
||||
anyOf: [
|
||||
{ type: "number" },
|
||||
{ type: "string", pattern: "^[+-]?(?:0|[1-9][0-9]*)n$" }
|
||||
]
|
||||
},
|
||||
uniqueItems: true
|
||||
},
|
||||
@@ -56,18 +73,9 @@ module.exports = {
|
||||
const config = context.options[0] || {},
|
||||
detectObjects = !!config.detectObjects,
|
||||
enforceConst = !!config.enforceConst,
|
||||
ignore = config.ignore || [],
|
||||
ignore = (config.ignore || []).map(normalizeIgnoreValue),
|
||||
ignoreArrayIndexes = !!config.ignoreArrayIndexes;
|
||||
|
||||
/**
|
||||
* Returns whether the node is number literal
|
||||
* @param {Node} node the node literal being evaluated
|
||||
* @returns {boolean} true if the node is a number literal
|
||||
*/
|
||||
function isNumber(node) {
|
||||
return typeof node.value === "number";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the number should be ignored
|
||||
* @param {number} num the number
|
||||
@@ -113,7 +121,7 @@ module.exports = {
|
||||
Literal(node) {
|
||||
const okTypes = detectObjects ? [] : ["ObjectExpression", "Property", "AssignmentExpression"];
|
||||
|
||||
if (!isNumber(node)) {
|
||||
if (!isNumericLiteral(node)) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
+7
-5
@@ -112,7 +112,11 @@ module.exports = {
|
||||
},
|
||||
additionalProperties: false
|
||||
}
|
||||
]
|
||||
],
|
||||
|
||||
messages: {
|
||||
unexpectedMixedOperator: "Unexpected mix of '{{leftOperator}}' and '{{rightOperator}}'."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -188,8 +192,6 @@ module.exports = {
|
||||
const parent = node.parent;
|
||||
const left = (getChildNode(parent) === node) ? node : parent;
|
||||
const right = (getChildNode(parent) !== node) ? node : parent;
|
||||
const message =
|
||||
"Unexpected mix of '{{leftOperator}}' and '{{rightOperator}}'.";
|
||||
const data = {
|
||||
leftOperator: left.operator || "?:",
|
||||
rightOperator: right.operator || "?:"
|
||||
@@ -198,13 +200,13 @@ module.exports = {
|
||||
context.report({
|
||||
node: left,
|
||||
loc: getOperatorToken(left).loc,
|
||||
message,
|
||||
messageId: "unexpectedMixedOperator",
|
||||
data
|
||||
});
|
||||
context.report({
|
||||
node: right,
|
||||
loc: getOperatorToken(right).loc,
|
||||
message,
|
||||
messageId: "unexpectedMixedOperator",
|
||||
data
|
||||
});
|
||||
}
|
||||
|
||||
+14
-3
@@ -40,7 +40,12 @@ module.exports = {
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
],
|
||||
|
||||
messages: {
|
||||
noMixRequire: "Do not mix 'require' and other declarations.",
|
||||
noMixCoreModuleFileComputed: "Do not mix core, module, file and computed requires."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -211,9 +216,15 @@ module.exports = {
|
||||
VariableDeclaration(node) {
|
||||
|
||||
if (isMixed(node.declarations)) {
|
||||
context.report({ node, message: "Do not mix 'require' and other declarations." });
|
||||
context.report({
|
||||
node,
|
||||
messageId: "noMixRequire"
|
||||
});
|
||||
} else if (grouping && !isGrouped(node.declarations)) {
|
||||
context.report({ node, message: "Do not mix core, module, file and computed requires." });
|
||||
context.report({
|
||||
node,
|
||||
messageId: "noMixCoreModuleFileComputed"
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
+26
-67
@@ -23,14 +23,17 @@ module.exports = {
|
||||
{
|
||||
enum: ["smart-tabs", true, false]
|
||||
}
|
||||
]
|
||||
],
|
||||
|
||||
messages: {
|
||||
mixedSpacesAndTabs: "Mixed spaces and tabs."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const sourceCode = context.getSourceCode();
|
||||
|
||||
let smartTabs;
|
||||
const ignoredLocs = [];
|
||||
|
||||
switch (context.options[0]) {
|
||||
case true: // Support old syntax, maybe add deprecation warning here
|
||||
@@ -41,47 +44,23 @@ module.exports = {
|
||||
smartTabs = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a given line and column are before a location.
|
||||
* @param {Location} loc The location object from an AST node.
|
||||
* @param {int} line The line to check.
|
||||
* @param {int} column The column to check.
|
||||
* @returns {boolean} True if the line and column are before the location, false if not.
|
||||
* @private
|
||||
*/
|
||||
function beforeLoc(loc, line, column) {
|
||||
if (line < loc.start.line) {
|
||||
return true;
|
||||
}
|
||||
return line === loc.start.line && column < loc.start.column;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a given line and column are after a location.
|
||||
* @param {Location} loc The location object from an AST node.
|
||||
* @param {int} line The line to check.
|
||||
* @param {int} column The column to check.
|
||||
* @returns {boolean} True if the line and column are after the location, false if not.
|
||||
* @private
|
||||
*/
|
||||
function afterLoc(loc, line, column) {
|
||||
if (line > loc.end.line) {
|
||||
return true;
|
||||
}
|
||||
return line === loc.end.line && column > loc.end.column;
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Public
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
return {
|
||||
|
||||
TemplateElement(node) {
|
||||
ignoredLocs.push(node.loc);
|
||||
},
|
||||
|
||||
"Program:exit"(node) {
|
||||
const lines = sourceCode.lines,
|
||||
comments = sourceCode.getAllComments(),
|
||||
ignoredCommentLines = new Set();
|
||||
|
||||
// Add all lines except the first ones.
|
||||
comments.forEach(comment => {
|
||||
for (let i = comment.loc.start.line + 1; i <= comment.loc.end.line; i++) {
|
||||
ignoredCommentLines.add(i);
|
||||
}
|
||||
});
|
||||
|
||||
/*
|
||||
* At least one space followed by a tab
|
||||
@@ -89,24 +68,6 @@ module.exports = {
|
||||
* characters begin.
|
||||
*/
|
||||
let regex = /^(?=[\t ]*(\t | \t))/u;
|
||||
const lines = sourceCode.lines,
|
||||
comments = sourceCode.getAllComments();
|
||||
|
||||
comments.forEach(comment => {
|
||||
ignoredLocs.push(comment.loc);
|
||||
});
|
||||
|
||||
ignoredLocs.sort((first, second) => {
|
||||
if (beforeLoc(first, second.start.line, second.start.column)) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (beforeLoc(second, first.start.line, second.start.column)) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
});
|
||||
|
||||
if (smartTabs) {
|
||||
|
||||
@@ -122,25 +83,23 @@ module.exports = {
|
||||
|
||||
if (match) {
|
||||
const lineNumber = i + 1,
|
||||
column = match.index + 1;
|
||||
column = match.index + 1,
|
||||
loc = { line: lineNumber, column };
|
||||
|
||||
for (let j = 0; j < ignoredLocs.length; j++) {
|
||||
if (beforeLoc(ignoredLocs[j], lineNumber, column)) {
|
||||
continue;
|
||||
}
|
||||
if (afterLoc(ignoredLocs[j], lineNumber, column)) {
|
||||
continue;
|
||||
}
|
||||
if (!ignoredCommentLines.has(lineNumber)) {
|
||||
const containingNode = sourceCode.getNodeByRangeIndex(sourceCode.getIndexFromLoc(loc));
|
||||
|
||||
return;
|
||||
if (!(containingNode && ["Literal", "TemplateElement"].includes(containingNode.type))) {
|
||||
context.report({
|
||||
node,
|
||||
loc,
|
||||
messageId: "mixedSpacesAndTabs"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
context.report({ node, loc: { line: lineNumber, column }, message: "Mixed spaces and tabs." });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
};
|
||||
+6
-2
@@ -21,7 +21,11 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-multi-assign"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
unexpectedChain: "Unexpected chained assignment."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -35,7 +39,7 @@ module.exports = {
|
||||
if (["AssignmentExpression", "VariableDeclarator"].indexOf(node.parent.type) !== -1) {
|
||||
context.report({
|
||||
node,
|
||||
message: "Unexpected chained assignment."
|
||||
messageId: "unexpectedChain"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+6
-2
@@ -44,7 +44,11 @@ module.exports = {
|
||||
},
|
||||
additionalProperties: false
|
||||
}
|
||||
]
|
||||
],
|
||||
|
||||
messages: {
|
||||
multipleSpaces: "Multiple spaces found before '{{displayValue}}'."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -122,7 +126,7 @@ module.exports = {
|
||||
context.report({
|
||||
node: rightToken,
|
||||
loc: { start: leftToken.loc.end, end: rightToken.loc.start },
|
||||
message: "Multiple spaces found before '{{displayValue}}'.",
|
||||
messageId: "multipleSpaces",
|
||||
data: { displayValue },
|
||||
fix: fixer => fixer.replaceTextRange([leftToken.range[1], rightToken.range[0]], " ")
|
||||
});
|
||||
|
||||
+9
-2
@@ -26,7 +26,11 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-multi-str"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
multilineString: "Multiline support is limited to browsers supporting ES5 only."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -49,7 +53,10 @@ module.exports = {
|
||||
|
||||
Literal(node) {
|
||||
if (astUtils.LINEBREAK_MATCHER.test(node.raw) && !isJSXElement(node.parent)) {
|
||||
context.report({ node, message: "Multiline support is limited to browsers supporting ES5 only." });
|
||||
context.report({
|
||||
node,
|
||||
messageId: "multilineString"
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
+20
-8
@@ -42,7 +42,13 @@ module.exports = {
|
||||
required: ["max"],
|
||||
additionalProperties: false
|
||||
}
|
||||
]
|
||||
],
|
||||
|
||||
messages: {
|
||||
blankBeginningOfFile: "Too many blank lines at the beginning of file. Max of {{max}} allowed.",
|
||||
blankEndOfFile: "Too many blank lines at the end of file. Max of {{max}} allowed.",
|
||||
consecutiveBlank: "More than {{max}} blank {{pluralizedLines}} not allowed."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -94,25 +100,31 @@ module.exports = {
|
||||
|
||||
// Given two line numbers of non-empty lines, report the lines between if the difference is too large.
|
||||
.reduce((lastLineNumber, lineNumber) => {
|
||||
let message, maxAllowed;
|
||||
let messageId, maxAllowed;
|
||||
|
||||
if (lastLineNumber === 0) {
|
||||
message = "Too many blank lines at the beginning of file. Max of {{max}} allowed.";
|
||||
messageId = "blankBeginningOfFile";
|
||||
maxAllowed = maxBOF;
|
||||
} else if (lineNumber === allLines.length + 1) {
|
||||
message = "Too many blank lines at the end of file. Max of {{max}} allowed.";
|
||||
messageId = "blankEndOfFile";
|
||||
maxAllowed = maxEOF;
|
||||
} else {
|
||||
message = "More than {{max}} blank {{pluralizedLines}} not allowed.";
|
||||
messageId = "consecutiveBlank";
|
||||
maxAllowed = max;
|
||||
}
|
||||
|
||||
if (lineNumber - lastLineNumber - 1 > maxAllowed) {
|
||||
context.report({
|
||||
node,
|
||||
loc: { start: { line: lastLineNumber + maxAllowed + 1, column: 0 }, end: { line: lineNumber, column: 0 } },
|
||||
message,
|
||||
data: { max: maxAllowed, pluralizedLines: maxAllowed === 1 ? "line" : "lines" },
|
||||
loc: {
|
||||
start: { line: lastLineNumber + maxAllowed + 1, column: 0 },
|
||||
end: { line: lineNumber, column: 0 }
|
||||
},
|
||||
messageId,
|
||||
data: {
|
||||
max: maxAllowed,
|
||||
pluralizedLines: maxAllowed === 1 ? "line" : "lines"
|
||||
},
|
||||
fix(fixer) {
|
||||
const rangeStart = sourceCode.getIndexFromLoc({ line: lastLineNumber + 1, column: 0 });
|
||||
|
||||
|
||||
+13
-3
@@ -19,7 +19,11 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-negated-condition"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
unexpectedNegated: "Unexpected negated condition."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -72,12 +76,18 @@ module.exports = {
|
||||
}
|
||||
|
||||
if (isNegatedIf(node)) {
|
||||
context.report({ node, message: "Unexpected negated condition." });
|
||||
context.report({
|
||||
node,
|
||||
messageId: "unexpectedNegated"
|
||||
});
|
||||
}
|
||||
},
|
||||
ConditionalExpression(node) {
|
||||
if (isNegatedIf(node)) {
|
||||
context.report({ node, message: "Unexpected negated condition." });
|
||||
context.report({
|
||||
node,
|
||||
messageId: "unexpectedNegated"
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
+9
-2
@@ -20,7 +20,11 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-nested-ternary"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
noNestedTernary: "Do not nest ternary expressions."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -29,7 +33,10 @@ module.exports = {
|
||||
ConditionalExpression(node) {
|
||||
if (node.alternate.type === "ConditionalExpression" ||
|
||||
node.consequent.type === "ConditionalExpression") {
|
||||
context.report({ node, message: "Do not nest ternary expressions." });
|
||||
context.report({
|
||||
node,
|
||||
messageId: "noNestedTernary"
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
+9
-2
@@ -20,7 +20,11 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-new-func"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
noFunctionConstructor: "The Function constructor is eval."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -36,7 +40,10 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function report(node) {
|
||||
context.report({ node, message: "The Function constructor is eval." });
|
||||
context.report({
|
||||
node,
|
||||
messageId: "noFunctionConstructor"
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
+9
-2
@@ -20,7 +20,11 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-new-object"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
preferLiteral: "The object literal notation {} is preferrable."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -29,7 +33,10 @@ module.exports = {
|
||||
|
||||
NewExpression(node) {
|
||||
if (node.callee.name === "Object") {
|
||||
context.report({ node, message: "The object literal notation {} is preferrable." });
|
||||
context.report({
|
||||
node,
|
||||
messageId: "preferLiteral"
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
+9
-2
@@ -20,7 +20,11 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-new-require"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
noNewRequire: "Unexpected use of new with require."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -29,7 +33,10 @@ module.exports = {
|
||||
|
||||
NewExpression(node) {
|
||||
if (node.callee.type === "Identifier" && node.callee.name === "require") {
|
||||
context.report({ node, message: "Unexpected use of new with require." });
|
||||
context.report({
|
||||
node,
|
||||
messageId: "noNewRequire"
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
+9
-2
@@ -20,7 +20,11 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-new-symbol"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
noNewSymbol: "`Symbol` cannot be called as a constructor."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -35,7 +39,10 @@ module.exports = {
|
||||
const node = ref.identifier;
|
||||
|
||||
if (node.parent && node.parent.type === "NewExpression") {
|
||||
context.report({ node, message: "`Symbol` cannot be called as a constructor." });
|
||||
context.report({
|
||||
node,
|
||||
messageId: "noNewSymbol"
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+10
-2
@@ -20,7 +20,11 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-new-wrappers"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
noConstructor: "Do not use {{fn}} as a constructor."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -31,7 +35,11 @@ module.exports = {
|
||||
const wrapperObjects = ["String", "Number", "Boolean", "Math", "JSON"];
|
||||
|
||||
if (wrapperObjects.indexOf(node.callee.name) > -1) {
|
||||
context.report({ node, message: "Do not use {{fn}} as a constructor.", data: { fn: node.callee.name } });
|
||||
context.report({
|
||||
node,
|
||||
messageId: "noConstructor",
|
||||
data: { fn: node.callee.name }
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
+9
-2
@@ -21,14 +21,21 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-new"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
noNewStatement: "Do not use 'new' for side effects."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
|
||||
return {
|
||||
"ExpressionStatement > NewExpression"(node) {
|
||||
context.report({ node: node.parent, message: "Do not use 'new' for side effects." });
|
||||
context.report({
|
||||
node: node.parent,
|
||||
messageId: "noNewStatement"
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+9
-2
@@ -20,7 +20,11 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-octal"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
noOcatal: "Octal literals should not be used."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -29,7 +33,10 @@ module.exports = {
|
||||
|
||||
Literal(node) {
|
||||
if (typeof node.value === "number" && /^0[0-9]/u.test(node.raw)) {
|
||||
context.report({ node, message: "Octal literals should not be used." });
|
||||
context.report({
|
||||
node,
|
||||
messageId: "noOcatal"
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
+16
-3
@@ -58,7 +58,12 @@ module.exports = {
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
],
|
||||
|
||||
messages: {
|
||||
assignmentToFunctionParam: "Assignment to function parameter '{{name}}'.",
|
||||
assignmentToFunctionParamProp: "Assignment to property of function parameter '{{name}}'."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -177,9 +182,17 @@ module.exports = {
|
||||
(index === 0 || references[index - 1].identifier !== identifier)
|
||||
) {
|
||||
if (reference.isWrite()) {
|
||||
context.report({ node: identifier, message: "Assignment to function parameter '{{name}}'.", data: { name: identifier.name } });
|
||||
context.report({
|
||||
node: identifier,
|
||||
messageId: "assignmentToFunctionParam",
|
||||
data: { name: identifier.name }
|
||||
});
|
||||
} else if (props && isModifyingProp(reference) && !isIgnoredPropertyAssignment(identifier.name)) {
|
||||
context.report({ node: identifier, message: "Assignment to property of function parameter '{{name}}'.", data: { name: identifier.name } });
|
||||
context.report({
|
||||
node: identifier,
|
||||
messageId: "assignmentToFunctionParamProp",
|
||||
data: { name: identifier.name }
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
-2
@@ -19,7 +19,11 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-path-concat"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
usePathFunctions: "Use path.join() or path.resolve() instead of + to create paths."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -42,7 +46,10 @@ module.exports = {
|
||||
(right.type === "Identifier" && MATCHER.test(right.name)))
|
||||
) {
|
||||
|
||||
context.report({ node, message: "Use path.join() or path.resolve() instead of + to create paths." });
|
||||
context.report({
|
||||
node,
|
||||
messageId: "usePathFunctions"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+6
-2
@@ -32,7 +32,11 @@ module.exports = {
|
||||
},
|
||||
additionalProperties: false
|
||||
}
|
||||
]
|
||||
],
|
||||
|
||||
messages: {
|
||||
unexpectedUnaryOp: "Unary operator '{{operator}}' used."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -52,7 +56,7 @@ module.exports = {
|
||||
}
|
||||
context.report({
|
||||
node,
|
||||
message: "Unary operator '{{operator}}' used.",
|
||||
messageId: "unexpectedUnaryOp",
|
||||
data: {
|
||||
operator: node.operator
|
||||
}
|
||||
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* @fileoverview Rule to disallow specified names in exports
|
||||
* @author Milos Djermanovic
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "suggestion",
|
||||
|
||||
docs: {
|
||||
description: "disallow specified names in exports",
|
||||
category: "ECMAScript 6",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/no-restricted-exports"
|
||||
},
|
||||
|
||||
schema: [{
|
||||
type: "object",
|
||||
properties: {
|
||||
restrictedNamedExports: {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "string"
|
||||
},
|
||||
uniqueItems: true
|
||||
}
|
||||
},
|
||||
additionalProperties: false
|
||||
}],
|
||||
|
||||
messages: {
|
||||
restrictedNamed: "'{{name}}' is restricted from being used as an exported name."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
|
||||
const restrictedNames = new Set(context.options[0] && context.options[0].restrictedNamedExports);
|
||||
|
||||
/**
|
||||
* Checks and reports given exported identifier.
|
||||
* @param {ASTNode} node exported `Identifer` node to check.
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkExportedName(node) {
|
||||
const name = node.name;
|
||||
|
||||
if (restrictedNames.has(name)) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "restrictedNamed",
|
||||
data: { name }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
ExportNamedDeclaration(node) {
|
||||
const declaration = node.declaration;
|
||||
|
||||
if (declaration) {
|
||||
if (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration") {
|
||||
checkExportedName(declaration.id);
|
||||
} else if (declaration.type === "VariableDeclaration") {
|
||||
context.getDeclaredVariables(declaration)
|
||||
.map(v => v.defs.find(d => d.parent === declaration))
|
||||
.map(d => d.name) // Identifier nodes
|
||||
.forEach(checkExportedName);
|
||||
}
|
||||
} else {
|
||||
node.specifiers
|
||||
.map(s => s.exported)
|
||||
.forEach(checkExportedName);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
+10
-11
@@ -4,13 +4,6 @@
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const DEFAULT_MESSAGE_TEMPLATE = "Unexpected use of '{{name}}'.",
|
||||
CUSTOM_MESSAGE_TEMPLATE = "Unexpected use of '{{name}}'. {{customMessage}}";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -46,6 +39,12 @@ module.exports = {
|
||||
},
|
||||
uniqueItems: true,
|
||||
minItems: 0
|
||||
},
|
||||
|
||||
messages: {
|
||||
defaultMessage: "Unexpected use of '{{name}}'.",
|
||||
// eslint-disable-next-line eslint-plugin/report-message-format
|
||||
customMessage: "Unexpected use of '{{name}}'. {{customMessage}}"
|
||||
}
|
||||
},
|
||||
|
||||
@@ -75,13 +74,13 @@ module.exports = {
|
||||
function reportReference(reference) {
|
||||
const name = reference.identifier.name,
|
||||
customMessage = restrictedGlobalMessages[name],
|
||||
message = customMessage
|
||||
? CUSTOM_MESSAGE_TEMPLATE
|
||||
: DEFAULT_MESSAGE_TEMPLATE;
|
||||
messageId = customMessage
|
||||
? "customMessage"
|
||||
: "defaultMessage";
|
||||
|
||||
context.report({
|
||||
node: reference.identifier,
|
||||
message,
|
||||
messageId,
|
||||
data: {
|
||||
name,
|
||||
customMessage
|
||||
|
||||
+93
-111
@@ -64,7 +64,11 @@ module.exports = {
|
||||
|
||||
everything: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted.",
|
||||
// eslint-disable-next-line eslint-plugin/report-message-format
|
||||
everythingWithCustomMessage: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted. {{customMessage}}"
|
||||
everythingWithCustomMessage: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted. {{customMessage}}",
|
||||
|
||||
importName: "'{{importName}}' import from '{{importSource}}' is restricted.",
|
||||
// eslint-disable-next-line eslint-plugin/report-message-format
|
||||
importNameWithCustomMessage: "'{{importName}}' import from '{{importSource}}' is restricted. {{customMessage}}"
|
||||
},
|
||||
|
||||
schema: {
|
||||
@@ -87,6 +91,7 @@ module.exports = {
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const sourceCode = context.getSourceCode();
|
||||
const options = Array.isArray(context.options) ? context.options : [];
|
||||
const isPathAndPatternsObject =
|
||||
typeof options[0] === "object" &&
|
||||
@@ -95,6 +100,11 @@ module.exports = {
|
||||
const restrictedPaths = (isPathAndPatternsObject ? options[0].paths : context.options) || [];
|
||||
const restrictedPatterns = (isPathAndPatternsObject ? options[0].patterns : []) || [];
|
||||
|
||||
// if no imports are restricted we don"t need to check
|
||||
if (Object.keys(restrictedPaths).length === 0 && restrictedPatterns.length === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const restrictedPathMessages = restrictedPaths.reduce((memo, importSource) => {
|
||||
if (typeof importSource === "string") {
|
||||
memo[importSource] = { message: null };
|
||||
@@ -107,40 +117,68 @@ module.exports = {
|
||||
return memo;
|
||||
}, {});
|
||||
|
||||
// if no imports are restricted we don"t need to check
|
||||
if (Object.keys(restrictedPaths).length === 0 && restrictedPatterns.length === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const restrictedPatternsMatcher = ignore().add(restrictedPatterns);
|
||||
|
||||
/**
|
||||
* Checks to see if "*" is being used to import everything.
|
||||
* @param {Set.<string>} importNames Set of import names that are being imported
|
||||
* @returns {boolean} whether everything is imported or not
|
||||
*/
|
||||
function isEverythingImported(importNames) {
|
||||
return importNames.has("*");
|
||||
}
|
||||
|
||||
/**
|
||||
* Report a restricted path.
|
||||
* @param {string} importSource path of the import
|
||||
* @param {Map<string,Object[]>} importNames Map of import names that are being imported
|
||||
* @param {node} node representing the restricted path reference
|
||||
* @returns {void}
|
||||
* @private
|
||||
*/
|
||||
function reportPath(node) {
|
||||
const importSource = node.source.value.trim();
|
||||
const customMessage = restrictedPathMessages[importSource] && restrictedPathMessages[importSource].message;
|
||||
function checkRestrictedPathAndReport(importSource, importNames, node) {
|
||||
if (!Object.prototype.hasOwnProperty.call(restrictedPathMessages, importSource)) {
|
||||
return;
|
||||
}
|
||||
|
||||
context.report({
|
||||
node,
|
||||
messageId: customMessage ? "pathWithCustomMessage" : "path",
|
||||
data: {
|
||||
importSource,
|
||||
customMessage
|
||||
const customMessage = restrictedPathMessages[importSource].message;
|
||||
const restrictedImportNames = restrictedPathMessages[importSource].importNames;
|
||||
|
||||
if (restrictedImportNames) {
|
||||
if (importNames.has("*")) {
|
||||
const specifierData = importNames.get("*")[0];
|
||||
|
||||
context.report({
|
||||
node,
|
||||
messageId: customMessage ? "everythingWithCustomMessage" : "everything",
|
||||
loc: specifierData.loc,
|
||||
data: {
|
||||
importSource,
|
||||
importNames: restrictedImportNames,
|
||||
customMessage
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
restrictedImportNames.forEach(importName => {
|
||||
if (importNames.has(importName)) {
|
||||
const specifiers = importNames.get(importName);
|
||||
|
||||
specifiers.forEach(specifier => {
|
||||
context.report({
|
||||
node,
|
||||
messageId: customMessage ? "importNameWithCustomMessage" : "importName",
|
||||
loc: specifier.loc,
|
||||
data: {
|
||||
importSource,
|
||||
customMessage,
|
||||
importName
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
} else {
|
||||
context.report({
|
||||
node,
|
||||
messageId: customMessage ? "pathWithCustomMessage" : "path",
|
||||
data: {
|
||||
importSource,
|
||||
customMessage
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -161,75 +199,6 @@ module.exports = {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Report a restricted path specifically when using the '*' import.
|
||||
* @param {string} importSource path of the import
|
||||
* @param {node} node representing the restricted path reference
|
||||
* @returns {void}
|
||||
* @private
|
||||
*/
|
||||
function reportPathForEverythingImported(importSource, node) {
|
||||
const importNames = restrictedPathMessages[importSource].importNames;
|
||||
const customMessage = restrictedPathMessages[importSource] && restrictedPathMessages[importSource].message;
|
||||
|
||||
context.report({
|
||||
node,
|
||||
messageId: customMessage ? "everythingWithCustomMessage" : "everything",
|
||||
data: {
|
||||
importSource,
|
||||
importNames,
|
||||
customMessage
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given importSource is restricted because '*' is being imported.
|
||||
* @param {string} importSource path of the import
|
||||
* @param {Set.<string>} importNames Set of import names that are being imported
|
||||
* @returns {boolean} whether the path is restricted
|
||||
* @private
|
||||
*/
|
||||
function isRestrictedForEverythingImported(importSource, importNames) {
|
||||
return Object.prototype.hasOwnProperty.call(restrictedPathMessages, importSource) &&
|
||||
restrictedPathMessages[importSource].importNames &&
|
||||
isEverythingImported(importNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given importNames are restricted given a list of restrictedImportNames.
|
||||
* @param {Set.<string>} importNames Set of import names that are being imported
|
||||
* @param {string[]} restrictedImportNames array of import names that are restricted for this import
|
||||
* @returns {boolean} whether the objectName is restricted
|
||||
* @private
|
||||
*/
|
||||
function isRestrictedObject(importNames, restrictedImportNames) {
|
||||
return restrictedImportNames.some(restrictedObjectName => (
|
||||
importNames.has(restrictedObjectName)
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given importSource is a restricted path.
|
||||
* @param {string} importSource path of the import
|
||||
* @param {Set.<string>} importNames Set of import names that are being imported
|
||||
* @returns {boolean} whether the variable is a restricted path or not
|
||||
* @private
|
||||
*/
|
||||
function isRestrictedPath(importSource, importNames) {
|
||||
let isRestricted = false;
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(restrictedPathMessages, importSource)) {
|
||||
if (restrictedPathMessages[importSource].importNames) {
|
||||
isRestricted = isRestrictedObject(importNames, restrictedPathMessages[importSource].importNames);
|
||||
} else {
|
||||
isRestricted = true;
|
||||
}
|
||||
}
|
||||
|
||||
return isRestricted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given importSource is restricted by a pattern.
|
||||
* @param {string} importSource path of the import
|
||||
@@ -248,26 +217,39 @@ module.exports = {
|
||||
*/
|
||||
function checkNode(node) {
|
||||
const importSource = node.source.value.trim();
|
||||
const importNames = node.specifiers ? node.specifiers.reduce((set, specifier) => {
|
||||
if (specifier.type === "ImportDefaultSpecifier") {
|
||||
set.add("default");
|
||||
} else if (specifier.type === "ImportNamespaceSpecifier") {
|
||||
set.add("*");
|
||||
} else if (specifier.imported) {
|
||||
set.add(specifier.imported.name);
|
||||
} else if (specifier.local) {
|
||||
set.add(specifier.local.name);
|
||||
const importNames = new Map();
|
||||
|
||||
if (node.type === "ExportAllDeclaration") {
|
||||
const starToken = sourceCode.getFirstToken(node, 1);
|
||||
|
||||
importNames.set("*", [{ loc: starToken.loc }]);
|
||||
} else if (node.specifiers) {
|
||||
for (const specifier of node.specifiers) {
|
||||
let name;
|
||||
const specifierData = { loc: specifier.loc };
|
||||
|
||||
if (specifier.type === "ImportDefaultSpecifier") {
|
||||
name = "default";
|
||||
} else if (specifier.type === "ImportNamespaceSpecifier") {
|
||||
name = "*";
|
||||
} else if (specifier.imported) {
|
||||
name = specifier.imported.name;
|
||||
} else if (specifier.local) {
|
||||
name = specifier.local.name;
|
||||
}
|
||||
|
||||
if (name) {
|
||||
if (importNames.has(name)) {
|
||||
importNames.get(name).push(specifierData);
|
||||
} else {
|
||||
importNames.set(name, [specifierData]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return set;
|
||||
}, new Set()) : new Set();
|
||||
|
||||
if (isRestrictedForEverythingImported(importSource, importNames)) {
|
||||
reportPathForEverythingImported(importSource, node);
|
||||
}
|
||||
|
||||
if (isRestrictedPath(importSource, importNames)) {
|
||||
reportPath(node);
|
||||
}
|
||||
checkRestrictedPathAndReport(importSource, importNames, node);
|
||||
|
||||
if (isRestrictedPattern(importSource)) {
|
||||
reportPathForPatterns(node);
|
||||
}
|
||||
|
||||
+6
-2
@@ -41,7 +41,11 @@ module.exports = {
|
||||
},
|
||||
additionalProperties: false
|
||||
}
|
||||
]
|
||||
],
|
||||
|
||||
messages: {
|
||||
noShadow: "'{{name}}' is already declared in the upper scope."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -163,7 +167,7 @@ module.exports = {
|
||||
) {
|
||||
context.report({
|
||||
node: variable.identifiers[0],
|
||||
message: "'{{name}}' is already declared in the upper scope.",
|
||||
messageId: "noShadow",
|
||||
data: variable
|
||||
});
|
||||
}
|
||||
|
||||
+6
-2
@@ -157,7 +157,11 @@ module.exports = {
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
],
|
||||
|
||||
messages: {
|
||||
usedBeforeDefined: "'{{name}}' was used before it was defined."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -212,7 +216,7 @@ module.exports = {
|
||||
// Reports.
|
||||
context.report({
|
||||
node: reference.identifier,
|
||||
message: "'{{name}}' was used before it was defined.",
|
||||
messageId: "usedBeforeDefined",
|
||||
data: reference.identifier
|
||||
});
|
||||
});
|
||||
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* @fileoverview Rule to disallow useless backreferences in regular expressions
|
||||
* @author Milos Djermanovic
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const { CALL, CONSTRUCT, ReferenceTracker, getStringIfConstant } = require("eslint-utils");
|
||||
const { RegExpParser, visitRegExpAST } = require("regexpp");
|
||||
const lodash = require("lodash");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const parser = new RegExpParser();
|
||||
|
||||
/**
|
||||
* Finds the path from the given `regexpp` AST node to the root node.
|
||||
* @param {regexpp.Node} node Node.
|
||||
* @returns {regexpp.Node[]} Array that starts with the given node and ends with the root node.
|
||||
*/
|
||||
function getPathToRoot(node) {
|
||||
const path = [];
|
||||
let current = node;
|
||||
|
||||
do {
|
||||
path.push(current);
|
||||
current = current.parent;
|
||||
} while (current);
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the given `regexpp` AST node is a lookaround node.
|
||||
* @param {regexpp.Node} node Node.
|
||||
* @returns {boolean} `true` if it is a lookaround node.
|
||||
*/
|
||||
function isLookaround(node) {
|
||||
return node.type === "Assertion" &&
|
||||
(node.kind === "lookahead" || node.kind === "lookbehind");
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the given `regexpp` AST node is a negative lookaround node.
|
||||
* @param {regexpp.Node} node Node.
|
||||
* @returns {boolean} `true` if it is a negative lookaround node.
|
||||
*/
|
||||
function isNegativeLookaround(node) {
|
||||
return isLookaround(node) && node.negate;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "problem",
|
||||
|
||||
docs: {
|
||||
description: "disallow useless backreferences in regular expressions",
|
||||
category: "Possible Errors",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/no-useless-backreference"
|
||||
},
|
||||
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
nested: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' from within that group.",
|
||||
forward: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' which appears later in the pattern.",
|
||||
backward: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' which appears before in the same lookbehind.",
|
||||
disjunctive: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' which is in another alternative.",
|
||||
intoNegativeLookaround: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' which is in a negative lookaround."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
|
||||
/**
|
||||
* Checks and reports useless backreferences in the given regular expression.
|
||||
* @param {ASTNode} node Node that represents regular expression. A regex literal or RegExp constructor call.
|
||||
* @param {string} pattern Regular expression pattern.
|
||||
* @param {string} flags Regular expression flags.
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkRegex(node, pattern, flags) {
|
||||
let regExpAST;
|
||||
|
||||
try {
|
||||
regExpAST = parser.parsePattern(pattern, 0, pattern.length, flags.includes("u"));
|
||||
} catch (e) {
|
||||
|
||||
// Ignore regular expressions with syntax errors
|
||||
return;
|
||||
}
|
||||
|
||||
visitRegExpAST(regExpAST, {
|
||||
onBackreferenceEnter(bref) {
|
||||
const group = bref.resolved,
|
||||
brefPath = getPathToRoot(bref),
|
||||
groupPath = getPathToRoot(group);
|
||||
let messageId = null;
|
||||
|
||||
if (brefPath.includes(group)) {
|
||||
|
||||
// group is bref's ancestor => bref is nested ('nested reference') => group hasn't matched yet when bref starts to match.
|
||||
messageId = "nested";
|
||||
} else {
|
||||
|
||||
// Start from the root to find the lowest common ancestor.
|
||||
let i = brefPath.length - 1,
|
||||
j = groupPath.length - 1;
|
||||
|
||||
do {
|
||||
i--;
|
||||
j--;
|
||||
} while (brefPath[i] === groupPath[j]);
|
||||
|
||||
const indexOfLowestCommonAncestor = j + 1,
|
||||
groupCut = groupPath.slice(0, indexOfLowestCommonAncestor),
|
||||
commonPath = groupPath.slice(indexOfLowestCommonAncestor),
|
||||
lowestCommonLookaround = commonPath.find(isLookaround),
|
||||
isMatchingBackward = lowestCommonLookaround && lowestCommonLookaround.kind === "lookbehind";
|
||||
|
||||
if (!isMatchingBackward && bref.end <= group.start) {
|
||||
|
||||
// bref is left, group is right ('forward reference') => group hasn't matched yet when bref starts to match.
|
||||
messageId = "forward";
|
||||
} else if (isMatchingBackward && group.end <= bref.start) {
|
||||
|
||||
// the opposite of the previous when the regex is matching backward in a lookbehind context.
|
||||
messageId = "backward";
|
||||
} else if (lodash.last(groupCut).type === "Alternative") {
|
||||
|
||||
// group's and bref's ancestor nodes below the lowest common ancestor are sibling alternatives => they're disjunctive.
|
||||
messageId = "disjunctive";
|
||||
} else if (groupCut.some(isNegativeLookaround)) {
|
||||
|
||||
// group is in a negative lookaround which isn't bref's ancestor => group has already failed when bref starts to match.
|
||||
messageId = "intoNegativeLookaround";
|
||||
}
|
||||
}
|
||||
|
||||
if (messageId) {
|
||||
context.report({
|
||||
node,
|
||||
messageId,
|
||||
data: {
|
||||
bref: bref.raw,
|
||||
group: group.raw
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
"Literal[regex]"(node) {
|
||||
const { pattern, flags } = node.regex;
|
||||
|
||||
checkRegex(node, pattern, flags);
|
||||
},
|
||||
Program() {
|
||||
const scope = context.getScope(),
|
||||
tracker = new ReferenceTracker(scope),
|
||||
traceMap = {
|
||||
RegExp: {
|
||||
[CALL]: true,
|
||||
[CONSTRUCT]: true
|
||||
}
|
||||
};
|
||||
|
||||
for (const { node } of tracker.iterateGlobalReferences(traceMap)) {
|
||||
const [patternNode, flagsNode] = node.arguments,
|
||||
pattern = getStringIfConstant(patternNode, scope),
|
||||
flags = getStringIfConstant(flagsNode, scope);
|
||||
|
||||
if (typeof pattern === "string") {
|
||||
checkRegex(node, pattern, flags || "");
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
+4
-7
@@ -71,14 +71,11 @@ module.exports = {
|
||||
message: MESSAGE_UNNECESSARY_COMPUTED,
|
||||
data: { property: sourceCode.getText(key) },
|
||||
fix(fixer) {
|
||||
const leftSquareBracket = sourceCode.getFirstToken(node, astUtils.isOpeningBracketToken);
|
||||
const rightSquareBracket = sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isClosingBracketToken);
|
||||
const tokensBetween = sourceCode.getTokensBetween(leftSquareBracket, rightSquareBracket, 1);
|
||||
const leftSquareBracket = sourceCode.getTokenBefore(key, astUtils.isOpeningBracketToken);
|
||||
const rightSquareBracket = sourceCode.getTokenAfter(key, astUtils.isClosingBracketToken);
|
||||
|
||||
if (tokensBetween.slice(0, -1).some((token, index) =>
|
||||
sourceCode.getText().slice(token.range[1], tokensBetween[index + 1].range[0]).trim())) {
|
||||
|
||||
// If there are comments between the brackets and the property name, don't do a fix.
|
||||
// If there are comments between the brackets and the property name, don't do a fix.
|
||||
if (sourceCode.commentsExistBetween(leftSquareBracket, rightSquareBracket)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
+6
-2
@@ -143,7 +143,11 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-useless-constructor"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
noUselessConstructor: "Useless constructor."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -165,7 +169,7 @@ module.exports = {
|
||||
if (superClass ? isRedundantSuperCall(body, ctorParams) : (body.length === 0)) {
|
||||
context.report({
|
||||
node,
|
||||
message: "Useless constructor."
|
||||
messageId: "noUselessConstructor"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+29
-5
@@ -19,22 +19,46 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/no-void"
|
||||
},
|
||||
|
||||
schema: []
|
||||
messages: {
|
||||
noVoid: "Expected 'undefined' and instead saw 'void'."
|
||||
},
|
||||
|
||||
schema: [
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
allowAsStatement: {
|
||||
type: "boolean",
|
||||
default: false
|
||||
}
|
||||
},
|
||||
additionalProperties: false
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const allowAsStatement =
|
||||
context.options[0] && context.options[0].allowAsStatement;
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Public
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
return {
|
||||
UnaryExpression(node) {
|
||||
if (node.operator === "void") {
|
||||
context.report({ node, message: "Expected 'undefined' and instead saw 'void'." });
|
||||
'UnaryExpression[operator="void"]'(node) {
|
||||
if (
|
||||
allowAsStatement &&
|
||||
node.parent &&
|
||||
node.parent.type === "ExpressionStatement"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
context.report({
|
||||
node,
|
||||
messageId: "noVoid"
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
};
|
||||
+35
-1
@@ -25,6 +25,36 @@ function hasArraySpread(node) {
|
||||
return node.arguments.some(arg => arg.type === "SpreadElement");
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the given node is an accessor property (getter/setter).
|
||||
* @param {ASTNode} node Node to check.
|
||||
* @returns {boolean} `true` if the node is a getter or a setter.
|
||||
*/
|
||||
function isAccessorProperty(node) {
|
||||
return node.type === "Property" &&
|
||||
(node.kind === "get" || node.kind === "set");
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the given object expression node has accessor properties (getters/setters).
|
||||
* @param {ASTNode} node `ObjectExpression` node to check.
|
||||
* @returns {boolean} `true` if the node has at least one getter/setter.
|
||||
*/
|
||||
function hasAccessors(node) {
|
||||
return node.properties.some(isAccessorProperty);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the given call expression node has object expression arguments with accessor properties (getters/setters).
|
||||
* @param {ASTNode} node `CallExpression` node to check.
|
||||
* @returns {boolean} `true` if the node has at least one argument that is an object expression with at least one getter/setter.
|
||||
*/
|
||||
function hasArgumentsWithAccessors(node) {
|
||||
return node.arguments
|
||||
.filter(arg => arg.type === "ObjectExpression")
|
||||
.some(hasAccessors);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper that checks if the node needs parentheses to be valid JS.
|
||||
* The default is to wrap the node in parentheses to avoid parsing errors.
|
||||
@@ -249,7 +279,11 @@ module.exports = {
|
||||
if (
|
||||
node.arguments.length >= 1 &&
|
||||
node.arguments[0].type === "ObjectExpression" &&
|
||||
!hasArraySpread(node)
|
||||
!hasArraySpread(node) &&
|
||||
!(
|
||||
node.arguments.length > 1 &&
|
||||
hasArgumentsWithAccessors(node)
|
||||
)
|
||||
) {
|
||||
const messageId = node.arguments.length === 1
|
||||
? "useLiteralMessage"
|
||||
|
||||
+4
-3
@@ -8,8 +8,9 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const espree = require("espree"),
|
||||
keywords = require("./utils/keywords");
|
||||
const espree = require("espree");
|
||||
const astUtils = require("./utils/ast-utils");
|
||||
const keywords = require("./utils/keywords");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
@@ -177,7 +178,7 @@ module.exports = {
|
||||
data: { property: key.name },
|
||||
fix: fixer => fixer.replaceText(key, getQuotedKey(key))
|
||||
});
|
||||
} else if (NUMBERS && key.type === "Literal" && typeof key.value === "number") {
|
||||
} else if (NUMBERS && key.type === "Literal" && astUtils.isNumericLiteral(key)) {
|
||||
context.report({
|
||||
node,
|
||||
message: MESSAGE_NUMERIC,
|
||||
|
||||
+7
-3
@@ -110,7 +110,11 @@ module.exports = {
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
],
|
||||
|
||||
messages: {
|
||||
wrongQuotes: "Strings must use {{description}}."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -273,7 +277,7 @@ module.exports = {
|
||||
if (!isValid) {
|
||||
context.report({
|
||||
node,
|
||||
message: "Strings must use {{description}}.",
|
||||
messageId: "wrongQuotes",
|
||||
data: {
|
||||
description: settings.description
|
||||
},
|
||||
@@ -304,7 +308,7 @@ module.exports = {
|
||||
|
||||
context.report({
|
||||
node,
|
||||
message: "Strings must use {{description}}.",
|
||||
messageId: "wrongQuotes",
|
||||
data: {
|
||||
description: settings.description
|
||||
},
|
||||
|
||||
+6
-2
@@ -39,7 +39,11 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/require-await"
|
||||
},
|
||||
|
||||
schema: []
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
missingAwait: "{{name}} has no 'await' expression."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
@@ -68,7 +72,7 @@ module.exports = {
|
||||
context.report({
|
||||
node,
|
||||
loc: astUtils.getFunctionHeadLoc(node, sourceCode),
|
||||
message: "{{name}} has no 'await' expression.",
|
||||
messageId: "missingAwait",
|
||||
data: {
|
||||
name: capitalizeFirstLetter(
|
||||
astUtils.getFunctionNameWithKind(node)
|
||||
|
||||
+9
-4
@@ -67,6 +67,11 @@ module.exports = {
|
||||
maxItems: 2
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
messages: {
|
||||
missingSemi: "Missing semicolon.",
|
||||
extraSemi: "Extra semicolon."
|
||||
}
|
||||
},
|
||||
|
||||
@@ -91,12 +96,12 @@ module.exports = {
|
||||
*/
|
||||
function report(node, missing) {
|
||||
const lastToken = sourceCode.getLastToken(node);
|
||||
let message,
|
||||
let messageId,
|
||||
fix,
|
||||
loc;
|
||||
|
||||
if (!missing) {
|
||||
message = "Missing semicolon.";
|
||||
messageId = "missingSemi";
|
||||
loc = {
|
||||
start: lastToken.loc.end,
|
||||
end: astUtils.getNextLocation(sourceCode, lastToken.loc.end)
|
||||
@@ -105,7 +110,7 @@ module.exports = {
|
||||
return fixer.insertTextAfter(lastToken, ";");
|
||||
};
|
||||
} else {
|
||||
message = "Extra semicolon.";
|
||||
messageId = "extraSemi";
|
||||
loc = lastToken.loc;
|
||||
fix = function(fixer) {
|
||||
|
||||
@@ -123,7 +128,7 @@ module.exports = {
|
||||
context.report({
|
||||
node,
|
||||
loc,
|
||||
message,
|
||||
messageId,
|
||||
fix
|
||||
});
|
||||
|
||||
|
||||
+2
-2
@@ -57,7 +57,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkSpacingBefore(token) {
|
||||
const prevToken = sourceCode.getTokenBefore(token);
|
||||
const prevToken = sourceCode.getTokenBefore(token, { includeComments: true });
|
||||
|
||||
if (prevToken &&
|
||||
CLOSE_PAREN.test(token.value) &&
|
||||
@@ -86,7 +86,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkSpacingAfter(token) {
|
||||
const nextToken = sourceCode.getTokenAfter(token);
|
||||
const nextToken = sourceCode.getTokenAfter(token, { includeComments: true });
|
||||
|
||||
if (nextToken &&
|
||||
OPEN_PAREN.test(token.value) &&
|
||||
|
||||
+59
-16
@@ -865,6 +865,47 @@ module.exports = {
|
||||
return isFunction(node) && module.exports.isEmptyBlock(node.body);
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the result of the string conversion applied to the evaluated value of the given expression node,
|
||||
* if it can be determined statically.
|
||||
*
|
||||
* This function returns a `string` value for all `Literal` nodes and simple `TemplateLiteral` nodes only.
|
||||
* In all other cases, this function returns `null`.
|
||||
* @param {ASTNode} node Expression node.
|
||||
* @returns {string|null} String value if it can be determined. Otherwise, `null`.
|
||||
*/
|
||||
getStaticStringValue(node) {
|
||||
switch (node.type) {
|
||||
case "Literal":
|
||||
if (node.value === null) {
|
||||
if (module.exports.isNullLiteral(node)) {
|
||||
return String(node.value); // "null"
|
||||
}
|
||||
if (node.regex) {
|
||||
return `/${node.regex.pattern}/${node.regex.flags}`;
|
||||
}
|
||||
if (node.bigint) {
|
||||
return node.bigint;
|
||||
}
|
||||
|
||||
// Otherwise, this is an unknown literal. The function will return null.
|
||||
|
||||
} else {
|
||||
return String(node.value);
|
||||
}
|
||||
break;
|
||||
case "TemplateLiteral":
|
||||
if (node.expressions.length === 0 && node.quasis.length === 1) {
|
||||
return node.quasis[0].value.cooked;
|
||||
}
|
||||
break;
|
||||
|
||||
// no default
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Gets the property name of a given node.
|
||||
* The node can be a MemberExpression, a Property, or a MethodDefinition.
|
||||
@@ -911,23 +952,12 @@ module.exports = {
|
||||
// no default
|
||||
}
|
||||
|
||||
switch (prop && prop.type) {
|
||||
case "Literal":
|
||||
return String(prop.value);
|
||||
if (prop) {
|
||||
if (prop.type === "Identifier" && !node.computed) {
|
||||
return prop.name;
|
||||
}
|
||||
|
||||
case "TemplateLiteral":
|
||||
if (prop.expressions.length === 0 && prop.quasis.length === 1) {
|
||||
return prop.quasis[0].value.cooked;
|
||||
}
|
||||
break;
|
||||
|
||||
case "Identifier":
|
||||
if (!node.computed) {
|
||||
return prop.name;
|
||||
}
|
||||
break;
|
||||
|
||||
// no default
|
||||
return module.exports.getStaticStringValue(prop);
|
||||
}
|
||||
|
||||
return null;
|
||||
@@ -987,6 +1017,7 @@ module.exports = {
|
||||
* 0o5 // false
|
||||
* 5e0 // false
|
||||
* '5' // false
|
||||
* 5n // false
|
||||
*/
|
||||
isDecimalInteger(node) {
|
||||
return node.type === "Literal" && typeof node.value === "number" &&
|
||||
@@ -1306,6 +1337,18 @@ module.exports = {
|
||||
return node.type === "Literal" && node.value === null && !node.regex && !node.bigint;
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if a given node is a numeric literal or not.
|
||||
* @param {ASTNode} node The node to check.
|
||||
* @returns {boolean} `true` if the node is a number or bigint literal.
|
||||
*/
|
||||
isNumericLiteral(node) {
|
||||
return (
|
||||
node.type === "Literal" &&
|
||||
(typeof node.value === "number" || Boolean(node.bigint))
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* Determines whether two tokens can safely be placed next to each other without merging into a single token
|
||||
* @param {Token|string} leftValue The left token. If this is a string, it will be tokenized and the last token will be used.
|
||||
|
||||
+7
-7
@@ -1,13 +1,13 @@
|
||||
// THIS FILE WAS GENERATED BY 'tools/update-unicode-utils.js'
|
||||
/**
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
const combiningChars = new Set([768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809,810,811,812,813,814,815,816,817,818,819,820,821,822,823,824,825,826,827,828,829,830,831,832,833,834,835,836,837,838,839,840,841,842,843,844,845,846,847,848,849,850,851,852,853,854,855,856,857,858,859,860,861,862,863,864,865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,1155,1156,1157,1158,1159,1160,1161,1425,1426,1427,1428,1429,1430,1431,1432,1433,1434,1435,1436,1437,1438,1439,1440,1441,1442,1443,1444,1445,1446,1447,1448,1449,1450,1451,1452,1453,1454,1455,1456,1457,1458,1459,1460,1461,1462,1463,1464,1465,1466,1467,1468,1469,1471,1473,1474,1476,1477,1479,1552,1553,1554,1555,1556,1557,1558,1559,1560,1561,1562,1611,1612,1613,1614,1615,1616,1617,1618,1619,1620,1621,1622,1623,1624,1625,1626,1627,1628,1629,1630,1631,1648,1750,1751,1752,1753,1754,1755,1756,1759,1760,1761,1762,1763,1764,1767,1768,1770,1771,1772,1773,1809,1840,1841,1842,1843,1844,1845,1846,1847,1848,1849,1850,1851,1852,1853,1854,1855,1856,1857,1858,1859,1860,1861,1862,1863,1864,1865,1866,1958,1959,1960,1961,1962,1963,1964,1965,1966,1967,1968,2027,2028,2029,2030,2031,2032,2033,2034,2035,2070,2071,2072,2073,2075,2076,2077,2078,2079,2080,2081,2082,2083,2085,2086,2087,2089,2090,2091,2092,2093,2137,2138,2139,2260,2261,2262,2263,2264,2265,2266,2267,2268,2269,2270,2271,2272,2273,2275,2276,2277,2278,2279,2280,2281,2282,2283,2284,2285,2286,2287,2288,2289,2290,2291,2292,2293,2294,2295,2296,2297,2298,2299,2300,2301,2302,2303,2304,2305,2306,2307,2362,2363,2364,2366,2367,2368,2369,2370,2371,2372,2373,2374,2375,2376,2377,2378,2379,2380,2381,2382,2383,2385,2386,2387,2388,2389,2390,2391,2402,2403,2433,2434,2435,2492,2494,2495,2496,2497,2498,2499,2500,2503,2504,2507,2508,2509,2519,2530,2531,2561,2562,2563,2620,2622,2623,2624,2625,2626,2631,2632,2635,2636,2637,2641,2672,2673,2677,2689,2690,2691,2748,2750,2751,2752,2753,2754,2755,2756,2757,2759,2760,2761,2763,2764,2765,2786,2787,2810,2811,2812,2813,2814,2815,2817,2818,2819,2876,2878,2879,2880,2881,2882,2883,2884,2887,2888,2891,2892,2893,2902,2903,2914,2915,2946,3006,3007,3008,3009,3010,3014,3015,3016,3018,3019,3020,3021,3031,3072,3073,3074,3075,3134,3135,3136,3137,3138,3139,3140,3142,3143,3144,3146,3147,3148,3149,3157,3158,3170,3171,3201,3202,3203,3260,3262,3263,3264,3265,3266,3267,3268,3270,3271,3272,3274,3275,3276,3277,3285,3286,3298,3299,3328,3329,3330,3331,3387,3388,3390,3391,3392,3393,3394,3395,3396,3398,3399,3400,3402,3403,3404,3405,3415,3426,3427,3458,3459,3530,3535,3536,3537,3538,3539,3540,3542,3544,3545,3546,3547,3548,3549,3550,3551,3570,3571,3633,3636,3637,3638,3639,3640,3641,3642,3655,3656,3657,3658,3659,3660,3661,3662,3761,3764,3765,3766,3767,3768,3769,3771,3772,3784,3785,3786,3787,3788,3789,3864,3865,3893,3895,3897,3902,3903,3953,3954,3955,3956,3957,3958,3959,3960,3961,3962,3963,3964,3965,3966,3967,3968,3969,3970,3971,3972,3974,3975,3981,3982,3983,3984,3985,3986,3987,3988,3989,3990,3991,3993,3994,3995,3996,3997,3998,3999,4000,4001,4002,4003,4004,4005,4006,4007,4008,4009,4010,4011,4012,4013,4014,4015,4016,4017,4018,4019,4020,4021,4022,4023,4024,4025,4026,4027,4028,4038,4139,4140,4141,4142,4143,4144,4145,4146,4147,4148,4149,4150,4151,4152,4153,4154,4155,4156,4157,4158,4182,4183,4184,4185,4190,4191,4192,4194,4195,4196,4199,4200,4201,4202,4203,4204,4205,4209,4210,4211,4212,4226,4227,4228,4229,4230,4231,4232,4233,4234,4235,4236,4237,4239,4250,4251,4252,4253,4957,4958,4959,5906,5907,5908,5938,5939,5940,5970,5971,6002,6003,6068,6069,6070,6071,6072,6073,6074,6075,6076,6077,6078,6079,6080,6081,6082,6083,6084,6085,6086,6087,6088,6089,6090,6091,6092,6093,6094,6095,6096,6097,6098,6099,6109,6155,6156,6157,6277,6278,6313,6432,6433,6434,6435,6436,6437,6438,6439,6440,6441,6442,6443,6448,6449,6450,6451,6452,6453,6454,6455,6456,6457,6458,6459,6679,6680,6681,6682,6683,6741,6742,6743,6744,6745,6746,6747,6748,6749,6750,6752,6753,6754,6755,6756,6757,6758,6759,6760,6761,6762,6763,6764,6765,6766,6767,6768,6769,6770,6771,6772,6773,6774,6775,6776,6777,6778,6779,6780,6783,6832,6833,6834,6835,6836,6837,6838,6839,6840,6841,6842,6843,6844,6845,6846,6912,6913,6914,6915,6916,6964,6965,6966,6967,6968,6969,6970,6971,6972,6973,6974,6975,6976,6977,6978,6979,6980,7019,7020,7021,7022,7023,7024,7025,7026,7027,7040,7041,7042,7073,7074,7075,7076,7077,7078,7079,7080,7081,7082,7083,7084,7085,7142,7143,7144,7145,7146,7147,7148,7149,7150,7151,7152,7153,7154,7155,7204,7205,7206,7207,7208,7209,7210,7211,7212,7213,7214,7215,7216,7217,7218,7219,7220,7221,7222,7223,7376,7377,7378,7380,7381,7382,7383,7384,7385,7386,7387,7388,7389,7390,7391,7392,7393,7394,7395,7396,7397,7398,7399,7400,7405,7410,7411,7412,7415,7416,7417,7616,7617,7618,7619,7620,7621,7622,7623,7624,7625,7626,7627,7628,7629,7630,7631,7632,7633,7634,7635,7636,7637,7638,7639,7640,7641,7642,7643,7644,7645,7646,7647,7648,7649,7650,7651,7652,7653,7654,7655,7656,7657,7658,7659,7660,7661,7662Line truncated
|
||||
|
||||
/**
|
||||
* Check whether a given character is a combining mark or not.
|
||||
* @param {number} c The character code to check.
|
||||
* @returns {boolean} `true` if the character belongs to the category, one of `Mc`, `Me`, and `Mn`.
|
||||
* @param {number} codePoint The character code to check.
|
||||
* @returns {boolean} `true` if the character belongs to the category, any of `Mc`, `Me`, and `Mn`.
|
||||
*/
|
||||
module.exports = function isCombiningCharacter(c) {
|
||||
return combiningChars.has(c);
|
||||
module.exports = function isCombiningCharacter(codePoint) {
|
||||
return /^[\p{Mc}\p{Me}\p{Mn}]$/u.test(String.fromCodePoint(codePoint));
|
||||
};
|
||||
+1
-2
@@ -53,8 +53,7 @@ function looksLikeLiteral(node) {
|
||||
return (node.type === "UnaryExpression" &&
|
||||
node.operator === "-" &&
|
||||
node.prefix &&
|
||||
node.argument.type === "Literal" &&
|
||||
typeof node.argument.value === "number");
|
||||
astUtils.isNumericLiteral(node.argument));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+2
-27
@@ -10,13 +10,12 @@
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const
|
||||
path = require("path"),
|
||||
util = require("util"),
|
||||
lodash = require("lodash"),
|
||||
configSchema = require("../../conf/config-schema"),
|
||||
BuiltInEnvironments = require("../../conf/environments"),
|
||||
BuiltInRules = require("../rules"),
|
||||
ConfigOps = require("./config-ops");
|
||||
ConfigOps = require("./config-ops"),
|
||||
{ emitDeprecationWarning } = require("./deprecation-warnings");
|
||||
|
||||
const ajv = require("./ajv")();
|
||||
const ruleValidators = new WeakMap();
|
||||
@@ -26,11 +25,6 @@ const noop = Function.prototype;
|
||||
// Private
|
||||
//------------------------------------------------------------------------------
|
||||
let validateSchema;
|
||||
|
||||
// Defitions for deprecation warnings.
|
||||
const deprecationWarningMessages = {
|
||||
ESLINT_LEGACY_ECMAFEATURES: "The 'ecmaFeatures' config file property is deprecated, and has no effect."
|
||||
};
|
||||
const severityMap = {
|
||||
error: 2,
|
||||
warn: 1,
|
||||
@@ -254,25 +248,6 @@ function formatErrors(errors) {
|
||||
}).map(message => `\t- ${message}.\n`).join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* 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}
|
||||
*/
|
||||
const emitDeprecationWarning = lodash.memoize((source, errorCode) => {
|
||||
const rel = path.relative(process.cwd(), source);
|
||||
const message = deprecationWarningMessages[errorCode];
|
||||
|
||||
process.emitWarning(
|
||||
`${message} (found in "${rel}")`,
|
||||
"DeprecationWarning",
|
||||
errorCode
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Validates the top level properties of the config object.
|
||||
* @param {Object} config The config object to validate.
|
||||
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* @fileoverview Provide the function that emits deprecation warnings.
|
||||
* @author Toru Nagashima <http://github.com/mysticatea>
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const path = require("path");
|
||||
const lodash = require("lodash");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// 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."
|
||||
};
|
||||
|
||||
/**
|
||||
* 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}
|
||||
*/
|
||||
const emitDeprecationWarning = lodash.memoize((source, errorCode) => {
|
||||
const rel = path.relative(process.cwd(), source);
|
||||
const message = deprecationWarningMessages[errorCode];
|
||||
|
||||
process.emitWarning(
|
||||
`${message} (found in "${rel}")`,
|
||||
"DeprecationWarning",
|
||||
errorCode
|
||||
);
|
||||
}, (...args) => JSON.stringify(args));
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
module.exports = {
|
||||
emitDeprecationWarning
|
||||
};
|
||||
+7
-22
@@ -6,35 +6,18 @@
|
||||
"use strict";
|
||||
|
||||
const Module = require("module");
|
||||
const path = require("path");
|
||||
|
||||
// Polyfill Node's `Module.createRequire` if not present. We only support the case where the argument is a filepath, not a URL.
|
||||
const createRequire = (
|
||||
|
||||
// Added in v12.2.0
|
||||
Module.createRequire ||
|
||||
|
||||
// Added in v10.12.0, but deprecated in v12.2.0.
|
||||
Module.createRequireFromPath ||
|
||||
|
||||
// Polyfill - This is not executed on the tests on node@>=10.
|
||||
/* istanbul ignore next */
|
||||
(filename => {
|
||||
const mod = new Module(filename, null);
|
||||
|
||||
mod.filename = filename;
|
||||
mod.paths = Module._nodeModulePaths(path.dirname(filename)); // eslint-disable-line no-underscore-dangle
|
||||
mod._compile("module.exports = require;", filename); // eslint-disable-line no-underscore-dangle
|
||||
return mod.exports;
|
||||
})
|
||||
);
|
||||
/*
|
||||
* `Module.createRequire` is added in v12.2.0. It supports URL as well.
|
||||
* We only support the case where the argument is a filepath, not a URL.
|
||||
*/
|
||||
const createRequire = Module.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`
|
||||
@@ -43,6 +26,8 @@ module.exports = {
|
||||
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 &&
|
||||
|
||||
+7
-13
@@ -6,17 +6,11 @@ Object.defineProperty(exports, "__esModule", {
|
||||
exports.codeFrameColumns = codeFrameColumns;
|
||||
exports.default = _default;
|
||||
|
||||
function _highlight() {
|
||||
const data = _interopRequireWildcard(require("@babel/highlight"));
|
||||
var _highlight = _interopRequireWildcard(require("@babel/highlight"));
|
||||
|
||||
_highlight = function () {
|
||||
return data;
|
||||
};
|
||||
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
|
||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
|
||||
|
||||
let deprecationWarningShown = false;
|
||||
|
||||
@@ -35,7 +29,7 @@ function getMarkerLines(loc, source, opts) {
|
||||
column: 0,
|
||||
line: -1
|
||||
}, loc.start);
|
||||
const endLoc = Object.assign({}, startLoc, loc.end);
|
||||
const endLoc = Object.assign({}, startLoc, {}, loc.end);
|
||||
const {
|
||||
linesAbove = 2,
|
||||
linesBelow = 3
|
||||
@@ -94,8 +88,8 @@ function getMarkerLines(loc, source, opts) {
|
||||
}
|
||||
|
||||
function codeFrameColumns(rawLines, loc, opts = {}) {
|
||||
const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight().shouldHighlight)(opts);
|
||||
const chalk = (0, _highlight().getChalk)(opts);
|
||||
const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts);
|
||||
const chalk = (0, _highlight.getChalk)(opts);
|
||||
const defs = getDefs(chalk);
|
||||
|
||||
const maybeHighlight = (chalkFn, string) => {
|
||||
@@ -110,7 +104,7 @@ function codeFrameColumns(rawLines, loc, opts = {}) {
|
||||
} = getMarkerLines(loc, lines, opts);
|
||||
const hasColumns = loc.start && typeof loc.start.column === "number";
|
||||
const numberMaxWidth = String(end).length;
|
||||
const highlightedLines = highlighted ? (0, _highlight().default)(rawLines, opts) : rawLines;
|
||||
const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines;
|
||||
let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => {
|
||||
const number = start + 1 + index;
|
||||
const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
|
||||
|
||||
+3
-3
@@ -5,7 +5,7 @@
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {
|
||||
"@babel/highlight": "^7.0.0"
|
||||
"@babel/highlight": "^7.8.3"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "Generate errors that contain a code frame that point to source locations.",
|
||||
@@ -13,7 +13,7 @@
|
||||
"chalk": "^2.0.0",
|
||||
"strip-ansi": "^4.0.0"
|
||||
},
|
||||
"gitHead": "0407f034f09381b95e9cabefbf6b176c76485a43",
|
||||
"gitHead": "a7620bd266ae1345975767bbc7abf09034437017",
|
||||
"homepage": "https://babeljs.io/",
|
||||
"license": "MIT",
|
||||
"main": "lib/index.js",
|
||||
@@ -25,5 +25,5 @@
|
||||
"type": "git",
|
||||
"url": "https://github.com/babel/babel/tree/master/packages/babel-code-frame"
|
||||
},
|
||||
"version": "7.5.5"
|
||||
"version": "7.8.3"
|
||||
}
|
||||
+12
-34
@@ -7,39 +7,17 @@ exports.shouldHighlight = shouldHighlight;
|
||||
exports.getChalk = getChalk;
|
||||
exports.default = highlight;
|
||||
|
||||
function _jsTokens() {
|
||||
const data = _interopRequireWildcard(require("js-tokens"));
|
||||
var _jsTokens = _interopRequireWildcard(require("js-tokens"));
|
||||
|
||||
_jsTokens = function () {
|
||||
return data;
|
||||
};
|
||||
var _esutils = _interopRequireDefault(require("esutils"));
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
function _esutils() {
|
||||
const data = _interopRequireDefault(require("esutils"));
|
||||
|
||||
_esutils = function () {
|
||||
return data;
|
||||
};
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
function _chalk() {
|
||||
const data = _interopRequireDefault(require("chalk"));
|
||||
|
||||
_chalk = function () {
|
||||
return data;
|
||||
};
|
||||
|
||||
return data;
|
||||
}
|
||||
var _chalk = _interopRequireDefault(require("chalk"));
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
|
||||
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
|
||||
|
||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
|
||||
|
||||
function getDefs(chalk) {
|
||||
return {
|
||||
@@ -61,10 +39,10 @@ const BRACKET = /^[()[\]{}]$/;
|
||||
|
||||
function getTokenType(match) {
|
||||
const [offset, text] = match.slice(-2);
|
||||
const token = (0, _jsTokens().matchToToken)(match);
|
||||
const token = (0, _jsTokens.matchToToken)(match);
|
||||
|
||||
if (token.type === "name") {
|
||||
if (_esutils().default.keyword.isReservedWordES6(token.value)) {
|
||||
if (_esutils.default.keyword.isReservedWordES6(token.value)) {
|
||||
return "keyword";
|
||||
}
|
||||
|
||||
@@ -89,7 +67,7 @@ function getTokenType(match) {
|
||||
}
|
||||
|
||||
function highlightTokens(defs, text) {
|
||||
return text.replace(_jsTokens().default, function (...args) {
|
||||
return text.replace(_jsTokens.default, function (...args) {
|
||||
const type = getTokenType(args);
|
||||
const colorize = defs[type];
|
||||
|
||||
@@ -102,14 +80,14 @@ function highlightTokens(defs, text) {
|
||||
}
|
||||
|
||||
function shouldHighlight(options) {
|
||||
return _chalk().default.supportsColor || options.forceColor;
|
||||
return _chalk.default.supportsColor || options.forceColor;
|
||||
}
|
||||
|
||||
function getChalk(options) {
|
||||
let chalk = _chalk().default;
|
||||
let chalk = _chalk.default;
|
||||
|
||||
if (options.forceColor) {
|
||||
chalk = new (_chalk().default.constructor)({
|
||||
chalk = new _chalk.default.constructor({
|
||||
enabled: true,
|
||||
level: 1
|
||||
});
|
||||
|
||||
Generated
Vendored
File renamed without changes.
Generated
Vendored
File renamed without changes.
Generated
Vendored
File renamed without changes.
Generated
Vendored
+80
@@ -0,0 +1,80 @@
|
||||
{
|
||||
"bugs": {
|
||||
"url": "https://github.com/chalk/chalk/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {
|
||||
"ansi-styles": "^3.2.1",
|
||||
"escape-string-regexp": "^1.0.5",
|
||||
"supports-color": "^5.3.0"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "Terminal string styling done right",
|
||||
"devDependencies": {
|
||||
"ava": "*",
|
||||
"coveralls": "^3.0.0",
|
||||
"execa": "^0.9.0",
|
||||
"flow-bin": "^0.68.0",
|
||||
"import-fresh": "^2.0.0",
|
||||
"matcha": "^0.7.0",
|
||||
"nyc": "^11.0.2",
|
||||
"resolve-from": "^4.0.0",
|
||||
"typescript": "^2.5.3",
|
||||
"xo": "*"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
},
|
||||
"files": [
|
||||
"index.js",
|
||||
"templates.js",
|
||||
"types/index.d.ts",
|
||||
"index.js.flow"
|
||||
],
|
||||
"homepage": "https://github.com/chalk/chalk#readme",
|
||||
"keywords": [
|
||||
"color",
|
||||
"colour",
|
||||
"colors",
|
||||
"terminal",
|
||||
"console",
|
||||
"cli",
|
||||
"string",
|
||||
"str",
|
||||
"ansi",
|
||||
"style",
|
||||
"styles",
|
||||
"tty",
|
||||
"formatting",
|
||||
"rgb",
|
||||
"256",
|
||||
"shell",
|
||||
"xterm",
|
||||
"log",
|
||||
"logging",
|
||||
"command-line",
|
||||
"text"
|
||||
],
|
||||
"license": "MIT",
|
||||
"name": "chalk",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/chalk/chalk.git"
|
||||
},
|
||||
"scripts": {
|
||||
"bench": "matcha benchmark.js",
|
||||
"coveralls": "nyc report --reporter=text-lcov | coveralls",
|
||||
"test": "xo && tsc --project types && flow --max-warnings=0 && nyc ava"
|
||||
},
|
||||
"types": "types/index.d.ts",
|
||||
"version": "2.4.2",
|
||||
"xo": {
|
||||
"envs": [
|
||||
"node",
|
||||
"mocha"
|
||||
],
|
||||
"ignores": [
|
||||
"test/_flow.js"
|
||||
]
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+314
@@ -0,0 +1,314 @@
|
||||
<h1 align="center">
|
||||
<br>
|
||||
<br>
|
||||
<img width="320" src="media/logo.svg" alt="Chalk">
|
||||
<br>
|
||||
<br>
|
||||
<br>
|
||||
</h1>
|
||||
|
||||
> Terminal string styling done right
|
||||
|
||||
[](https://travis-ci.org/chalk/chalk) [](https://coveralls.io/github/chalk/chalk?branch=master) [](https://www.youtube.com/watch?v=9auOCbH5Ns4) [](https://github.com/xojs/xo) [](https://github.com/sindresorhus/awesome-nodejs)
|
||||
|
||||
### [See what's new in Chalk 2](https://github.com/chalk/chalk/releases/tag/v2.0.0)
|
||||
|
||||
<img src="https://cdn.rawgit.com/chalk/ansi-styles/8261697c95bf34b6c7767e2cbe9941a851d59385/screenshot.svg" alt="" width="900">
|
||||
|
||||
|
||||
## Highlights
|
||||
|
||||
- Expressive API
|
||||
- Highly performant
|
||||
- Ability to nest styles
|
||||
- [256/Truecolor color support](#256-and-truecolor-color-support)
|
||||
- Auto-detects color support
|
||||
- Doesn't extend `String.prototype`
|
||||
- Clean and focused
|
||||
- Actively maintained
|
||||
- [Used by ~23,000 packages](https://www.npmjs.com/browse/depended/chalk) as of December 31, 2017
|
||||
|
||||
|
||||
## Install
|
||||
|
||||
```console
|
||||
$ npm install chalk
|
||||
```
|
||||
|
||||
<a href="https://www.patreon.com/sindresorhus">
|
||||
<img src="https://c5.patreon.com/external/logo/become_a_patron_button@2x.png" width="160">
|
||||
</a>
|
||||
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
const chalk = require('chalk');
|
||||
|
||||
console.log(chalk.blue('Hello world!'));
|
||||
```
|
||||
|
||||
Chalk comes with an easy to use composable API where you just chain and nest the styles you want.
|
||||
|
||||
```js
|
||||
const chalk = require('chalk');
|
||||
const log = console.log;
|
||||
|
||||
// Combine styled and normal strings
|
||||
log(chalk.blue('Hello') + ' World' + chalk.red('!'));
|
||||
|
||||
// Compose multiple styles using the chainable API
|
||||
log(chalk.blue.bgRed.bold('Hello world!'));
|
||||
|
||||
// Pass in multiple arguments
|
||||
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
|
||||
|
||||
// Nest styles
|
||||
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
|
||||
|
||||
// Nest styles of the same type even (color, underline, background)
|
||||
log(chalk.green(
|
||||
'I am a green line ' +
|
||||
chalk.blue.underline.bold('with a blue substring') +
|
||||
' that becomes green again!'
|
||||
));
|
||||
|
||||
// ES2015 template literal
|
||||
log(`
|
||||
CPU: ${chalk.red('90%')}
|
||||
RAM: ${chalk.green('40%')}
|
||||
DISK: ${chalk.yellow('70%')}
|
||||
`);
|
||||
|
||||
// ES2015 tagged template literal
|
||||
log(chalk`
|
||||
CPU: {red ${cpu.totalPercent}%}
|
||||
RAM: {green ${ram.used / ram.total * 100}%}
|
||||
DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
|
||||
`);
|
||||
|
||||
// Use RGB colors in terminal emulators that support it.
|
||||
log(chalk.keyword('orange')('Yay for orange colored text!'));
|
||||
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
|
||||
log(chalk.hex('#DEADED').bold('Bold gray!'));
|
||||
```
|
||||
|
||||
Easily define your own themes:
|
||||
|
||||
```js
|
||||
const chalk = require('chalk');
|
||||
|
||||
const error = chalk.bold.red;
|
||||
const warning = chalk.keyword('orange');
|
||||
|
||||
console.log(error('Error!'));
|
||||
console.log(warning('Warning!'));
|
||||
```
|
||||
|
||||
Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args):
|
||||
|
||||
```js
|
||||
const name = 'Sindre';
|
||||
console.log(chalk.green('Hello %s'), name);
|
||||
//=> 'Hello Sindre'
|
||||
```
|
||||
|
||||
|
||||
## API
|
||||
|
||||
### chalk.`<style>[.<style>...](string, [string...])`
|
||||
|
||||
Example: `chalk.red.bold.underline('Hello', 'world');`
|
||||
|
||||
Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
|
||||
|
||||
Multiple arguments will be separated by space.
|
||||
|
||||
### chalk.enabled
|
||||
|
||||
Color support is automatically detected, as is the level (see `chalk.level`). However, if you'd like to simply enable/disable Chalk, you can do so via the `.enabled` property.
|
||||
|
||||
Chalk is enabled by default unless explicitly disabled via the constructor or `chalk.level` is `0`.
|
||||
|
||||
If you need to change this in a reusable module, create a new instance:
|
||||
|
||||
```js
|
||||
const ctx = new chalk.constructor({enabled: false});
|
||||
```
|
||||
|
||||
### chalk.level
|
||||
|
||||
Color support is automatically detected, but you can override it by setting the `level` property. You should however only do this in your own code as it applies globally to all Chalk consumers.
|
||||
|
||||
If you need to change this in a reusable module, create a new instance:
|
||||
|
||||
```js
|
||||
const ctx = new chalk.constructor({level: 0});
|
||||
```
|
||||
|
||||
Levels are as follows:
|
||||
|
||||
0. All colors disabled
|
||||
1. Basic color support (16 colors)
|
||||
2. 256 color support
|
||||
3. Truecolor support (16 million colors)
|
||||
|
||||
### chalk.supportsColor
|
||||
|
||||
Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
|
||||
|
||||
Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, add the environment variable `FORCE_COLOR=1` to forcefully enable color or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks.
|
||||
|
||||
Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.
|
||||
|
||||
|
||||
## Styles
|
||||
|
||||
### Modifiers
|
||||
|
||||
- `reset`
|
||||
- `bold`
|
||||
- `dim`
|
||||
- `italic` *(Not widely supported)*
|
||||
- `underline`
|
||||
- `inverse`
|
||||
- `hidden`
|
||||
- `strikethrough` *(Not widely supported)*
|
||||
- `visible` (Text is emitted only if enabled)
|
||||
|
||||
### Colors
|
||||
|
||||
- `black`
|
||||
- `red`
|
||||
- `green`
|
||||
- `yellow`
|
||||
- `blue` *(On Windows the bright version is used since normal blue is illegible)*
|
||||
- `magenta`
|
||||
- `cyan`
|
||||
- `white`
|
||||
- `gray` ("bright black")
|
||||
- `redBright`
|
||||
- `greenBright`
|
||||
- `yellowBright`
|
||||
- `blueBright`
|
||||
- `magentaBright`
|
||||
- `cyanBright`
|
||||
- `whiteBright`
|
||||
|
||||
### Background colors
|
||||
|
||||
- `bgBlack`
|
||||
- `bgRed`
|
||||
- `bgGreen`
|
||||
- `bgYellow`
|
||||
- `bgBlue`
|
||||
- `bgMagenta`
|
||||
- `bgCyan`
|
||||
- `bgWhite`
|
||||
- `bgBlackBright`
|
||||
- `bgRedBright`
|
||||
- `bgGreenBright`
|
||||
- `bgYellowBright`
|
||||
- `bgBlueBright`
|
||||
- `bgMagentaBright`
|
||||
- `bgCyanBright`
|
||||
- `bgWhiteBright`
|
||||
|
||||
|
||||
## Tagged template literal
|
||||
|
||||
Chalk can be used as a [tagged template literal](http://exploringjs.com/es6/ch_template-literals.html#_tagged-template-literals).
|
||||
|
||||
```js
|
||||
const chalk = require('chalk');
|
||||
|
||||
const miles = 18;
|
||||
const calculateFeet = miles => miles * 5280;
|
||||
|
||||
console.log(chalk`
|
||||
There are {bold 5280 feet} in a mile.
|
||||
In {bold ${miles} miles}, there are {green.bold ${calculateFeet(miles)} feet}.
|
||||
`);
|
||||
```
|
||||
|
||||
Blocks are delimited by an opening curly brace (`{`), a style, some content, and a closing curly brace (`}`).
|
||||
|
||||
Template styles are chained exactly like normal Chalk styles. The following two statements are equivalent:
|
||||
|
||||
```js
|
||||
console.log(chalk.bold.rgb(10, 100, 200)('Hello!'));
|
||||
console.log(chalk`{bold.rgb(10,100,200) Hello!}`);
|
||||
```
|
||||
|
||||
Note that function styles (`rgb()`, `hsl()`, `keyword()`, etc.) may not contain spaces between parameters.
|
||||
|
||||
All interpolated values (`` chalk`${foo}` ``) are converted to strings via the `.toString()` method. All curly braces (`{` and `}`) in interpolated value strings are escaped.
|
||||
|
||||
|
||||
## 256 and Truecolor color support
|
||||
|
||||
Chalk supports 256 colors and [Truecolor](https://gist.github.com/XVilka/8346728) (16 million colors) on supported terminal apps.
|
||||
|
||||
Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying `{level: n}` as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red).
|
||||
|
||||
Examples:
|
||||
|
||||
- `chalk.hex('#DEADED').underline('Hello, world!')`
|
||||
- `chalk.keyword('orange')('Some orange text')`
|
||||
- `chalk.rgb(15, 100, 204).inverse('Hello!')`
|
||||
|
||||
Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `keyword` for foreground colors and `bgKeyword` for background colors).
|
||||
|
||||
- `chalk.bgHex('#DEADED').underline('Hello, world!')`
|
||||
- `chalk.bgKeyword('orange')('Some orange text')`
|
||||
- `chalk.bgRgb(15, 100, 204).inverse('Hello!')`
|
||||
|
||||
The following color models can be used:
|
||||
|
||||
- [`rgb`](https://en.wikipedia.org/wiki/RGB_color_model) - Example: `chalk.rgb(255, 136, 0).bold('Orange!')`
|
||||
- [`hex`](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) - Example: `chalk.hex('#FF8800').bold('Orange!')`
|
||||
- [`keyword`](https://www.w3.org/wiki/CSS/Properties/color/keywords) (CSS keywords) - Example: `chalk.keyword('orange').bold('Orange!')`
|
||||
- [`hsl`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 100, 50).bold('Orange!')`
|
||||
- [`hsv`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsv(32, 100, 100).bold('Orange!')`
|
||||
- [`hwb`](https://en.wikipedia.org/wiki/HWB_color_model) - Example: `chalk.hwb(32, 0, 50).bold('Orange!')`
|
||||
- `ansi16`
|
||||
- `ansi256`
|
||||
|
||||
|
||||
## Windows
|
||||
|
||||
If you're on Windows, do yourself a favor and use [`cmder`](http://cmder.net/) instead of `cmd.exe`.
|
||||
|
||||
|
||||
## Origin story
|
||||
|
||||
[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68) and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative.
|
||||
|
||||
|
||||
## Related
|
||||
|
||||
- [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
|
||||
- [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal
|
||||
- [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color
|
||||
- [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes
|
||||
- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Strip ANSI escape codes from a stream
|
||||
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
|
||||
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
|
||||
- [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes
|
||||
- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes
|
||||
- [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models
|
||||
- [chalk-animation](https://github.com/bokub/chalk-animation) - Animate strings in the terminal
|
||||
- [gradient-string](https://github.com/bokub/gradient-string) - Apply color gradients to strings
|
||||
- [chalk-pipe](https://github.com/LitoMore/chalk-pipe) - Create chalk style schemes with simpler style strings
|
||||
- [terminal-link](https://github.com/sindresorhus/terminal-link) - Create clickable links in the terminal
|
||||
|
||||
|
||||
## Maintainers
|
||||
|
||||
- [Sindre Sorhus](https://github.com/sindresorhus)
|
||||
- [Josh Junon](https://github.com/qix-)
|
||||
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
Generated
Vendored
File renamed without changes.
+2
-2
@@ -14,7 +14,7 @@
|
||||
"devDependencies": {
|
||||
"strip-ansi": "^4.0.0"
|
||||
},
|
||||
"gitHead": "49da9a07c81156e997e60146eb001ea77b7044c4",
|
||||
"gitHead": "a7620bd266ae1345975767bbc7abf09034437017",
|
||||
"homepage": "https://babeljs.io/",
|
||||
"license": "MIT",
|
||||
"main": "lib/index.js",
|
||||
@@ -26,5 +26,5 @@
|
||||
"type": "git",
|
||||
"url": "https://github.com/babel/babel/tree/master/packages/babel-highlight"
|
||||
},
|
||||
"version": "7.5.0"
|
||||
"version": "7.8.3"
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
|
||||
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
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
# Installation
|
||||
> `npm install --save @types/color-name`
|
||||
|
||||
# Summary
|
||||
This package contains type definitions for color-name ( https://github.com/colorjs/color-name ).
|
||||
|
||||
# Details
|
||||
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/color-name
|
||||
|
||||
Additional Details
|
||||
* Last updated: Wed, 13 Feb 2019 16:16:48 GMT
|
||||
* Dependencies: none
|
||||
* Global values: none
|
||||
|
||||
# Credits
|
||||
These definitions were written by Junyoung Clare Jang <https://github.com/Ailrun>.
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"bugs": {
|
||||
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Junyoung Clare Jang",
|
||||
"url": "https://github.com/Ailrun"
|
||||
}
|
||||
],
|
||||
"dependencies": {},
|
||||
"deprecated": false,
|
||||
"description": "TypeScript definitions for color-name",
|
||||
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme",
|
||||
"license": "MIT",
|
||||
"main": "",
|
||||
"name": "@types/color-name",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git"
|
||||
},
|
||||
"scripts": {},
|
||||
"typeScriptVersion": "2.0",
|
||||
"types": "index",
|
||||
"typesPublisherContentHash": "e22c6881e2dcf766e32142cbb82d9acf9c08258bdf0da8e76c8a448d1be44ac7",
|
||||
"version": "1.1.1"
|
||||
}
|
||||
+11
-3
@@ -136,6 +136,14 @@ function plugin(options, Parser) {
|
||||
chunkStart = this.pos;
|
||||
break;
|
||||
|
||||
case 62: // '>'
|
||||
case 125: // '}'
|
||||
this.raise(
|
||||
this.pos,
|
||||
"Unexpected token `" + this.input[this.pos] + "`. Did you mean `" +
|
||||
(ch === 62 ? ">" : "}") + "` or " + "`{\"" + this.input[this.pos] + "\"}" + "`?"
|
||||
);
|
||||
|
||||
default:
|
||||
if (isNewLine(ch)) {
|
||||
out += this.input.slice(chunkStart, this.pos);
|
||||
@@ -414,8 +422,8 @@ function plugin(options, Parser) {
|
||||
|
||||
// Parse JSX text
|
||||
|
||||
jsx_parseText(value) {
|
||||
let node = this.parseLiteral(value);
|
||||
jsx_parseText() {
|
||||
let node = this.parseLiteral(this.value);
|
||||
node.type = "JSXText";
|
||||
return node;
|
||||
}
|
||||
@@ -430,7 +438,7 @@ function plugin(options, Parser) {
|
||||
|
||||
parseExprAtom(refShortHandDefaultPos) {
|
||||
if (this.type === tok.jsxText)
|
||||
return this.jsx_parseText(this.value);
|
||||
return this.jsx_parseText();
|
||||
else if (this.type === tok.jsxTagStart)
|
||||
return this.jsx_parseElement();
|
||||
else
|
||||
|
||||
+1
-1
@@ -28,5 +28,5 @@
|
||||
"scripts": {
|
||||
"test": "node test/run.js"
|
||||
},
|
||||
"version": "5.1.0"
|
||||
"version": "5.2.0"
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"bin": {
|
||||
"acorn": "./bin/acorn"
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/acornjs/acorn/issues"
|
||||
|
||||
+58
-6
@@ -57,6 +57,7 @@ ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
|
||||
- [Untrusted schemas](#untrusted-schemas)
|
||||
- [Circular references in objects](#circular-references-in-javascript-objects)
|
||||
- [Trusted schemas](#security-risks-of-trusted-schemas)
|
||||
- [ReDoS attack](#redos-attack)
|
||||
- Modifying data during validation
|
||||
- [Filtering data](#filtering-data)
|
||||
- [Assigning defaults](#assigning-defaults)
|
||||
@@ -130,7 +131,11 @@ Try it in the Node.js REPL: https://tonicdev.com/npm/ajv
|
||||
The fastest validation call:
|
||||
|
||||
```javascript
|
||||
// Node.js require:
|
||||
var Ajv = require('ajv');
|
||||
// or ESM/TypeScript import
|
||||
import Ajv from 'ajv';
|
||||
|
||||
var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true}
|
||||
var validate = ajv.compile(schema);
|
||||
var valid = validate(data);
|
||||
@@ -164,6 +169,10 @@ The best performance is achieved when using compiled functions returned by `comp
|
||||
|
||||
__Please note__: every time a validation function or `ajv.validate` are called `errors` property is overwritten. You need to copy `errors` array reference to another variable if you want to use it later (e.g., in the callback). See [Validation errors](#validation-errors)
|
||||
|
||||
__Note for TypeScript users__: `ajv` provides its own TypeScript declarations
|
||||
out of the box, so you don't need to install the deprecated `@types/ajv`
|
||||
module.
|
||||
|
||||
|
||||
## Using in browser
|
||||
|
||||
@@ -240,7 +249,11 @@ __Please note__: Ajv does not implement validation of the keywords `examples`,
|
||||
|
||||
## Formats
|
||||
|
||||
The following formats are supported for string validation with "format" keyword:
|
||||
Ajv implements formats defined by JSON Schema specification and several other formats. It is recommended NOT to use "format" keyword implementations with untrusted data, as they use potentially unsafe regular expressions - see [ReDoS attack](#redos-attack).
|
||||
|
||||
__Please note__: if you need to use "format" keyword to validate untrusted data, you MUST assess their suitability and safety for your validation scenarios.
|
||||
|
||||
The following formats are implemented for string validation with "format" keyword:
|
||||
|
||||
- _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6).
|
||||
- _time_: time with optional time-zone.
|
||||
@@ -323,7 +336,7 @@ __Please note__:
|
||||
|
||||
## $data reference
|
||||
|
||||
With `$data` option you can use values from the validated data as the values for the schema keywords. See [proposal](https://github.com/json-schema/json-schema/wiki/$data-(v5-proposal)) for more information about how it works.
|
||||
With `$data` option you can use values from the validated data as the values for the schema keywords. See [proposal](https://github.com/json-schema-org/json-schema-spec/issues/51) for more information about how it works.
|
||||
|
||||
`$data` reference is supported in the keywords: const, enum, format, maximum/minimum, exclusiveMaximum / exclusiveMinimum, maxLength / minLength, maxItems / minItems, maxProperties / minProperties, formatMaximum / formatMinimum, formatExclusiveMaximum / formatExclusiveMinimum, multipleOf, pattern, required, uniqueItems.
|
||||
|
||||
@@ -646,9 +659,9 @@ An attempt to compile such schemas or validate such data would cause stack overf
|
||||
|
||||
Some keywords in JSON Schemas can lead to very slow validation for certain data. These keywords include (but may be not limited to):
|
||||
|
||||
- `pattern` and `format` for large strings - use `maxLength` to mitigate
|
||||
- `pattern` and `format` for large strings - in some cases using `maxLength` can help mitigate it, but certain regular expressions can lead to exponential validation time even with relatively short strings (see [ReDoS attack](#redos-attack)).
|
||||
- `patternProperties` for large property names - use `propertyNames` to mitigate, but some regular expressions can have exponential evaluation time as well.
|
||||
- `uniqueItems` for large non-scalar arrays - use `maxItems` to mitigate
|
||||
- `patternProperties` for large property names - use `propertyNames` to mitigate
|
||||
|
||||
__Please note__: The suggestions above to prevent slow validation would only work if you do NOT use `allErrors: true` in production code (using it would continue validation after validation errors).
|
||||
|
||||
@@ -660,13 +673,29 @@ const isSchemaSecure = ajv.compile(require('ajv/lib/refs/json-schema-secure.json
|
||||
const schema1 = {format: 'email'};
|
||||
isSchemaSecure(schema1); // false
|
||||
|
||||
const schema2 = {format: 'email', maxLength: 256};
|
||||
const schema2 = {format: 'email', maxLength: MAX_LENGTH};
|
||||
isSchemaSecure(schema2); // true
|
||||
```
|
||||
|
||||
__Please note__: following all these recommendation is not a guarantee that validation of untrusted data is safe - it can still lead to some undesirable results.
|
||||
|
||||
|
||||
## ReDoS attack
|
||||
|
||||
Certain regular expressions can lead to the exponential evaluation time even with relatively short strings.
|
||||
|
||||
Please assess the regular expressions you use in the schemas on their vulnerability to this attack - see [safe-regex](https://github.com/substack/safe-regex), for example.
|
||||
|
||||
__Please note__: some formats that Ajv implements use [regular expressions](https://github.com/epoberezkin/ajv/blob/master/lib/compile/formats.js) that can be vulnerable to ReDoS attack, so if you use Ajv to validate data from untrusted sources __it is strongly recommended__ to consider the following:
|
||||
|
||||
- making assessment of "format" implementations in Ajv.
|
||||
- using `format: 'fast'` option that simplifies some of the regular expressions (although it does not guarantee that they are safe).
|
||||
- replacing format implementations provided by Ajv with your own implementations of "format" keyword that either uses different regular expressions or another approach to format validation. Please see [addFormat](#api-addformat) method.
|
||||
- disabling format validation by ignoring "format" keyword with option `format: false`
|
||||
|
||||
Whatever mitigation you choose, please assume all formats provided by Ajv as potentially unsafe and make your own assessment of their suitability for your validation scenarios.
|
||||
|
||||
|
||||
## Filtering data
|
||||
|
||||
With [option `removeAdditional`](#options) (added by [andyscott](https://github.com/andyscott)) you can filter data during the validation.
|
||||
@@ -1123,12 +1152,13 @@ Defaults:
|
||||
- `"full"` - more restrictive and slow validation. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode.
|
||||
- `false` - ignore all format keywords.
|
||||
- _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method.
|
||||
- _keywords_: an object with custom keywords. Keys and values will be passed to `addKeyword` method.
|
||||
- _unknownFormats_: handling of unknown formats. Option values:
|
||||
- `true` (default) - if an unknown format is encountered the exception is thrown during schema compilation. If `format` keyword value is [$data reference](#data-reference) and it is unknown the validation will fail.
|
||||
- `[String]` - an array of unknown format names that will be ignored. This option can be used to allow usage of third party schemas with format(s) for which you don't have definitions, but still fail if another unknown format is used. If `format` keyword value is [$data reference](#data-reference) and it is not in this array the validation will fail.
|
||||
- `"ignore"` - to log warning during schema compilation and always pass validation (the default behaviour in versions before 5.0.0). This option is not recommended, as it allows to mistype format name and it won't be validated without any error message. This behaviour is required by JSON Schema specification.
|
||||
- _schemas_: an array or object of schemas that will be added to the instance. In case you pass the array the schemas must have IDs in them. When the object is passed the method `addSchema(value, key)` will be called for each schema in this object.
|
||||
- _logger_: sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. Option values:
|
||||
- _logger_: sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. See [Error logging](#error-logging). Option values:
|
||||
- custom logger - it should have methods `log`, `warn` and `error`. If any of these methods is missing an exception will be thrown.
|
||||
- `false` - logging is disabled.
|
||||
|
||||
@@ -1266,6 +1296,28 @@ Properties of `params` object in errors depend on the keyword that failed valida
|
||||
- custom keywords (in case keyword definition doesn't create errors) - property `keyword` (the keyword name).
|
||||
|
||||
|
||||
### Error logging
|
||||
|
||||
Using the `logger` option when initiallizing Ajv will allow you to define custom logging. Here you can build upon the exisiting logging. The use of other logging packages is supported as long as the package or its associated wrapper exposes the required methods. If any of the required methods are missing an exception will be thrown.
|
||||
- **Required Methods**: `log`, `warn`, `error`
|
||||
|
||||
```javascript
|
||||
var otherLogger = new OtherLogger();
|
||||
var ajv = new Ajv({
|
||||
logger: {
|
||||
log: console.log.bind(console),
|
||||
warn: function warn() {
|
||||
otherLogger.logWarn.apply(otherLogger, arguments);
|
||||
},
|
||||
error: function error() {
|
||||
otherLogger.logError.apply(otherLogger, arguments);
|
||||
console.error.apply(console, arguments);
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
## Plugins
|
||||
|
||||
Ajv can be extended with plugins that add custom keywords, formats or functions to process generated code. When such plugin is published as npm package it is recommended that it follows these conventions:
|
||||
|
||||
+29
-36
@@ -161,8 +161,8 @@ var util = require('./util');
|
||||
|
||||
var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
|
||||
var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31];
|
||||
var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i;
|
||||
var HOSTNAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*$/i;
|
||||
var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;
|
||||
var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i;
|
||||
var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
|
||||
var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
|
||||
// uri-template: https://tools.ietf.org/html/rfc6570
|
||||
@@ -190,8 +190,8 @@ formats.fast = {
|
||||
// date: http://tools.ietf.org/html/rfc3339#section-5.6
|
||||
date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
|
||||
// date-time: http://tools.ietf.org/html/rfc3339#section-5.6
|
||||
time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i,
|
||||
'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i,
|
||||
time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,
|
||||
'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,
|
||||
// uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
|
||||
uri: /^(?:[a-z][a-z0-9+-.]*:)(?:\/?\/)?[^\s]*$/i,
|
||||
'uri-reference': /^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
|
||||
@@ -227,7 +227,7 @@ formats.full = {
|
||||
'uri-template': URITEMPLATE,
|
||||
url: URL,
|
||||
email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
|
||||
hostname: hostname,
|
||||
hostname: HOSTNAME,
|
||||
ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
|
||||
ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
|
||||
regex: regex,
|
||||
@@ -280,13 +280,6 @@ function date_time(str) {
|
||||
}
|
||||
|
||||
|
||||
function hostname(str) {
|
||||
// https://tools.ietf.org/html/rfc1034#section-3.5
|
||||
// https://tools.ietf.org/html/rfc1123#section-2
|
||||
return str.length <= 255 && HOSTNAME.test(str);
|
||||
}
|
||||
|
||||
|
||||
var NOT_URI_FRAGMENT = /\/|:/;
|
||||
function uri(str) {
|
||||
// http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
|
||||
@@ -5072,21 +5065,18 @@ module.exports={
|
||||
},{}],42:[function(require,module,exports){
|
||||
'use strict';
|
||||
|
||||
var isArray = Array.isArray;
|
||||
var keyList = Object.keys;
|
||||
var hasProp = Object.prototype.hasOwnProperty;
|
||||
// do not edit .js files directly - edit src/index.jst
|
||||
|
||||
|
||||
|
||||
module.exports = function equal(a, b) {
|
||||
if (a === b) return true;
|
||||
|
||||
if (a && b && typeof a == 'object' && typeof b == 'object') {
|
||||
var arrA = isArray(a)
|
||||
, arrB = isArray(b)
|
||||
, i
|
||||
, length
|
||||
, key;
|
||||
if (a.constructor !== b.constructor) return false;
|
||||
|
||||
if (arrA && arrB) {
|
||||
var length, i, keys;
|
||||
if (Array.isArray(a)) {
|
||||
length = a.length;
|
||||
if (length != b.length) return false;
|
||||
for (i = length; i-- !== 0;)
|
||||
@@ -5094,35 +5084,29 @@ module.exports = function equal(a, b) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (arrA != arrB) return false;
|
||||
|
||||
var dateA = a instanceof Date
|
||||
, dateB = b instanceof Date;
|
||||
if (dateA != dateB) return false;
|
||||
if (dateA && dateB) return a.getTime() == b.getTime();
|
||||
|
||||
var regexpA = a instanceof RegExp
|
||||
, regexpB = b instanceof RegExp;
|
||||
if (regexpA != regexpB) return false;
|
||||
if (regexpA && regexpB) return a.toString() == b.toString();
|
||||
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
|
||||
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
|
||||
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
|
||||
|
||||
var keys = keyList(a);
|
||||
keys = Object.keys(a);
|
||||
length = keys.length;
|
||||
|
||||
if (length !== keyList(b).length)
|
||||
return false;
|
||||
if (length !== Object.keys(b).length) return false;
|
||||
|
||||
for (i = length; i-- !== 0;)
|
||||
if (!hasProp.call(b, keys[i])) return false;
|
||||
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
|
||||
|
||||
for (i = length; i-- !== 0;) {
|
||||
key = keys[i];
|
||||
var key = keys[i];
|
||||
|
||||
if (!equal(a[key], b[key])) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// true if both NaN, false otherwise
|
||||
return a!==a && b!==b;
|
||||
};
|
||||
|
||||
@@ -6741,6 +6725,7 @@ function Ajv(opts) {
|
||||
this._metaOpts = getMetaSchemaOptions(this);
|
||||
|
||||
if (opts.formats) addInitialFormats(this);
|
||||
if (opts.keywords) addInitialKeywords(this);
|
||||
addDefaultMetaSchema(this);
|
||||
if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
|
||||
if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}});
|
||||
@@ -7139,6 +7124,14 @@ function addInitialFormats(self) {
|
||||
}
|
||||
|
||||
|
||||
function addInitialKeywords(self) {
|
||||
for (var name in self._opts.keywords) {
|
||||
var keyword = self._opts.keywords[name];
|
||||
self.addKeyword(name, keyword);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function checkUnique(self, id) {
|
||||
if (self._schemas[id] || self._refs[id])
|
||||
throw new Error('schema with key or id "' + id + '" already exists');
|
||||
|
||||
+2
-2
@@ -1,3 +1,3 @@
|
||||
/* ajv 6.10.2: Another JSON Schema Validator */
|
||||
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Ajv=e()}}(function(){return function o(i,n,l){function c(r,e){if(!n[r]){if(!i[r]){var t="function"==typeof require&&require;if(!e&&t)return t(r,!0);if(u)return u(r,!0);var a=new Error("Cannot find module '"+r+"'");throw a.code="MODULE_NOT_FOUND",a}var s=n[r]={exports:{}};i[r][0].call(s.exports,function(e){return c(i[r][1][e]||e)},s,s.exports,o,i,n,l)}return n[r].exports}for(var u="function"==typeof require&&require,e=0;e<l.length;e++)c(l[e]);return c}({1:[function(e,r,t){"use strict";var a=r.exports=function(){this._cache={}};a.prototype.put=function(e,r){this._cache[e]=r},a.prototype.get=function(e){return this._cache[e]},a.prototype.del=function(e){delete this._cache[e]},a.prototype.clear=function(){this._cache={}}},{}],2:[function(e,r,t){"use strict";var s=e("./error_classes").MissingRef;r.exports=function t(r,i,a){var n=this;if("function"!=typeof this._opts.loadSchema)throw new Error("options.loadSchema should be a function");"function"==typeof i&&(a=i,i=void 0);var e=l(r).then(function(){var e=n._addSchema(r,void 0,i);return e.validate||c(e)});a&&e.then(function(e){a(null,e)},a);return e;function l(e){var r=e.$schema;return r&&!n.getSchema(r)?t.call(n,{$ref:r},!0):Promise.resolve()}function c(o){try{return n._compile(o)}catch(e){if(e instanceof s)return r(e);throw e}function r(e){var r=e.missingSchema;if(s(r))throw new Error("Schema "+r+" is loaded but "+e.missingRef+" cannot be resolved");var t=n._loadingSchemas[r];return t||(t=n._loadingSchemas[r]=n._opts.loadSchema(r)).then(a,a),t.then(function(e){if(!s(r))return l(e).then(function(){s(r)||n.addSchema(e,r,void 0,i)})}).then(function(){return c(o)});function a(){delete n._loadingSchemas[r]}function s(e){return n._refs[e]||n._schemas[e]}}}}},{"./error_classes":3}],3:[function(e,r,t){"use strict";var a=e("./resolve");function s(e,r,t){this.message=t||s.message(e,r),this.missingRef=a.url(e,r),this.missingSchema=a.normalizeId(a.fullPath(this.missingRef))}function o(e){return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e}r.exports={Validation:o(function(e){this.message="validation failed",this.errors=e,this.ajv=this.validation=!0}),MissingRef:o(s)},s.message=function(e,r){return"can't resolve reference "+r+" from id "+e}},{"./resolve":6}],4:[function(e,r,t){"use strict";var a=e("./util"),o=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31],n=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i,s=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*$/i,l=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,c=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,u=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000Line truncated
|
||||
/* ajv 6.12.0: Another JSON Schema Validator */
|
||||
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Ajv=e()}}(function(){return function o(i,n,l){function c(r,e){if(!n[r]){if(!i[r]){var t="function"==typeof require&&require;if(!e&&t)return t(r,!0);if(u)return u(r,!0);var a=new Error("Cannot find module '"+r+"'");throw a.code="MODULE_NOT_FOUND",a}var s=n[r]={exports:{}};i[r][0].call(s.exports,function(e){return c(i[r][1][e]||e)},s,s.exports,o,i,n,l)}return n[r].exports}for(var u="function"==typeof require&&require,e=0;e<l.length;e++)c(l[e]);return c}({1:[function(e,r,t){"use strict";var a=r.exports=function(){this._cache={}};a.prototype.put=function(e,r){this._cache[e]=r},a.prototype.get=function(e){return this._cache[e]},a.prototype.del=function(e){delete this._cache[e]},a.prototype.clear=function(){this._cache={}}},{}],2:[function(e,r,t){"use strict";var s=e("./error_classes").MissingRef;r.exports=function t(r,i,a){var n=this;if("function"!=typeof this._opts.loadSchema)throw new Error("options.loadSchema should be a function");"function"==typeof i&&(a=i,i=void 0);var e=l(r).then(function(){var e=n._addSchema(r,void 0,i);return e.validate||c(e)});a&&e.then(function(e){a(null,e)},a);return e;function l(e){var r=e.$schema;return r&&!n.getSchema(r)?t.call(n,{$ref:r},!0):Promise.resolve()}function c(o){try{return n._compile(o)}catch(e){if(e instanceof s)return r(e);throw e}function r(e){var r=e.missingSchema;if(s(r))throw new Error("Schema "+r+" is loaded but "+e.missingRef+" cannot be resolved");var t=n._loadingSchemas[r];return t||(t=n._loadingSchemas[r]=n._opts.loadSchema(r)).then(a,a),t.then(function(e){if(!s(r))return l(e).then(function(){s(r)||n.addSchema(e,r,void 0,i)})}).then(function(){return c(o)});function a(){delete n._loadingSchemas[r]}function s(e){return n._refs[e]||n._schemas[e]}}}}},{"./error_classes":3}],3:[function(e,r,t){"use strict";var a=e("./resolve");function s(e,r,t){this.message=t||s.message(e,r),this.missingRef=a.url(e,r),this.missingSchema=a.normalizeId(a.fullPath(this.missingRef))}function o(e){return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e}r.exports={Validation:o(function(e){this.message="validation failed",this.errors=e,this.ajv=this.validation=!0}),MissingRef:o(s)},s.message=function(e,r){return"can't resolve reference "+r+" from id "+e}},{"./resolve":6}],4:[function(e,r,t){"use strict";var a=e("./util"),o=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31],n=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,s=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,l=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,c=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,u=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[Line truncated
|
||||
//# sourceMappingURL=ajv.min.js.map
|
||||
+9
@@ -69,6 +69,7 @@ function Ajv(opts) {
|
||||
this._metaOpts = getMetaSchemaOptions(this);
|
||||
|
||||
if (opts.formats) addInitialFormats(this);
|
||||
if (opts.keywords) addInitialKeywords(this);
|
||||
addDefaultMetaSchema(this);
|
||||
if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
|
||||
if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}});
|
||||
@@ -467,6 +468,14 @@ function addInitialFormats(self) {
|
||||
}
|
||||
|
||||
|
||||
function addInitialKeywords(self) {
|
||||
for (var name in self._opts.keywords) {
|
||||
var keyword = self._opts.keywords[name];
|
||||
self.addKeyword(name, keyword);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function checkUnique(self, id) {
|
||||
if (self._schemas[id] || self._refs[id])
|
||||
throw new Error('schema with key or id "' + id + '" already exists');
|
||||
|
||||
Loaded 100 of 336 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user