tools: update ESLint to 5.15.0

Update ESLint to 5.15.0

PR-URL: https://github.com/nodejs/node/pull/26391
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Masashi Hirano <shisama07@gmail.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
This commit is contained in:
cjihrig 2019-03-01 21:47:17 -05:00
parent 8c597df350
commit 17b7fa75c3
No known key found for this signature in database
GPG Key ID: 7434390BDBE9B9C5
111 changed files with 471 additions and 409 deletions

View File

@ -266,7 +266,7 @@ The following companies, organizations, and individuals support ESLint's ongoing
<!-- NOTE: This section is autogenerated. Do not manually edit.--> <!-- NOTE: This section is autogenerated. Do not manually edit.-->
<!--sponsorsstart--> <!--sponsorsstart-->
<h3>Gold Sponsors</h3> <h3>Gold Sponsors</h3>
<p><a href="https://code.facebook.com/projects/"><img src="https://images.opencollective.com/proxy/images/?src=https%3A%2F%2Fres.cloudinary.com%2Fopencollective%2Fimage%2Fupload%2Fv1508519428%2FS9gk78AS_400x400_fulq2l.jpg&height=96" alt="Facebook Open Source" height="96"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/proxy/images/?src=https%3A%2F%2Fopencollective-production.s3-us-west-1.amazonaws.com%2F098e3bd0-4d57-11e8-9324-0f6cc1f92bf1.png&height=96" alt="Airbnb" height="96"></a></p><h3>Silver Sponsors</h3> <p><a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/proxy/images/?src=https%3A%2F%2Fopencollective-production.s3-us-west-1.amazonaws.com%2F098e3bd0-4d57-11e8-9324-0f6cc1f92bf1.png&height=96" alt="Airbnb" height="96"></a> <a href="https://code.facebook.com/projects/"><img src="https://images.opencollective.com/proxy/images/?src=https%3A%2F%2Fres.cloudinary.com%2Fopencollective%2Fimage%2Fupload%2Fv1508519428%2FS9gk78AS_400x400_fulq2l.jpg&height=96" alt="Facebook Open Source" height="96"></a> <a href="https://badoo.com/team?utm_source=eslint"><img src="https://images.opencollective.com/proxy/images/?src=https%3A%2F%2Fopencollective-production.s3-us-west-1.amazonaws.com%2Fbbdb9cc0-3b5d-11e9-9537-ad85092287b8.png&height=96" alt="Badoo" height="96"></a></p><h3>Silver Sponsors</h3>
<p><a href="https://www.ampproject.org/"><img src="https://images.opencollective.com/proxy/images/?src=https%3A%2F%2Fopencollective-production.s3-us-west-1.amazonaws.com%2F68ed8b70-ebf2-11e6-9958-cb7e79408c56.png&height=96" alt="AMP Project" height="64"></a></p><h3>Bronze Sponsors</h3> <p><a href="https://www.ampproject.org/"><img src="https://images.opencollective.com/proxy/images/?src=https%3A%2F%2Fopencollective-production.s3-us-west-1.amazonaws.com%2F68ed8b70-ebf2-11e6-9958-cb7e79408c56.png&height=96" alt="AMP Project" height="64"></a></p><h3>Bronze Sponsors</h3>
<p><a href="http://faithlife.com/ref/about"><img src="https://images.opencollective.com/proxy/images/?src=https%3A%2F%2Flogo.clearbit.com%2Ffaithlife.com&height=96" alt="Faithlife" height="32"></a></p> <p><a href="http://faithlife.com/ref/about"><img src="https://images.opencollective.com/proxy/images/?src=https%3A%2F%2Flogo.clearbit.com%2Ffaithlife.com&height=96" alt="Faithlife" height="32"></a></p>
<!--sponsorsend--> <!--sponsorsend-->

View File

@ -232,6 +232,7 @@ module.exports = {
"prefer-arrow-callback": require("./rules/prefer-arrow-callback"), "prefer-arrow-callback": require("./rules/prefer-arrow-callback"),
"prefer-const": require("./rules/prefer-const"), "prefer-const": require("./rules/prefer-const"),
"prefer-destructuring": require("./rules/prefer-destructuring"), "prefer-destructuring": require("./rules/prefer-destructuring"),
"prefer-named-capture-group": require("./rules/prefer-named-capture-group"),
"prefer-numeric-literals": require("./rules/prefer-numeric-literals"), "prefer-numeric-literals": require("./rules/prefer-numeric-literals"),
"prefer-object-spread": require("./rules/prefer-object-spread"), "prefer-object-spread": require("./rules/prefer-object-spread"),
"prefer-promise-reject-errors": require("./rules/prefer-promise-reject-errors"), "prefer-promise-reject-errors": require("./rules/prefer-promise-reject-errors"),

View File

@ -258,7 +258,7 @@ function processFile(filename, configHelper, options, linter) {
*/ */
function createIgnoreResult(filePath, baseDir) { function createIgnoreResult(filePath, baseDir) {
let message; let message;
const isHidden = /^\./.test(path.basename(filePath)); const isHidden = /^\./u.test(path.basename(filePath));
const isInNodeModules = baseDir && path.relative(baseDir, filePath).startsWith("node_modules"); const isInNodeModules = baseDir && path.relative(baseDir, filePath).startsWith("node_modules");
const isInBowerComponents = baseDir && path.relative(baseDir, filePath).startsWith("bower_components"); const isInBowerComponents = baseDir && path.relative(baseDir, filePath).startsWith("bower_components");
@ -757,7 +757,7 @@ class CLIEngine {
if (typeof resolvedFormatName === "string") { if (typeof resolvedFormatName === "string") {
// replace \ with / for Windows compatibility // replace \ with / for Windows compatibility
const normalizedFormatName = resolvedFormatName.replace(/\\/g, "/"); const normalizedFormatName = resolvedFormatName.replace(/\\/gu, "/");
const cwd = this.options ? this.options.cwd : process.cwd(); const cwd = this.options ? this.options.cwd : process.cwd();
const namespace = naming.getNamespaceFromTerm(normalizedFormatName); const namespace = naming.getNamespaceFromTerm(normalizedFormatName);

View File

@ -61,7 +61,7 @@ const resolver = new ModuleResolver();
* @private * @private
*/ */
function readFile(filePath) { function readFile(filePath) {
return fs.readFileSync(filePath, "utf8").replace(/^\ufeff/, ""); return fs.readFileSync(filePath, "utf8").replace(/^\ufeff/u, "");
} }
/** /**
@ -73,7 +73,7 @@ function readFile(filePath) {
* @private * @private
*/ */
function isFilePath(filePath) { function isFilePath(filePath) {
return path.isAbsolute(filePath) || !/\w|@/.test(filePath.charAt(0)); return path.isAbsolute(filePath) || !/\w|@/u.test(filePath.charAt(0));
} }
/** /**

View File

@ -152,7 +152,7 @@ function configureRules(answers, config) {
bar.tick(0); // Shows the progress bar bar.tick(0); // Shows the progress bar
// Get the SourceCode of all chosen files // Get the SourceCode of all chosen files
const patterns = answers.patterns.split(/[\s]+/); const patterns = answers.patterns.split(/[\s]+/u);
try { try {
sourceCodes = getSourceCodeOfFiles(patterns, { baseConfig: newConfig, useEslintrc: false }, total => { sourceCodes = getSourceCodeOfFiles(patterns, { baseConfig: newConfig, useEslintrc: false }, total => {

View File

@ -76,7 +76,7 @@ function validateRuleSeverity(options) {
return normSeverity; return normSeverity;
} }
throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/g, "\"").replace(/\n/g, "")}').\n`); throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`);
} }

View File

@ -84,7 +84,7 @@ class Plugins {
const shortName = naming.getShorthandName(longName, "eslint-plugin"); const shortName = naming.getShorthandName(longName, "eslint-plugin");
let plugin = null; let plugin = null;
if (pluginName.match(/\s+/)) { if (pluginName.match(/\s+/u)) {
const whitespaceError = new Error(`Whitespace found in plugin name '${pluginName}'`); const whitespaceError = new Error(`Whitespace found in plugin name '${pluginName}'`);
whitespaceError.messageTemplate = "whitespace-found"; whitespaceError.messageTemplate = "whitespace-found";

View File

@ -47,7 +47,7 @@ function formatFilePath(filePath, line, column) {
*/ */
function formatMessage(message, parentResult) { function formatMessage(message, parentResult) {
const type = (message.fatal || message.severity === 2) ? chalk.red("error") : chalk.yellow("warning"); const type = (message.fatal || message.severity === 2) ? chalk.red("error") : chalk.yellow("warning");
const msg = `${chalk.bold(message.message.replace(/([^ ])\.$/, "$1"))}`; const msg = `${chalk.bold(message.message.replace(/([^ ])\.$/u, "$1"))}`;
const ruleId = message.fatal ? "" : chalk.dim(`(${message.ruleId})`); const ruleId = message.fatal ? "" : chalk.dim(`(${message.ruleId})`);
const filePath = formatFilePath(parentResult.filePath, message.line, message.column); const filePath = formatFilePath(parentResult.filePath, message.line, message.column);
const sourceCode = parentResult.output ? parentResult.output : parentResult.source; const sourceCode = parentResult.output ? parentResult.output : parentResult.source;

View File

@ -65,7 +65,7 @@ module.exports = function(results) {
message.line || 0, message.line || 0,
message.column || 0, message.column || 0,
messageType, messageType,
message.message.replace(/([^ ])\.$/, "$1"), message.message.replace(/([^ ])\.$/u, "$1"),
chalk.dim(message.ruleId || "") chalk.dim(message.ruleId || "")
]; ];
}), }),
@ -75,7 +75,7 @@ module.exports = function(results) {
return stripAnsi(str).length; return stripAnsi(str).length;
} }
} }
).split("\n").map(el => el.replace(/(\d+)\s+(\d+)/, (m, p1, p2) => chalk.dim(`${p1}:${p2}`))).join("\n")}\n\n`; ).split("\n").map(el => el.replace(/(\d+)\s+(\d+)/u, (m, p1, p2) => chalk.dim(`${p1}:${p2}`))).join("\n")}\n\n`;
}); });
const total = errorCount + warningCount; const total = errorCount + warningCount;

View File

@ -11,6 +11,7 @@
const eslintScope = require("eslint-scope"), const eslintScope = require("eslint-scope"),
evk = require("eslint-visitor-keys"), evk = require("eslint-visitor-keys"),
espree = require("espree"),
lodash = require("lodash"), lodash = require("lodash"),
CodePathAnalyzer = require("./code-path-analysis/code-path-analyzer"), CodePathAnalyzer = require("./code-path-analysis/code-path-analyzer"),
ConfigOps = require("./config/config-ops"), ConfigOps = require("./config/config-ops"),
@ -163,7 +164,7 @@ function getDirectiveComments(filename, ast, ruleMapper) {
ast.comments.filter(token => token.type !== "Shebang").forEach(comment => { ast.comments.filter(token => token.type !== "Shebang").forEach(comment => {
const trimmedCommentText = comment.value.trim(); const trimmedCommentText = comment.value.trim();
const match = /^(eslint(-\w+){0,3}|exported|globals?)(\s|$)/.exec(trimmedCommentText); const match = /^(eslint(-\w+){0,3}|exported|globals?)(\s|$)/u.exec(trimmedCommentText);
if (!match) { if (!match) {
return; return;
@ -171,7 +172,7 @@ function getDirectiveComments(filename, ast, ruleMapper) {
const directiveValue = trimmedCommentText.slice(match.index + match[1].length); const directiveValue = trimmedCommentText.slice(match.index + match[1].length);
if (/^eslint-disable-(next-)?line$/.test(match[1])) { if (/^eslint-disable-(next-)?line$/u.test(match[1])) {
if (comment.loc.start.line === comment.loc.end.line) { if (comment.loc.start.line === comment.loc.end.line) {
const directiveType = match[1].slice("eslint-".length); const directiveType = match[1].slice("eslint-".length);
@ -275,7 +276,7 @@ function normalizeEcmaVersion(ecmaVersion, isModule) {
return ecmaVersion; return ecmaVersion;
} }
const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)\*\//g; const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)\*\//gu;
/** /**
* Checks whether or not there is a comment which has "eslint-env *" in a given text. * Checks whether or not there is a comment which has "eslint-env *" in a given text.
@ -497,7 +498,7 @@ function parse(text, providedParserOptions, parserName, parserMap, filePath) {
} catch (ex) { } catch (ex) {
// If the message includes a leading line number, strip it: // If the message includes a leading line number, strip it:
const message = `Parsing error: ${ex.message.replace(/^line \d+:/i, "").trim()}`; const message = `Parsing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`;
return { return {
success: false, success: false,
@ -776,6 +777,8 @@ module.exports = class Linter {
ruleMaps.set(this, new Rules()); ruleMaps.set(this, new Rules());
this.version = pkg.version; this.version = pkg.version;
this.environments = new Environments(); this.environments = new Environments();
this.defineParser("espree", espree);
} }
/** /**

View File

@ -34,13 +34,11 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
multiline: { multiline: {
type: "boolean", type: "boolean"
default: true
}, },
minItems: { minItems: {
type: ["integer", "null"], type: ["integer", "null"],
minimum: 0, minimum: 0
default: null
} }
}, },
additionalProperties: false additionalProperties: false

View File

@ -17,8 +17,8 @@ const astUtils = require("../util/ast-utils");
// Helpers // Helpers
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/; const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u;
const TARGET_METHODS = /^(?:every|filter|find(?:Index)?|map|reduce(?:Right)?|some|sort)$/; const TARGET_METHODS = /^(?:every|filter|find(?:Index)?|map|reduce(?:Right)?|some|sort)$/u;
/** /**
* Checks a given code path segment is reachable. * Checks a given code path segment is reachable.

View File

@ -34,13 +34,11 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
multiline: { multiline: {
type: "boolean", type: "boolean"
default: false
}, },
minItems: { minItems: {
type: ["integer", "null"], type: ["integer", "null"],
minimum: 0, minimum: 0
default: null
} }
}, },
additionalProperties: false additionalProperties: false

View File

@ -46,7 +46,7 @@ module.exports = {
{ {
type: "object", type: "object",
properties: { properties: {
requireReturnForObjectLiteral: { type: "boolean", default: false } requireReturnForObjectLiteral: { type: "boolean" }
}, },
additionalProperties: false additionalProperties: false
} }
@ -82,7 +82,7 @@ module.exports = {
* @returns {boolean} `true` if it changes semantics if `;` or `}` followed by the token are removed. * @returns {boolean} `true` if it changes semantics if `;` or `}` followed by the token are removed.
*/ */
function hasASIProblem(token) { function hasASIProblem(token) {
return token && token.type === "Punctuator" && /^[([/`+-]/.test(token.value); return token && token.type === "Punctuator" && /^[([/`+-]/u.test(token.value);
} }
/** /**

View File

@ -90,7 +90,7 @@ module.exports = {
*/ */
function isAllowed(name) { function isAllowed(name) {
return allow.findIndex( return allow.findIndex(
entry => name === entry || name.match(new RegExp(entry)) entry => name === entry || name.match(new RegExp(entry)) // eslint-disable-line require-unicode-regexp
) !== -1; ) !== -1;
} }
@ -142,7 +142,7 @@ module.exports = {
* private/protected identifiers, strip them before checking if underscored * private/protected identifiers, strip them before checking if underscored
*/ */
const name = node.name, const name = node.name,
nameIsUnderscored = isUnderscored(name.replace(/^_+|_+$/g, "")), nameIsUnderscored = isUnderscored(name.replace(/^_+|_+$/gu, "")),
effectiveParent = (node.parent.type === "MemberExpression") ? node.parent.parent : node.parent; effectiveParent = (node.parent.type === "MemberExpression") ? node.parent.parent : node.parent;
// First, we ignore the node if it match the ignore list // First, we ignore the node if it match the ignore list

View File

@ -16,8 +16,8 @@ const astUtils = require("../util/ast-utils");
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const DEFAULT_IGNORE_PATTERN = astUtils.COMMENTS_IGNORE_PATTERN, const DEFAULT_IGNORE_PATTERN = astUtils.COMMENTS_IGNORE_PATTERN,
WHITESPACE = /\s/g, WHITESPACE = /\s/gu,
MAYBE_URL = /^\s*[^:/?#\s]+:\/\/[^?#]/; // TODO: Combine w/ max-len pattern? MAYBE_URL = /^\s*[^:/?#\s]+:\/\/[^?#]/u; // TODO: Combine w/ max-len pattern?
/* /*
* Base schema body for defining the basic capitalization rule, ignorePattern, * Base schema body for defining the basic capitalization rule, ignorePattern,
@ -28,27 +28,22 @@ const SCHEMA_BODY = {
type: "object", type: "object",
properties: { properties: {
ignorePattern: { ignorePattern: {
type: "string", type: "string"
default: ""
}, },
ignoreInlineComments: { ignoreInlineComments: {
type: "boolean", type: "boolean"
default: false
}, },
ignoreConsecutiveComments: { ignoreConsecutiveComments: {
type: "boolean", type: "boolean"
default: false
} }
}, },
additionalProperties: false additionalProperties: false
}; };
const DEFAULTS = Object.keys(SCHEMA_BODY.properties).reduce( const DEFAULTS = {
(obj, current) => { ignorePattern: "",
obj[current] = SCHEMA_BODY.properties[current].default; ignoreInlineComments: false,
return obj; ignoreConsecutiveComments: false
}, };
{}
);
/** /**
* Get normalized options for either block or line comments from the given * Get normalized options for either block or line comments from the given
@ -96,7 +91,7 @@ function createRegExpForIgnorePatterns(normalizedOptions) {
const ignorePatternStr = normalizedOptions[key].ignorePattern; const ignorePatternStr = normalizedOptions[key].ignorePattern;
if (ignorePatternStr) { if (ignorePatternStr) {
const regExp = RegExp(`^\\s*(?:${ignorePatternStr})`); const regExp = RegExp(`^\\s*(?:${ignorePatternStr})`); // eslint-disable-line require-unicode-regexp
normalizedOptions[key].ignorePatternRegExp = regExp; normalizedOptions[key].ignorePatternRegExp = regExp;
} }
@ -215,7 +210,7 @@ module.exports = {
// 2. Check for custom ignore pattern. // 2. Check for custom ignore pattern.
const commentWithoutAsterisks = comment.value const commentWithoutAsterisks = comment.value
.replace(/\*/g, ""); .replace(/\*/gu, "");
if (options.ignorePatternRegExp && options.ignorePatternRegExp.test(commentWithoutAsterisks)) { if (options.ignorePatternRegExp && options.ignorePatternRegExp.test(commentWithoutAsterisks)) {
return true; return true;

View File

@ -41,13 +41,11 @@ module.exports = {
properties: { properties: {
maximum: { maximum: {
type: "integer", type: "integer",
minimum: 0, minimum: 0
default: 20
}, },
max: { max: {
type: "integer", type: "integer",
minimum: 0, minimum: 0
default: 20
} }
}, },
additionalProperties: false additionalProperties: false
@ -65,7 +63,10 @@ module.exports = {
const option = context.options[0]; const option = context.options[0];
let THRESHOLD = 20; let THRESHOLD = 20;
if (typeof option === "object") { if (
typeof option === "object" &&
(Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max"))
) {
THRESHOLD = option.maximum || option.max; THRESHOLD = option.maximum || option.max;
} else if (typeof option === "number") { } else if (typeof option === "number") {
THRESHOLD = option; THRESHOLD = option;

View File

@ -191,7 +191,7 @@ module.exports = {
return true; return true;
} }
if (/^[([/`+-]/.test(tokenAfter.value)) { if (/^[([/`+-]/u.test(tokenAfter.value)) {
// If the next token starts with a character that would disrupt ASI, insert a semicolon. // If the next token starts with a character that would disrupt ASI, insert a semicolon.
return true; return true;

View File

@ -4,7 +4,7 @@
*/ */
"use strict"; "use strict";
const DEFAULT_COMMENT_PATTERN = /^no default$/i; const DEFAULT_COMMENT_PATTERN = /^no default$/iu;
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Rule Definition // Rule Definition
@ -39,7 +39,7 @@ module.exports = {
create(context) { create(context) {
const options = context.options[0] || {}; const options = context.options[0] || {};
const commentPattern = options.commentPattern const commentPattern = options.commentPattern
? new RegExp(options.commentPattern) ? new RegExp(options.commentPattern) // eslint-disable-line require-unicode-regexp
: DEFAULT_COMMENT_PATTERN; : DEFAULT_COMMENT_PATTERN;
const sourceCode = context.getSourceCode(); const sourceCode = context.getSourceCode();

View File

@ -14,7 +14,7 @@ const astUtils = require("../util/ast-utils");
// Rule Definition // Rule Definition
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/; const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/u;
const keywords = require("../util/keywords"); const keywords = require("../util/keywords");
module.exports = { module.exports = {
@ -61,7 +61,7 @@ module.exports = {
let allowPattern; let allowPattern;
if (options.allowPattern) { if (options.allowPattern) {
allowPattern = new RegExp(options.allowPattern); allowPattern = new RegExp(options.allowPattern); // eslint-disable-line require-unicode-regexp
} }
/** /**

View File

@ -97,7 +97,7 @@ module.exports = {
loc: location, loc: location,
messageId: "unexpected", messageId: "unexpected",
fix(fixer) { fix(fixer) {
const finalEOLs = /(?:\r?\n)+$/, const finalEOLs = /(?:\r?\n)+$/u,
match = finalEOLs.exec(sourceCode.text), match = finalEOLs.exec(sourceCode.text),
start = match.index, start = match.index,
end = sourceCode.text.length; end = sourceCode.text.length;

View File

@ -38,8 +38,7 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
null: { null: {
enum: ["always", "never", "ignore"], enum: ["always", "never", "ignore"]
default: "always"
} }
}, },
additionalProperties: false additionalProperties: false

View File

@ -50,8 +50,7 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
allowNewlines: { allowNewlines: {
type: "boolean", type: "boolean"
default: false
} }
}, },
additionalProperties: false additionalProperties: false
@ -93,8 +92,8 @@ module.exports = {
return; return;
} }
const textBetweenTokens = text.slice(prevToken.range[1], parenToken.range[0]).replace(/\/\*.*?\*\//g, ""); const textBetweenTokens = text.slice(prevToken.range[1], parenToken.range[0]).replace(/\/\*.*?\*\//gu, "");
const hasWhitespace = /\s/.test(textBetweenTokens); const hasWhitespace = /\s/u.test(textBetweenTokens);
const hasNewline = hasWhitespace && astUtils.LINEBREAK_MATCHER.test(textBetweenTokens); const hasNewline = hasWhitespace && astUtils.LINEBREAK_MATCHER.test(textBetweenTokens);
/* /*

View File

@ -14,7 +14,7 @@ const astUtils = require("../util/ast-utils");
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Helpers // Helpers
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/; const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u;
/** /**
* Checks a given code path segment is reachable. * Checks a given code path segment is reachable.

View File

@ -52,7 +52,7 @@ module.exports = {
*/ */
function matchesConfiguredErrorName(name) { function matchesConfiguredErrorName(name) {
if (isPattern(errorArgument)) { if (isPattern(errorArgument)) {
const regexp = new RegExp(errorArgument); const regexp = new RegExp(errorArgument); // eslint-disable-line require-unicode-regexp
return regexp.test(name); return regexp.test(name);
} }

View File

@ -53,7 +53,7 @@ module.exports = {
// Options // Options
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
const pattern = context.options[0] || "^.+$", const pattern = context.options[0] || "^.+$",
regexp = new RegExp(pattern); regexp = new RegExp(pattern); // eslint-disable-line require-unicode-regexp
const options = context.options[1] || {}, const options = context.options[1] || {},
properties = !!options.properties, properties = !!options.properties,

View File

@ -975,7 +975,7 @@ module.exports = {
* @returns {boolean} the result * @returns {boolean} the result
*/ */
function isWrappedInParenthesis(node) { function isWrappedInParenthesis(node) {
const regex = /^return\s*?\(\s*?\);*?/; const regex = /^return\s*?\(\s*?\);*?/u;
const statementWithoutArgument = sourceCode.getText(node).replace( const statementWithoutArgument = sourceCode.getText(node).replace(
sourceCode.getText(node.argument), "" sourceCode.getText(node.argument), ""

View File

@ -442,7 +442,7 @@ class OffsetStorage {
const offset = ( const offset = (
offsetInfo.from && offsetInfo.from &&
offsetInfo.from.loc.start.line === token.loc.start.line && offsetInfo.from.loc.start.line === token.loc.start.line &&
!/^\s*?\n/.test(token.value) && !/^\s*?\n/u.test(token.value) &&
!offsetInfo.force !offsetInfo.force
) ? 0 : offsetInfo.offset * this._indentSize; ) ? 0 : offsetInfo.offset * this._indentSize;
@ -785,7 +785,7 @@ module.exports = {
* or the total number of linebreaks if the string is all whitespace. * or the total number of linebreaks if the string is all whitespace.
*/ */
function countTrailingLinebreaks(string) { function countTrailingLinebreaks(string) {
const trailingWhitespace = string.match(/\s*$/)[0]; const trailingWhitespace = string.match(/\s*$/u)[0];
const linebreakMatches = trailingWhitespace.match(astUtils.createGlobalLinebreakMatcher()); const linebreakMatches = trailingWhitespace.match(astUtils.createGlobalLinebreakMatcher());
return linebreakMatches === null ? 0 : linebreakMatches.length; return linebreakMatches === null ? 0 : linebreakMatches.length;

View File

@ -75,8 +75,7 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
ignoreForLoopInit: { ignoreForLoopInit: {
type: "boolean", type: "boolean"
default: false
} }
}, },
additionalProperties: false additionalProperties: false

View File

@ -20,14 +20,14 @@ const QUOTE_SETTINGS = {
quote: "\"", quote: "\"",
description: "singlequote", description: "singlequote",
convert(str) { convert(str) {
return str.replace(/'/g, "\""); return str.replace(/'/gu, "\"");
} }
}, },
"prefer-single": { "prefer-single": {
quote: "'", quote: "'",
description: "doublequote", description: "doublequote",
convert(str) { convert(str) {
return str.replace(/"/g, "'"); return str.replace(/"/gu, "'");
} }
} }
}; };

View File

@ -148,20 +148,16 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
mode: { mode: {
enum: ["strict", "minimum"], enum: ["strict", "minimum"]
default: "strict"
}, },
on: { on: {
enum: ["colon", "value"], enum: ["colon", "value"]
default: "colon"
}, },
beforeColon: { beforeColon: {
type: "boolean", type: "boolean"
default: false
}, },
afterColon: { afterColon: {
type: "boolean", type: "boolean"
default: true
} }
}, },
additionalProperties: false additionalProperties: false
@ -169,16 +165,13 @@ module.exports = {
] ]
}, },
mode: { mode: {
enum: ["strict", "minimum"], enum: ["strict", "minimum"]
default: "strict"
}, },
beforeColon: { beforeColon: {
type: "boolean", type: "boolean"
default: false
}, },
afterColon: { afterColon: {
type: "boolean", type: "boolean"
default: true
} }
}, },
additionalProperties: false additionalProperties: false
@ -190,16 +183,13 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
mode: { mode: {
enum: ["strict", "minimum"], enum: ["strict", "minimum"]
default: "strict"
}, },
beforeColon: { beforeColon: {
type: "boolean", type: "boolean"
default: false
}, },
afterColon: { afterColon: {
type: "boolean", type: "boolean"
default: true
} }
}, },
additionalProperties: false additionalProperties: false
@ -216,20 +206,16 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
mode: { mode: {
enum: ["strict", "minimum"], enum: ["strict", "minimum"]
default: "strict"
}, },
on: { on: {
enum: ["colon", "value"], enum: ["colon", "value"]
default: "colon"
}, },
beforeColon: { beforeColon: {
type: "boolean", type: "boolean"
default: false
}, },
afterColon: { afterColon: {
type: "boolean", type: "boolean"
default: true
} }
}, },
additionalProperties: false additionalProperties: false
@ -237,16 +223,13 @@ module.exports = {
] ]
}, },
mode: { mode: {
enum: ["strict", "minimum"], enum: ["strict", "minimum"]
default: "strict"
}, },
beforeColon: { beforeColon: {
type: "boolean", type: "boolean"
default: false
}, },
afterColon: { afterColon: {
type: "boolean", type: "boolean"
default: true
} }
}, },
additionalProperties: false additionalProperties: false
@ -261,16 +244,13 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
mode: { mode: {
enum: ["strict", "minimum"], enum: ["strict", "minimum"]
default: "strict"
}, },
beforeColon: { beforeColon: {
type: "boolean", type: "boolean"
default: false
}, },
afterColon: { afterColon: {
type: "boolean", type: "boolean"
default: true
} }
}, },
additionalProperties: false additionalProperties: false
@ -279,16 +259,13 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
mode: { mode: {
enum: ["strict", "minimum"], enum: ["strict", "minimum"]
default: "strict"
}, },
beforeColon: { beforeColon: {
type: "boolean", type: "boolean"
default: false
}, },
afterColon: { afterColon: {
type: "boolean", type: "boolean"
default: true
} }
}, },
additionalProperties: false additionalProperties: false
@ -297,20 +274,16 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
mode: { mode: {
enum: ["strict", "minimum"], enum: ["strict", "minimum"]
default: "strict"
}, },
on: { on: {
enum: ["colon", "value"], enum: ["colon", "value"]
default: "colon"
}, },
beforeColon: { beforeColon: {
type: "boolean", type: "boolean"
default: false
}, },
afterColon: { afterColon: {
type: "boolean", type: "boolean"
default: true
} }
}, },
additionalProperties: false additionalProperties: false
@ -528,7 +501,7 @@ module.exports = {
* @returns {Object} Whitespace before and after the property's colon. * @returns {Object} Whitespace before and after the property's colon.
*/ */
function getPropertyWhitespace(property) { function getPropertyWhitespace(property) {
const whitespace = /(\s*):(\s*)/.exec(sourceCode.getText().slice( const whitespace = /(\s*):(\s*)/u.exec(sourceCode.getText().slice(
property.key.range[1], property.value.range[0] property.key.range[1], property.value.range[0]
)); ));

View File

@ -16,13 +16,13 @@ const astUtils = require("../util/ast-utils"),
// Constants // Constants
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const PREV_TOKEN = /^[)\]}>]$/; const PREV_TOKEN = /^[)\]}>]$/u;
const NEXT_TOKEN = /^(?:[([{<~!]|\+\+?|--?)$/; const NEXT_TOKEN = /^(?:[([{<~!]|\+\+?|--?)$/u;
const PREV_TOKEN_M = /^[)\]}>*]$/; const PREV_TOKEN_M = /^[)\]}>*]$/u;
const NEXT_TOKEN_M = /^[{*]$/; const NEXT_TOKEN_M = /^[{*]$/u;
const TEMPLATE_OPEN_PAREN = /\$\{$/; const TEMPLATE_OPEN_PAREN = /\$\{$/u;
const TEMPLATE_CLOSE_PAREN = /^\}/; const TEMPLATE_CLOSE_PAREN = /^\}/u;
const CHECK_TYPE = /^(?:JSXElement|RegularExpression|String|Template)$/; const CHECK_TYPE = /^(?:JSXElement|RegularExpression|String|Template)$/u;
const KEYS = keywords.concat(["as", "async", "await", "from", "get", "let", "of", "set", "yield"]); const KEYS = keywords.concat(["as", "async", "await", "from", "get", "let", "of", "set", "yield"]);
// check duplications. // check duplications.

View File

@ -38,12 +38,10 @@ module.exports = {
type: "string" type: "string"
}, },
applyDefaultPatterns: { applyDefaultPatterns: {
type: "boolean", type: "boolean"
default: true
}, },
applyDefaultIgnorePatterns: { applyDefaultIgnorePatterns: {
type: "boolean", type: "boolean"
default: true
} }
}, },
additionalProperties: false additionalProperties: false
@ -74,13 +72,13 @@ module.exports = {
if (Object.prototype.hasOwnProperty.call(options, "applyDefaultIgnorePatterns")) { if (Object.prototype.hasOwnProperty.call(options, "applyDefaultIgnorePatterns")) {
applyDefaultIgnorePatterns = options.applyDefaultIgnorePatterns; applyDefaultIgnorePatterns = options.applyDefaultIgnorePatterns;
} else { } else {
applyDefaultIgnorePatterns = options.applyDefaultPatterns; applyDefaultIgnorePatterns = options.applyDefaultPatterns !== false;
} }
} }
const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN; const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN;
const fallThroughRegExp = /^\s*falls?\s?through/; const fallThroughRegExp = /^\s*falls?\s?through/u;
const customIgnoreRegExp = new RegExp(ignorePattern); const customIgnoreRegExp = new RegExp(ignorePattern); // eslint-disable-line require-unicode-regexp
const sourceCode = context.getSourceCode(); const sourceCode = context.getSourceCode();
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------

View File

@ -130,7 +130,7 @@ module.exports = {
const options = Object.assign({}, context.options[0]); const options = Object.assign({}, context.options[0]);
const ignorePattern = options.ignorePattern; const ignorePattern = options.ignorePattern;
const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN; const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN;
const customIgnoreRegExp = new RegExp(ignorePattern); const customIgnoreRegExp = new RegExp(ignorePattern); // eslint-disable-line require-unicode-regexp
const applyDefaultIgnorePatterns = options.applyDefaultIgnorePatterns !== false; const applyDefaultIgnorePatterns = options.applyDefaultIgnorePatterns !== false;
options.beforeBlockComment = typeof options.beforeBlockComment !== "undefined" ? options.beforeBlockComment : true; options.beforeBlockComment = typeof options.beforeBlockComment !== "undefined" ? options.beforeBlockComment : true;

View File

@ -32,13 +32,11 @@ module.exports = {
properties: { properties: {
maximum: { maximum: {
type: "integer", type: "integer",
minimum: 0, minimum: 0
default: 4
}, },
max: { max: {
type: "integer", type: "integer",
minimum: 0, minimum: 0
default: 4
} }
}, },
additionalProperties: false additionalProperties: false
@ -61,7 +59,10 @@ module.exports = {
option = context.options[0]; option = context.options[0];
let maxDepth = 4; let maxDepth = 4;
if (typeof option === "object") { if (
typeof option === "object" &&
(Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max"))
) {
maxDepth = option.maximum || option.max; maxDepth = option.maximum || option.max;
} }
if (typeof option === "number") { if (typeof option === "number") {

View File

@ -103,7 +103,7 @@ module.exports = {
* too many false positives * too many false positives
* - We don't care about matching the entire URL, any small segment is fine * - We don't care about matching the entire URL, any small segment is fine
*/ */
const URL_REGEXP = /[^:/?#]:\/\/[^?#]/; const URL_REGEXP = /[^:/?#]:\/\/[^?#]/u;
const sourceCode = context.getSourceCode(); const sourceCode = context.getSourceCode();
@ -118,7 +118,7 @@ module.exports = {
function computeLineLength(line, tabWidth) { function computeLineLength(line, tabWidth) {
let extraCharacterCount = 0; let extraCharacterCount = 0;
line.replace(/\t/g, (match, offset) => { line.replace(/\t/gu, (match, offset) => {
const totalOffset = offset + extraCharacterCount, const totalOffset = offset + extraCharacterCount,
previousTabStopOffset = tabWidth ? totalOffset % tabWidth : 0, previousTabStopOffset = tabWidth ? totalOffset % tabWidth : 0,
spaceCount = tabWidth - previousTabStopOffset; spaceCount = tabWidth - previousTabStopOffset;
@ -153,7 +153,7 @@ module.exports = {
let ignorePattern = options.ignorePattern || null; let ignorePattern = options.ignorePattern || null;
if (ignorePattern) { if (ignorePattern) {
ignorePattern = new RegExp(ignorePattern); ignorePattern = new RegExp(ignorePattern); // eslint-disable-line require-unicode-regexp
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
@ -201,7 +201,7 @@ module.exports = {
function stripTrailingComment(line, comment) { function stripTrailingComment(line, comment) {
// loc.column is zero-indexed // loc.column is zero-indexed
return line.slice(0, comment.loc.start.column).replace(/\s+$/, ""); return line.slice(0, comment.loc.start.column).replace(/\s+$/u, "");
} }
/** /**

View File

@ -187,7 +187,7 @@ module.exports = {
} }
if (skipBlankLines) { if (skipBlankLines) {
if (line.match(/^\s*$/)) { if (line.match(/^\s*$/u)) {
continue; continue;
} }
} }

View File

@ -38,16 +38,13 @@ module.exports = {
properties: { properties: {
max: { max: {
type: "integer", type: "integer",
minimum: 0, minimum: 0
default: 300
}, },
skipComments: { skipComments: {
type: "boolean", type: "boolean"
default: false
}, },
skipBlankLines: { skipBlankLines: {
type: "boolean", type: "boolean"
default: false
} }
}, },
additionalProperties: false additionalProperties: false
@ -64,7 +61,7 @@ module.exports = {
const option = context.options[0]; const option = context.options[0];
let max = 300; let max = 300;
if (typeof option === "object") { if (typeof option === "object" && Object.prototype.hasOwnProperty.call(option, "max")) {
max = option.max; max = option.max;
} else if (typeof option === "number") { } else if (typeof option === "number") {
max = option; max = option;

View File

@ -32,13 +32,11 @@ module.exports = {
properties: { properties: {
maximum: { maximum: {
type: "integer", type: "integer",
minimum: 0, minimum: 0
default: 10
}, },
max: { max: {
type: "integer", type: "integer",
minimum: 0, minimum: 0
default: 10
} }
}, },
additionalProperties: false additionalProperties: false
@ -59,7 +57,10 @@ module.exports = {
const option = context.options[0]; const option = context.options[0];
let THRESHOLD = 10; let THRESHOLD = 10;
if (typeof option === "object") { if (
typeof option === "object" &&
(Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max"))
) {
THRESHOLD = option.maximum || option.max; THRESHOLD = option.maximum || option.max;
} else if (typeof option === "number") { } else if (typeof option === "number") {
THRESHOLD = option; THRESHOLD = option;

View File

@ -40,13 +40,11 @@ module.exports = {
properties: { properties: {
maximum: { maximum: {
type: "integer", type: "integer",
minimum: 0, minimum: 0
default: 3
}, },
max: { max: {
type: "integer", type: "integer",
minimum: 0, minimum: 0
default: 3
} }
}, },
additionalProperties: false additionalProperties: false
@ -64,7 +62,10 @@ module.exports = {
const option = context.options[0]; const option = context.options[0];
let numParams = 3; let numParams = 3;
if (typeof option === "object") { if (
typeof option === "object" &&
(Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max"))
) {
numParams = option.maximum || option.max; numParams = option.maximum || option.max;
} }
if (typeof option === "number") { if (typeof option === "number") {

View File

@ -57,7 +57,7 @@ module.exports = {
// Helpers // Helpers
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
const SINGLE_CHILD_ALLOWED = /^(?:(?:DoWhile|For|ForIn|ForOf|If|Labeled|While)Statement|Export(?:Default|Named)Declaration)$/; const SINGLE_CHILD_ALLOWED = /^(?:(?:DoWhile|For|ForIn|ForOf|If|Labeled|While)Statement|Export(?:Default|Named)Declaration)$/u;
/** /**
* Reports with the first extra statement, and clears it. * Reports with the first extra statement, and clears it.

View File

@ -40,13 +40,11 @@ module.exports = {
properties: { properties: {
maximum: { maximum: {
type: "integer", type: "integer",
minimum: 0, minimum: 0
default: 10
}, },
max: { max: {
type: "integer", type: "integer",
minimum: 0, minimum: 0
default: 10
} }
}, },
additionalProperties: false additionalProperties: false
@ -80,7 +78,10 @@ module.exports = {
topLevelFunctions = []; topLevelFunctions = [];
let maxStatements = 10; let maxStatements = 10;
if (typeof option === "object") { if (
typeof option === "object" &&
(Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max"))
) {
maxStatements = option.maximum || option.max; maxStatements = option.maximum || option.max;
} else if (typeof option === "number") { } else if (typeof option === "number") {
maxStatements = option; maxStatements = option;

View File

@ -52,7 +52,7 @@ module.exports = {
} }
return commentGroup[0].value return commentGroup[0].value
.split(astUtils.LINEBREAK_MATCHER) .split(astUtils.LINEBREAK_MATCHER)
.map(line => line.replace(/^\s*\*?/, "")); .map(line => line.replace(/^\s*\*?/u, ""));
} }
/** /**
@ -103,9 +103,9 @@ module.exports = {
const lines = commentGroup[0].value.split(astUtils.LINEBREAK_MATCHER); const lines = commentGroup[0].value.split(astUtils.LINEBREAK_MATCHER);
return commentGroup[0].type === "Block" && return commentGroup[0].type === "Block" &&
/^\*\s*$/.test(lines[0]) && /^\*\s*$/u.test(lines[0]) &&
lines.slice(1, -1).every(line => /^\s* /.test(line)) && lines.slice(1, -1).every(line => /^\s* /u.test(line)) &&
/^\s*$/.test(lines[lines.length - 1]); /^\s*$/u.test(lines[lines.length - 1]);
} }
/** /**
@ -143,7 +143,7 @@ module.exports = {
const lines = block.value.split(astUtils.LINEBREAK_MATCHER); const lines = block.value.split(astUtils.LINEBREAK_MATCHER);
const expectedLinePrefix = `${sourceCode.text.slice(block.range[0] - block.loc.start.column, block.range[0])} *`; const expectedLinePrefix = `${sourceCode.text.slice(block.range[0] - block.loc.start.column, block.range[0])} *`;
if (!/^\*?\s*$/.test(lines[0])) { if (!/^\*?\s*$/u.test(lines[0])) {
const start = block.value.startsWith("*") ? block.range[0] + 1 : block.range[0]; const start = block.value.startsWith("*") ? block.range[0] + 1 : block.range[0];
context.report({ context.report({
@ -156,7 +156,7 @@ module.exports = {
}); });
} }
if (!/^\s*$/.test(lines[lines.length - 1])) { if (!/^\s*$/u.test(lines[lines.length - 1])) {
context.report({ context.report({
loc: { loc: {
start: { line: block.loc.end.line, column: block.loc.end.column - 2 }, start: { line: block.loc.end.line, column: block.loc.end.column - 2 },
@ -176,12 +176,12 @@ module.exports = {
start: { line: lineNumber, column: 0 }, start: { line: lineNumber, column: 0 },
end: { line: lineNumber, column: sourceCode.lines[lineNumber - 1].length } end: { line: lineNumber, column: sourceCode.lines[lineNumber - 1].length }
}, },
messageId: /^\s*\*/.test(lineText) messageId: /^\s*\*/u.test(lineText)
? "alignment" ? "alignment"
: "missingStar", : "missingStar",
fix(fixer) { fix(fixer) {
const lineStartIndex = sourceCode.getIndexFromLoc({ line: lineNumber, column: 0 }); const lineStartIndex = sourceCode.getIndexFromLoc({ line: lineNumber, column: 0 });
const linePrefixLength = lineText.match(/^\s*\*? ?/)[0].length; const linePrefixLength = lineText.match(/^\s*\*? ?/u)[0].length;
const commentStartIndex = lineStartIndex + linePrefixLength; const commentStartIndex = lineStartIndex + linePrefixLength;
const replacementText = lineNumber === block.loc.end.line || lineText.length === linePrefixLength const replacementText = lineNumber === block.loc.end.line || lineText.length === linePrefixLength
@ -244,7 +244,7 @@ module.exports = {
const block = commentGroup[0]; const block = commentGroup[0];
const lines = block.value.split(astUtils.LINEBREAK_MATCHER).filter(line => line.trim()); const lines = block.value.split(astUtils.LINEBREAK_MATCHER).filter(line => line.trim());
if (lines.length > 0 && lines.every(line => /^\s*\*/.test(line))) { if (lines.length > 0 && lines.every(line => /^\s*\*/u.test(line))) {
context.report({ context.report({
loc: { loc: {
start: block.loc.start, start: block.loc.start,

View File

@ -136,10 +136,10 @@ module.exports = {
const skipProperties = config.properties === false; const skipProperties = config.properties === false;
const newIsCapExceptions = checkArray(config, "newIsCapExceptions", []).reduce(invert, {}); const newIsCapExceptions = checkArray(config, "newIsCapExceptions", []).reduce(invert, {});
const newIsCapExceptionPattern = config.newIsCapExceptionPattern ? new RegExp(config.newIsCapExceptionPattern) : null; const newIsCapExceptionPattern = config.newIsCapExceptionPattern ? new RegExp(config.newIsCapExceptionPattern) : null; // eslint-disable-line require-unicode-regexp
const capIsNewExceptions = calculateCapIsNewExceptions(config); const capIsNewExceptions = calculateCapIsNewExceptions(config);
const capIsNewExceptionPattern = config.capIsNewExceptionPattern ? new RegExp(config.capIsNewExceptionPattern) : null; const capIsNewExceptionPattern = config.capIsNewExceptionPattern ? new RegExp(config.capIsNewExceptionPattern) : null; // eslint-disable-line require-unicode-regexp
const listeners = {}; const listeners = {};

View File

@ -20,7 +20,7 @@ const getPropertyName = require("../util/ast-utils").getStaticPropertyName;
* @returns {boolean} Whether or not the name is prohibited. * @returns {boolean} Whether or not the name is prohibited.
*/ */
function isProhibitedIdentifier(name) { function isProhibitedIdentifier(name) {
return /^(alert|confirm|prompt)$/.test(name); return /^(alert|confirm|prompt)$/u.test(name);
} }
/** /**

View File

@ -35,7 +35,7 @@ module.exports = {
const objectName = node.object.name, const objectName = node.object.name,
propertyName = node.property.name; propertyName = node.property.name;
if (objectName === "arguments" && !node.computed && propertyName && propertyName.match(/^calle[er]$/)) { if (objectName === "arguments" && !node.computed && propertyName && propertyName.match(/^calle[er]$/u)) {
context.report({ node, messageId: "unexpected", data: { prop: propertyName } }); context.report({ node, messageId: "unexpected", data: { prop: propertyName } });
} }

View File

@ -15,8 +15,8 @@ const astUtils = require("../util/ast-utils");
// Helpers // Helpers
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const GET_KIND = /^(?:init|get)$/; const GET_KIND = /^(?:init|get)$/u;
const SET_KIND = /^(?:init|set)$/; const SET_KIND = /^(?:init|set)$/u;
/** /**
* The class which stores properties' information of an object. * The class which stores properties' information of an object.

View File

@ -82,7 +82,7 @@ module.exports = {
* after the if block * after the if block
*/ */
const ifBlockMaybeUnsafe = node.parent.consequent.type !== "BlockStatement" && lastIfToken.value !== ";"; const ifBlockMaybeUnsafe = node.parent.consequent.type !== "BlockStatement" && lastIfToken.value !== ";";
const elseBlockUnsafe = /^[([/+`-]/.test(firstTokenOfElseBlock.value); const elseBlockUnsafe = /^[([/+`-]/u.test(firstTokenOfElseBlock.value);
if (ifBlockMaybeUnsafe && elseBlockUnsafe) { if (ifBlockMaybeUnsafe && elseBlockUnsafe) {
return null; return null;
@ -94,7 +94,7 @@ module.exports = {
if (lastTokenOfElseBlock.value !== ";") { if (lastTokenOfElseBlock.value !== ";") {
const nextToken = sourceCode.getTokenAfter(endToken); const nextToken = sourceCode.getTokenAfter(endToken);
const nextTokenUnsafe = nextToken && /^[([/+`-]/.test(nextToken.value); const nextTokenUnsafe = nextToken && /^[([/+`-]/u.test(nextToken.value);
const nextTokenOnSameLine = nextToken && nextToken.loc.start.line === lastTokenOfElseBlock.loc.start.line; const nextTokenOnSameLine = nextToken && nextToken.loc.start.line === lastTokenOfElseBlock.loc.start.line;
/* /*

View File

@ -21,7 +21,7 @@
* 4. `[gimuy]*`: optional regexp flags * 4. `[gimuy]*`: optional regexp flags
* 5. `$`: fix the match at the end of the string * 5. `$`: fix the match at the end of the string
*/ */
const regex = /^\/([^\\[]|\\.|\[([^\\\]]|\\.)+])*\/[gimuys]*$/; const regex = /^\/([^\\[]|\\.|\[([^\\\]]|\\.)+\])*\/[gimuys]*$/u;
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Rule Definition // Rule Definition

View File

@ -44,11 +44,11 @@ module.exports = {
{ {
type: "object", type: "object",
properties: { properties: {
conditionalAssign: { type: "boolean", default: true }, conditionalAssign: { type: "boolean" },
nestedBinaryExpressions: { type: "boolean", default: true }, nestedBinaryExpressions: { type: "boolean" },
returnAssign: { type: "boolean", default: true }, returnAssign: { type: "boolean" },
ignoreJSX: { enum: ["none", "all", "single-line", "multi-line"] }, ignoreJSX: { enum: ["none", "all", "single-line", "multi-line"] },
enforceForArrowConditionals: { type: "boolean", default: true } enforceForArrowConditionals: { type: "boolean" }
}, },
additionalProperties: false additionalProperties: false
} }
@ -471,6 +471,7 @@ module.exports = {
const firstToken = isParenthesised(node) ? sourceCode.getTokenBefore(node) : sourceCode.getFirstToken(node); const firstToken = isParenthesised(node) ? sourceCode.getTokenBefore(node) : sourceCode.getFirstToken(node);
const secondToken = sourceCode.getTokenAfter(firstToken, astUtils.isNotOpeningParenToken); const secondToken = sourceCode.getTokenAfter(firstToken, astUtils.isNotOpeningParenToken);
const thirdToken = secondToken ? sourceCode.getTokenAfter(secondToken) : null; const thirdToken = secondToken ? sourceCode.getTokenAfter(secondToken) : null;
const tokenAfterClosingParens = secondToken ? sourceCode.getTokenAfter(secondToken, astUtils.isNotClosingParenToken) : null;
if ( if (
astUtils.isOpeningParenToken(firstToken) && astUtils.isOpeningParenToken(firstToken) &&
@ -479,7 +480,12 @@ module.exports = {
secondToken.type === "Keyword" && ( secondToken.type === "Keyword" && (
secondToken.value === "function" || secondToken.value === "function" ||
secondToken.value === "class" || secondToken.value === "class" ||
secondToken.value === "let" && astUtils.isOpeningBracketToken(sourceCode.getTokenAfter(secondToken, astUtils.isNotClosingParenToken)) secondToken.value === "let" &&
tokenAfterClosingParens &&
(
astUtils.isOpeningBracketToken(tokenAfterClosingParens) ||
tokenAfterClosingParens.type === "Identifier"
)
) || ) ||
secondToken && secondToken.type === "Identifier" && secondToken.value === "async" && thirdToken && thirdToken.type === "Keyword" && thirdToken.value === "function" secondToken && secondToken.type === "Identifier" && secondToken.value === "async" && thirdToken && thirdToken.type === "Keyword" && thirdToken.value === "function"
) )

View File

@ -14,7 +14,7 @@ const lodash = require("lodash");
// Helpers // Helpers
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const DEFAULT_FALLTHROUGH_COMMENT = /falls?\s?through/i; const DEFAULT_FALLTHROUGH_COMMENT = /falls?\s?through/iu;
/** /**
* Checks whether or not a given node has a fallthrough comment. * Checks whether or not a given node has a fallthrough comment.
@ -95,7 +95,7 @@ module.exports = {
let fallthroughCommentPattern = null; let fallthroughCommentPattern = null;
if (options.commentPattern) { if (options.commentPattern) {
fallthroughCommentPattern = new RegExp(options.commentPattern); fallthroughCommentPattern = new RegExp(options.commentPattern); // eslint-disable-line require-unicode-regexp
} else { } else {
fallthroughCommentPattern = DEFAULT_FALLTHROUGH_COMMENT; fallthroughCommentPattern = DEFAULT_FALLTHROUGH_COMMENT;
} }

View File

@ -11,7 +11,7 @@ const astUtils = require("../util/ast-utils");
// Helpers // Helpers
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const INDEX_OF_PATTERN = /^(?:i|lastI)ndexOf$/; const INDEX_OF_PATTERN = /^(?:i|lastI)ndexOf$/u;
const ALLOWABLE_OPERATORS = ["~", "!!", "+", "*"]; const ALLOWABLE_OPERATORS = ["~", "!!", "+", "*"];
/** /**

View File

@ -24,7 +24,7 @@ module.exports = {
}, },
create(context) { create(context) {
const CALLEE_RE = /^(setTimeout|setInterval|execScript)$/; const CALLEE_RE = /^(setTimeout|setInterval|execScript)$/u;
/* /*
* Figures out if we should inspect a given binary expression. Is a stack * Figures out if we should inspect a given binary expression. Is a stack

View File

@ -10,7 +10,7 @@
const RegExpValidator = require("regexpp").RegExpValidator; const RegExpValidator = require("regexpp").RegExpValidator;
const validator = new RegExpValidator({ ecmaVersion: 2018 }); const validator = new RegExpValidator({ ecmaVersion: 2018 });
const validFlags = /[gimuys]/g; const validFlags = /[gimuys]/gu;
const undefined1 = void 0; const undefined1 = void 0;
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
@ -51,7 +51,7 @@ module.exports = {
const temp = options.allowConstructorFlags.join("").replace(validFlags, ""); const temp = options.allowConstructorFlags.join("").replace(validFlags, "");
if (temp) { if (temp) {
allowedFlags = new RegExp(`[${temp}]`, "gi"); allowedFlags = new RegExp(`[${temp}]`, "giu");
} }
} }

View File

@ -16,9 +16,9 @@ const astUtils = require("../util/ast-utils");
// Constants // Constants
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const ALL_IRREGULARS = /[\f\v\u0085\ufeff\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000\u2028\u2029]/; const ALL_IRREGULARS = /[\f\v\u0085\ufeff\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000\u2028\u2029]/u;
const IRREGULAR_WHITESPACE = /[\f\v\u0085\ufeff\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000]+/mg; const IRREGULAR_WHITESPACE = /[\f\v\u0085\ufeff\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000]+/mgu;
const IRREGULAR_LINE_TERMINATORS = /[\u2028\u2029]/mg; const IRREGULAR_LINE_TERMINATORS = /[\u2028\u2029]/mgu;
const LINE_BREAK = astUtils.createGlobalLinebreakMatcher(); const LINE_BREAK = astUtils.createGlobalLinebreakMatcher();
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------

View File

@ -58,7 +58,7 @@ module.exports = {
node.consequent.type !== "BlockStatement" && lastIfToken.value !== ";" && tokenAfterElseBlock && node.consequent.type !== "BlockStatement" && lastIfToken.value !== ";" && tokenAfterElseBlock &&
( (
node.consequent.loc.end.line === tokenAfterElseBlock.loc.start.line || node.consequent.loc.end.line === tokenAfterElseBlock.loc.start.line ||
/^[([/+`-]/.test(tokenAfterElseBlock.value) || /^[([/+`-]/u.test(tokenAfterElseBlock.value) ||
lastIfToken.value === "++" || lastIfToken.value === "++" ||
lastIfToken.value === "--" lastIfToken.value === "--"
) )

View File

@ -34,7 +34,7 @@ const DEFAULT_GROUPS = [
LOGICAL_OPERATORS, LOGICAL_OPERATORS,
RELATIONAL_OPERATORS RELATIONAL_OPERATORS
]; ];
const TARGET_NODE_TYPE = /^(?:Binary|Logical)Expression$/; const TARGET_NODE_TYPE = /^(?:Binary|Logical)Expression$/u;
/** /**
* Normalizes options. * Normalizes options.

View File

@ -30,12 +30,10 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
grouping: { grouping: {
type: "boolean", type: "boolean"
default: false
}, },
allowCall: { allowCall: {
type: "boolean", type: "boolean"
default: false
} }
}, },
additionalProperties: false additionalProperties: false
@ -158,7 +156,7 @@ module.exports = {
// "var fs = require('fs');" // "var fs = require('fs');"
return REQ_CORE; return REQ_CORE;
} }
if (/^\.{0,2}\//.test(arg.value)) { if (/^\.{0,2}\//u.test(arg.value)) {
// "var utils = require('./utils');" // "var utils = require('./utils');"
return REQ_FILE; return REQ_FILE;

View File

@ -88,7 +88,7 @@ module.exports = {
* or the reverse before non-tab/-space * or the reverse before non-tab/-space
* characters begin. * characters begin.
*/ */
let regex = /^(?=[\t ]*(\t | \t))/; let regex = /^(?=[\t ]*(\t | \t))/u;
const lines = sourceCode.lines, const lines = sourceCode.lines,
comments = sourceCode.getAllComments(); comments = sourceCode.getAllComments();
@ -114,7 +114,7 @@ module.exports = {
* At least one space followed by a tab * At least one space followed by a tab
* before non-tab/-space characters begin. * before non-tab/-space characters begin.
*/ */
regex = /^(?=[\t ]* \t)/; regex = /^(?=[\t ]* \t)/u;
} }
lines.forEach((line, i) => { lines.forEach((line, i) => {

View File

@ -32,7 +32,7 @@ module.exports = {
return; return;
} }
const match = node.raw.match(/^([^\\]|\\[^0-7])*\\([0-3][0-7]{1,2}|[4-7][0-7]|[0-7])/); const match = node.raw.match(/^([^\\]|\\[^0-7])*\\([0-3][0-7]{1,2}|[4-7][0-7]|[0-7])/u);
if (match) { if (match) {
const octalDigit = match[2]; const octalDigit = match[2];

View File

@ -28,7 +28,7 @@ module.exports = {
return { return {
Literal(node) { Literal(node) {
if (typeof node.value === "number" && /^0[0-7]/.test(node.raw)) { if (typeof node.value === "number" && /^0[0-7]/u.test(node.raw)) {
context.report({ node, message: "Octal literals should not be used." }); context.report({ node, message: "Octal literals should not be used." });
} }
} }

View File

@ -8,7 +8,7 @@
// Rule Definition // Rule Definition
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const stopNodePattern = /(?:Statement|Declaration|Function(?:Expression)?|Program)$/; const stopNodePattern = /(?:Statement|Declaration|Function(?:Expression)?|Program)$/u;
module.exports = { module.exports = {
meta: { meta: {

View File

@ -24,7 +24,7 @@ module.exports = {
create(context) { create(context) {
const MATCHER = /^__(?:dir|file)name$/; const MATCHER = /^__(?:dir|file)name$/u;
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
// Public // Public

View File

@ -39,7 +39,7 @@ module.exports = {
* @private * @private
*/ */
function checkRegex(node, value, valueStart) { function checkRegex(node, value, valueStart) {
const multipleSpacesRegex = /( {2,})( [+*{?]|[^+*{?]|$)/, const multipleSpacesRegex = /( {2,})( [+*{?]|[^+*{?]|$)/u,
regexResults = multipleSpacesRegex.exec(value); regexResults = multipleSpacesRegex.exec(value);
if (regexResults !== null) { if (regexResults !== null) {

View File

@ -14,7 +14,7 @@ const astUtils = require("../util/ast-utils");
// Helpers // Helpers
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const SENTINEL_TYPE = /^(?:[a-zA-Z]+?Statement|ArrowFunctionExpression|FunctionExpression|ClassExpression)$/; const SENTINEL_TYPE = /^(?:[a-zA-Z]+?Statement|ArrowFunctionExpression|FunctionExpression|ClassExpression)$/u;
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Rule Definition // Rule Definition

View File

@ -15,7 +15,7 @@ const astUtils = require("../util/ast-utils");
// Helpers // Helpers
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const SPACES = /\s+/g; const SPACES = /\s+/gu;
/** /**
* Checks whether the property of 2 given member expression nodes are the same * Checks whether the property of 2 given member expression nodes are the same

View File

@ -9,8 +9,8 @@
// Helpers // Helpers
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const tabRegex = /\t+/g; const tabRegex = /\t+/gu;
const anyNonWhitespaceRegex = /\S/; const anyNonWhitespaceRegex = /\S/u;
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Public Interface // Public Interface

View File

@ -23,7 +23,7 @@ module.exports = {
}, },
create(context) { create(context) {
const regex = /\$\{[^}]+\}/; const regex = /\$\{[^}]+\}/u;
return { return {
Literal(node) { Literal(node) {

View File

@ -111,8 +111,8 @@ module.exports = {
* fetch the source code and do matching via regexps. * fetch the source code and do matching via regexps.
*/ */
const re = new RegExp(NONBLANK), const re = new RegExp(NONBLANK, "u"),
skipMatch = new RegExp(SKIP_BLANK), skipMatch = new RegExp(SKIP_BLANK, "u"),
lines = sourceCode.lines, lines = sourceCode.lines,
linebreaks = sourceCode.getText().match(astUtils.createGlobalLinebreakMatcher()), linebreaks = sourceCode.getText().match(astUtils.createGlobalLinebreakMatcher()),
comments = sourceCode.getAllComments(), comments = sourceCode.getAllComments(),

View File

@ -36,7 +36,7 @@ module.exports = {
create(context) { create(context) {
const REGEX_FLAG_MATCHER = /^[gimsuy]+$/; const REGEX_FLAG_MATCHER = /^[gimsuy]+$/u;
const sourceCode = context.getSourceCode(); const sourceCode = context.getSourceCode();

View File

@ -16,11 +16,11 @@ const Traverser = require("../util/traverser"),
// Helpers // Helpers
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const SENTINEL_PATTERN = /(?:(?:Call|Class|Function|Member|New|Yield)Expression|Statement|Declaration)$/; const SENTINEL_PATTERN = /(?:(?:Call|Class|Function|Member|New|Yield)Expression|Statement|Declaration)$/u;
const LOOP_PATTERN = /^(?:DoWhile|For|While)Statement$/; // for-in/of statements don't have `test` property. const LOOP_PATTERN = /^(?:DoWhile|For|While)Statement$/u; // for-in/of statements don't have `test` property.
const GROUP_PATTERN = /^(?:BinaryExpression|ConditionalExpression)$/; const GROUP_PATTERN = /^(?:BinaryExpression|ConditionalExpression)$/u;
const SKIP_PATTERN = /^(?:ArrowFunction|Class|Function)Expression$/; const SKIP_PATTERN = /^(?:ArrowFunction|Class|Function)Expression$/u;
const DYNAMIC_PATTERN = /^(?:Call|Member|New|TaggedTemplate|Yield)Expression$/; const DYNAMIC_PATTERN = /^(?:Call|Member|New|TaggedTemplate|Yield)Expression$/u;
/** /**
* @typedef {Object} LoopConditionInfo * @typedef {Object} LoopConditionInfo

View File

@ -9,9 +9,9 @@
// Helpers // Helpers
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const SENTINEL_NODE_TYPE_RETURN_THROW = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression)$/; const SENTINEL_NODE_TYPE_RETURN_THROW = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression)$/u;
const SENTINEL_NODE_TYPE_BREAK = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement|SwitchStatement)$/; const SENTINEL_NODE_TYPE_BREAK = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement|SwitchStatement)$/u;
const SENTINEL_NODE_TYPE_CONTINUE = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement)$/; const SENTINEL_NODE_TYPE_CONTINUE = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement)$/u;
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------

View File

@ -88,7 +88,7 @@ module.exports = {
grandparent = ancestors[ancestors.length - 2]; grandparent = ancestors[ancestors.length - 2];
return (parent.type === "Program" || parent.type === "BlockStatement" && return (parent.type === "Program" || parent.type === "BlockStatement" &&
(/Function/.test(grandparent.type))) && (/Function/u.test(grandparent.type))) &&
directives(parent).indexOf(node) >= 0; directives(parent).indexOf(node) >= 0;
} }
@ -116,7 +116,7 @@ module.exports = {
return true; return true;
} }
return /^(?:Assignment|Call|New|Update|Yield|Await)Expression$/.test(node.type) || return /^(?:Assignment|Call|New|Update|Yield|Await)Expression$/u.test(node.type) ||
(node.type === "UnaryExpression" && ["delete", "void"].indexOf(node.operator) >= 0); (node.type === "UnaryExpression" && ["delete", "void"].indexOf(node.operator) >= 0);
} }

View File

@ -37,26 +37,22 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
vars: { vars: {
enum: ["all", "local"], enum: ["all", "local"]
default: "all"
}, },
varsIgnorePattern: { varsIgnorePattern: {
type: "string" type: "string"
}, },
args: { args: {
enum: ["all", "after-used", "none"], enum: ["all", "after-used", "none"]
default: "after-used"
}, },
ignoreRestSiblings: { ignoreRestSiblings: {
type: "boolean", type: "boolean"
default: false
}, },
argsIgnorePattern: { argsIgnorePattern: {
type: "string" type: "string"
}, },
caughtErrors: { caughtErrors: {
enum: ["all", "none"], enum: ["all", "none"]
default: "none"
}, },
caughtErrorsIgnorePattern: { caughtErrorsIgnorePattern: {
type: "string" type: "string"
@ -71,7 +67,7 @@ module.exports = {
create(context) { create(context) {
const sourceCode = context.getSourceCode(); const sourceCode = context.getSourceCode();
const REST_PROPERTY_TYPE = /^(?:RestElement|(?:Experimental)?RestProperty)$/; const REST_PROPERTY_TYPE = /^(?:RestElement|(?:Experimental)?RestProperty)$/u;
const config = { const config = {
vars: "all", vars: "all",
@ -92,15 +88,15 @@ module.exports = {
config.caughtErrors = firstOption.caughtErrors || config.caughtErrors; config.caughtErrors = firstOption.caughtErrors || config.caughtErrors;
if (firstOption.varsIgnorePattern) { if (firstOption.varsIgnorePattern) {
config.varsIgnorePattern = new RegExp(firstOption.varsIgnorePattern); config.varsIgnorePattern = new RegExp(firstOption.varsIgnorePattern); // eslint-disable-line require-unicode-regexp
} }
if (firstOption.argsIgnorePattern) { if (firstOption.argsIgnorePattern) {
config.argsIgnorePattern = new RegExp(firstOption.argsIgnorePattern); config.argsIgnorePattern = new RegExp(firstOption.argsIgnorePattern); // eslint-disable-line require-unicode-regexp
} }
if (firstOption.caughtErrorsIgnorePattern) { if (firstOption.caughtErrorsIgnorePattern) {
config.caughtErrorsIgnorePattern = new RegExp(firstOption.caughtErrorsIgnorePattern); config.caughtErrorsIgnorePattern = new RegExp(firstOption.caughtErrorsIgnorePattern); // eslint-disable-line require-unicode-regexp
} }
} }
} }
@ -147,7 +143,7 @@ module.exports = {
// Helpers // Helpers
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
const STATEMENT_TYPE = /(?:Statement|Declaration)$/; const STATEMENT_TYPE = /(?:Statement|Declaration)$/u;
/** /**
* Determines if a given variable is being exported from a module. * Determines if a given variable is being exported from a module.
@ -600,7 +596,7 @@ module.exports = {
* @private * @private
*/ */
function getColumnInComment(variable, comment) { function getColumnInComment(variable, comment) {
const namePattern = new RegExp(`[\\s,]${lodash.escapeRegExp(variable.name)}(?:$|[\\s,:])`, "g"); const namePattern = new RegExp(`[\\s,]${lodash.escapeRegExp(variable.name)}(?:$|[\\s,:])`, "gu");
// To ignore the first text "global". // To ignore the first text "global".
namePattern.lastIndex = comment.value.indexOf("global") + 6; namePattern.lastIndex = comment.value.indexOf("global") + 6;

View File

@ -9,8 +9,8 @@
// Helpers // Helpers
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const SENTINEL_TYPE = /^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration)$/; const SENTINEL_TYPE = /^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration)$/u;
const FOR_IN_OF_TYPE = /^For(?:In|Of)Statement$/; const FOR_IN_OF_TYPE = /^For(?:In|Of)Statement$/u;
/** /**
* Parses a given value as options. * Parses a given value as options.
@ -154,9 +154,9 @@ module.exports = {
{ {
type: "object", type: "object",
properties: { properties: {
functions: { type: "boolean", default: true }, functions: { type: "boolean" },
classes: { type: "boolean", default: true }, classes: { type: "boolean" },
variables: { type: "boolean", default: true } variables: { type: "boolean" }
}, },
additionalProperties: false additionalProperties: false
} }

View File

@ -181,7 +181,7 @@ module.exports = {
} }
const value = isTemplateElement ? node.value.raw : node.raw.slice(1, -1); const value = isTemplateElement ? node.value.raw : node.raw.slice(1, -1);
const pattern = /\\[^\d]/g; const pattern = /\\[^\d]/gu;
let match; let match;
while ((match = pattern.exec(value))) { while ((match = pattern.exec(value))) {

View File

@ -77,7 +77,7 @@ function isDeclarationInitialized(node) {
return node.declarations.every(declarator => declarator.init !== null); return node.declarations.every(declarator => declarator.init !== null);
} }
const SCOPE_NODE_TYPE = /^(?:Program|BlockStatement|SwitchStatement|ForStatement|ForInStatement|ForOfStatement)$/; const SCOPE_NODE_TYPE = /^(?:Program|BlockStatement|SwitchStatement|ForStatement|ForInStatement|ForOfStatement)$/u;
/** /**
* Gets the scope node which directly contains a given node. * Gets the scope node which directly contains a given node.

View File

@ -47,7 +47,7 @@ module.exports = {
configuration = context.options[0] || {}, configuration = context.options[0] || {},
warningTerms = configuration.terms || ["todo", "fixme", "xxx"], warningTerms = configuration.terms || ["todo", "fixme", "xxx"],
location = configuration.location || "start", location = configuration.location || "start",
selfConfigRegEx = /\bno-warning-comments\b/; selfConfigRegEx = /\bno-warning-comments\b/u;
/** /**
* Convert a warning term into a RegExp which will match a comment containing that whole word in the specified * Convert a warning term into a RegExp which will match a comment containing that whole word in the specified
@ -58,7 +58,7 @@ module.exports = {
* @returns {RegExp} The term converted to a RegExp * @returns {RegExp} The term converted to a RegExp
*/ */
function convertToRegExp(term) { function convertToRegExp(term) {
const escaped = term.replace(/[-/\\$^*+?.()|[\]{}]/g, "\\$&"); const escaped = term.replace(/[-/\\$^*+?.()|[\]{}]/gu, "\\$&");
const wordBoundary = "\\b"; const wordBoundary = "\\b";
const eitherOrWordBoundary = `|${wordBoundary}`; const eitherOrWordBoundary = `|${wordBoundary}`;
let prefix; let prefix;
@ -73,7 +73,7 @@ module.exports = {
* In these cases, use no bounding match. Same applies for the * In these cases, use no bounding match. Same applies for the
* prefix, handled below. * prefix, handled below.
*/ */
const suffix = /\w$/.test(term) ? "\\b" : ""; const suffix = /\w$/u.test(term) ? "\\b" : "";
if (location === "start") { if (location === "start") {
@ -82,7 +82,7 @@ module.exports = {
* there's no need to worry about word boundaries. * there's no need to worry about word boundaries.
*/ */
prefix = "^\\s*"; prefix = "^\\s*";
} else if (/^\w/.test(term)) { } else if (/^\w/u.test(term)) {
prefix = wordBoundary; prefix = wordBoundary;
} else { } else {
prefix = ""; prefix = "";
@ -95,7 +95,7 @@ module.exports = {
* ^\s*TERM\b. This checks the word boundary * ^\s*TERM\b. This checks the word boundary
* at the beginning of the comment. * at the beginning of the comment.
*/ */
return new RegExp(prefix + escaped + suffix, "i"); return new RegExp(prefix + escaped + suffix, "iu");
} }
/* /*
@ -103,7 +103,7 @@ module.exports = {
* \bTERM\b|\bTERM\b, this checks the entire comment * \bTERM\b|\bTERM\b, this checks the entire comment
* for the term. * for the term.
*/ */
return new RegExp(prefix + escaped + suffix + eitherOrWordBoundary + term + wordBoundary, "i"); return new RegExp(prefix + escaped + suffix + eitherOrWordBoundary + term + wordBoundary, "iu");
} }
const warningRegExps = warningTerms.map(convertToRegExp); const warningRegExps = warningTerms.map(convertToRegExp);

View File

@ -26,16 +26,14 @@ const OPTION_VALUE = {
type: "object", type: "object",
properties: { properties: {
multiline: { multiline: {
type: "boolean", type: "boolean"
default: false
}, },
minProperties: { minProperties: {
type: "integer", type: "integer",
minimum: 0 minimum: 0
}, },
consistent: { consistent: {
type: "boolean", type: "boolean"
default: false
} }
}, },
additionalProperties: false, additionalProperties: false,
@ -61,9 +59,9 @@ function normalizeOptionValue(value) {
} else if (value === "never") { } else if (value === "never") {
minProperties = Number.POSITIVE_INFINITY; minProperties = Number.POSITIVE_INFINITY;
} else { } else {
multiline = value.multiline; multiline = Boolean(value.multiline);
minProperties = value.minProperties || Number.POSITIVE_INFINITY; minProperties = value.minProperties || Number.POSITIVE_INFINITY;
consistent = value.consistent; consistent = Boolean(value.consistent);
} }
} else { } else {
consistent = true; consistent = true;

View File

@ -57,8 +57,7 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
avoidQuotes: { avoidQuotes: {
type: "boolean", type: "boolean"
default: false
} }
}, },
additionalProperties: false additionalProperties: false
@ -77,16 +76,13 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
ignoreConstructors: { ignoreConstructors: {
type: "boolean", type: "boolean"
default: false
}, },
avoidQuotes: { avoidQuotes: {
type: "boolean", type: "boolean"
default: false
}, },
avoidExplicitReturnArrows: { avoidExplicitReturnArrows: {
type: "boolean", type: "boolean"
default: false
} }
}, },
additionalProperties: false additionalProperties: false

View File

@ -36,16 +36,13 @@ module.exports = {
default: false default: false
}, },
var: { var: {
enum: ["always", "never", "consecutive"], enum: ["always", "never", "consecutive"]
default: "always"
}, },
let: { let: {
enum: ["always", "never", "consecutive"], enum: ["always", "never", "consecutive"]
default: "always"
}, },
const: { const: {
enum: ["always", "never", "consecutive"], enum: ["always", "never", "consecutive"]
default: "always"
} }
}, },
additionalProperties: false additionalProperties: false

View File

@ -17,10 +17,11 @@ const astUtils = require("../util/ast-utils");
const LT = `[${Array.from(astUtils.LINEBREAKS).join("")}]`; const LT = `[${Array.from(astUtils.LINEBREAKS).join("")}]`;
const PADDING_LINE_SEQUENCE = new RegExp( const PADDING_LINE_SEQUENCE = new RegExp(
String.raw`^(\s*?${LT})\s*${LT}(\s*;?)$` String.raw`^(\s*?${LT})\s*${LT}(\s*;?)$`,
"u"
); );
const CJS_EXPORT = /^(?:module\s*\.\s*)?exports(?:\s*\.|\s*\[|$)/; const CJS_EXPORT = /^(?:module\s*\.\s*)?exports(?:\s*\.|\s*\[|$)/u;
const CJS_IMPORT = /^require\(/; const CJS_IMPORT = /^require\(/u;
/** /**
* Creates tester which check if a node starts with specific keyword. * Creates tester which check if a node starts with specific keyword.

View File

@ -11,9 +11,9 @@ const astUtils = require("../util/ast-utils");
// Helpers // Helpers
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const PATTERN_TYPE = /^(?:.+?Pattern|RestElement|SpreadProperty|ExperimentalRestProperty|Property)$/; const PATTERN_TYPE = /^(?:.+?Pattern|RestElement|SpreadProperty|ExperimentalRestProperty|Property)$/u;
const DECLARATION_HOST_TYPE = /^(?:Program|BlockStatement|SwitchCase)$/; const DECLARATION_HOST_TYPE = /^(?:Program|BlockStatement|SwitchCase)$/u;
const DESTRUCTURING_HOST_TYPE = /^(?:VariableDeclarator|AssignmentExpression)$/; const DESTRUCTURING_HOST_TYPE = /^(?:VariableDeclarator|AssignmentExpression)$/u;
/** /**
* Checks whether a given node is located at `ForStatement.init` or not. * Checks whether a given node is located at `ForStatement.init` or not.

View File

@ -36,12 +36,10 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
array: { array: {
type: "boolean", type: "boolean"
default: true
}, },
object: { object: {
type: "boolean", type: "boolean"
default: true
} }
}, },
additionalProperties: false additionalProperties: false
@ -50,12 +48,10 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
array: { array: {
type: "boolean", type: "boolean"
default: true
}, },
object: { object: {
type: "boolean", type: "boolean"
default: true
} }
}, },
additionalProperties: false additionalProperties: false
@ -67,12 +63,10 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
array: { array: {
type: "boolean", type: "boolean"
default: true
}, },
object: { object: {
type: "boolean", type: "boolean"
default: true
} }
}, },
additionalProperties: false additionalProperties: false
@ -83,8 +77,7 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
enforceForRenamedProperties: { enforceForRenamedProperties: {
type: "boolean", type: "boolean"
default: false
} }
}, },
additionalProperties: false additionalProperties: false

View File

@ -0,0 +1,123 @@
/**
* @fileoverview Rule to enforce requiring named capture groups in regular expression.
* @author Pig Fang <https://github.com/g-plane>
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const {
CALL,
CONSTRUCT,
ReferenceTracker,
getStringIfConstant
} = require("eslint-utils");
const regexpp = require("regexpp");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const parser = new regexpp.RegExpParser();
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "enforce using named capture group in regular expression",
category: "Best Practices",
recommended: false,
url: "https://eslint.org/docs/rules/prefer-named-capture-group"
},
schema: [],
messages: {
required: "Capture group '{{group}}' should be converted to a named or non-capturing group."
}
},
create(context) {
/**
* Function to check regular expression.
*
* @param {string} regex The regular expression to be check.
* @param {ASTNode} node AST node which contains regular expression.
* @param {boolean} uFlag Flag indicates whether unicode mode is enabled or not.
* @returns {void}
*/
function checkRegex(regex, node, uFlag) {
let ast;
try {
ast = parser.parsePattern(regex, 0, regex.length, uFlag);
} catch (_) {
// ignore regex syntax errors
return;
}
regexpp.visitRegExpAST(ast, {
onCapturingGroupEnter(group) {
if (!group.name) {
const locNode = node.type === "Literal" ? node : node.arguments[0];
context.report({
node,
messageId: "required",
loc: {
start: {
line: locNode.loc.start.line,
column: locNode.loc.start.column + group.start + 1
},
end: {
line: locNode.loc.start.line,
column: locNode.loc.start.column + group.end + 1
}
},
data: {
group: group.raw
}
});
}
}
});
}
return {
Literal(node) {
if (node.regex) {
checkRegex(node.regex.pattern, node, node.regex.flags.includes("u"));
}
},
Program() {
const scope = context.getScope();
const tracker = new ReferenceTracker(scope);
const traceMap = {
RegExp: {
[CALL]: true,
[CONSTRUCT]: true
}
};
for (const { node } of tracker.iterateGlobalReferences(traceMap)) {
const regex = getStringIfConstant(node.arguments[0]);
const flags = getStringIfConstant(node.arguments[1]);
if (regex) {
checkRegex(regex, node, flags && flags.includes("u"));
}
}
}
};
}
};

View File

@ -14,7 +14,7 @@ const {
isParenthesised isParenthesised
} = require("../util/ast-utils"); } = require("../util/ast-utils");
const ANY_SPACE = /\s/; const ANY_SPACE = /\s/u;
/** /**
* Helper that checks if the Object.assign call has array spread * Helper that checks if the Object.assign call has array spread

View File

@ -52,7 +52,7 @@ function isOctalEscapeSequence(node) {
return false; return false;
} }
const match = node.raw.match(/^([^\\]|\\[^0-7])*\\([0-7]{1,3})/); const match = node.raw.match(/^([^\\]|\\[^0-7])*\\([0-7]{1,3})/u);
if (match) { if (match) {
@ -187,14 +187,14 @@ module.exports = {
* for some reason, don't add another backslash, because that would change the meaning of the code (it would cause * for some reason, don't add another backslash, because that would change the meaning of the code (it would cause
* an actual backslash character to appear before the dollar sign). * an actual backslash character to appear before the dollar sign).
*/ */
return `\`${currentNode.raw.slice(1, -1).replace(/\\*(\${|`)/g, matched => { return `\`${currentNode.raw.slice(1, -1).replace(/\\*(\$\{|`)/gu, matched => {
if (matched.lastIndexOf("\\") % 2) { if (matched.lastIndexOf("\\") % 2) {
return `\\${matched}`; return `\\${matched}`;
} }
return matched; return matched;
// Unescape any quotes that appear in the original Literal that no longer need to be escaped. // Unescape any quotes that appear in the original Literal that no longer need to be escaped.
}).replace(new RegExp(`\\\\${currentNode.raw[0]}`, "g"), currentNode.raw[0])}\``; }).replace(new RegExp(`\\\\${currentNode.raw[0]}`, "gu"), currentNode.raw[0])}\``;
} }
if (currentNode.type === "TemplateLiteral") { if (currentNode.type === "TemplateLiteral") {

View File

@ -32,8 +32,7 @@ module.exports = {
type: "array", type: "array",
items: [ items: [
{ {
enum: ["always", "as-needed", "consistent", "consistent-as-needed"], enum: ["always", "as-needed", "consistent", "consistent-as-needed"]
default: "always"
} }
], ],
minItems: 0, minItems: 0,
@ -43,23 +42,19 @@ module.exports = {
type: "array", type: "array",
items: [ items: [
{ {
enum: ["always", "as-needed", "consistent", "consistent-as-needed"], enum: ["always", "as-needed", "consistent", "consistent-as-needed"]
default: "always"
}, },
{ {
type: "object", type: "object",
properties: { properties: {
keywords: { keywords: {
type: "boolean", type: "boolean"
default: false
}, },
unnecessary: { unnecessary: {
type: "boolean", type: "boolean"
default: true
}, },
numbers: { numbers: {
type: "boolean", type: "boolean"
default: false
} }
}, },
additionalProperties: false additionalProperties: false

View File

@ -34,7 +34,7 @@ const QUOTE_SETTINGS = {
}; };
// An unescaped newline is a newline preceded by an even number of backslashes. // An unescaped newline is a newline preceded by an even number of backslashes.
const UNESCAPED_LINEBREAK_PATTERN = new RegExp(String.raw`(^|[^\\])(\\\\)*[${Array.from(astUtils.LINEBREAKS).join("")}]`); const UNESCAPED_LINEBREAK_PATTERN = new RegExp(String.raw`(^|[^\\])(\\\\)*[${Array.from(astUtils.LINEBREAKS).join("")}]`, "u");
/** /**
* Switches quoting of javascript string between ' " and ` * Switches quoting of javascript string between ' " and `
@ -54,7 +54,7 @@ QUOTE_SETTINGS.backtick.convert = function(str) {
if (newQuote === oldQuote) { if (newQuote === oldQuote) {
return str; return str;
} }
return newQuote + str.slice(1, -1).replace(/\\(\${|\r\n?|\n|.)|["'`]|\${|(\r\n?|\n)/g, (match, escaped, newline) => { return newQuote + str.slice(1, -1).replace(/\\(\$\{|\r\n?|\n|.)|["'`]|\$\{|(\r\n?|\n)/gu, (match, escaped, newline) => {
if (escaped === oldQuote || oldQuote === "`" && escaped === "${") { if (escaped === oldQuote || oldQuote === "`" && escaped === "${") {
return escaped; // unescape return escaped; // unescape
} }
@ -100,12 +100,10 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
avoidEscape: { avoidEscape: {
type: "boolean", type: "boolean"
default: false
}, },
allowTemplateLiterals: { allowTemplateLiterals: {
type: "boolean", type: "boolean"
default: false
} }
}, },
additionalProperties: false additionalProperties: false

View File

@ -40,8 +40,7 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
beforeStatementContinuationChars: { beforeStatementContinuationChars: {
enum: ["always", "any", "never"], enum: ["always", "any", "never"]
default: "any"
} }
}, },
additionalProperties: false additionalProperties: false
@ -59,7 +58,7 @@ module.exports = {
{ {
type: "object", type: "object",
properties: { properties: {
omitLastInOneLineBlock: { type: "boolean", default: false } omitLastInOneLineBlock: { type: "boolean" }
}, },
additionalProperties: false additionalProperties: false
} }
@ -73,11 +72,11 @@ module.exports = {
create(context) { create(context) {
const OPT_OUT_PATTERN = /^[-[(/+`]/; // One of [(/+-` const OPT_OUT_PATTERN = /^[-[(/+`]/u; // One of [(/+-`
const options = context.options[1]; const options = context.options[1];
const never = context.options[0] === "never"; const never = context.options[0] === "never";
const exceptOneLine = options && options.omitLastInOneLineBlock; const exceptOneLine = Boolean(options && options.omitLastInOneLineBlock);
const beforeStatementContinuationChars = options && options.beforeStatementContinuationChars; const beforeStatementContinuationChars = options && options.beforeStatementContinuationChars || "any";
const sourceCode = context.getSourceCode(); const sourceCode = context.getSourceCode();
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
@ -292,7 +291,7 @@ module.exports = {
const parent = node.parent; const parent = node.parent;
if ((parent.type !== "ForStatement" || parent.init !== node) && if ((parent.type !== "ForStatement" || parent.init !== node) &&
(!/^For(?:In|Of)Statement/.test(parent.type) || parent.left !== node) (!/^For(?:In|Of)Statement/u.test(parent.type) || parent.left !== node)
) { ) {
checkForSemicolon(node); checkForSemicolon(node);
} }
@ -319,7 +318,7 @@ module.exports = {
} }
}, },
ExportDefaultDeclaration(node) { ExportDefaultDeclaration(node) {
if (!/(?:Class|Function)Declaration/.test(node.declaration.type)) { if (!/(?:Class|Function)Declaration/u.test(node.declaration.type)) {
checkForSemicolon(node); checkForSemicolon(node);
} }
} }

View File

@ -37,16 +37,13 @@ module.exports = {
type: "object", type: "object",
properties: { properties: {
anonymous: { anonymous: {
enum: ["always", "never", "ignore"], enum: ["always", "never", "ignore"]
default: "always"
}, },
named: { named: {
enum: ["always", "never", "ignore"], enum: ["always", "never", "ignore"]
default: "always"
}, },
asyncArrow: { asyncArrow: {
enum: ["always", "never", "ignore"], enum: ["always", "never", "ignore"]
default: "always"
} }
}, },
additionalProperties: false additionalProperties: false

View File

@ -126,7 +126,7 @@ function createAlwaysStylePattern(markers, exceptions) {
pattern += "?"; // or nothing. pattern += "?"; // or nothing.
pattern += createExceptionsPattern(exceptions); pattern += createExceptionsPattern(exceptions);
return new RegExp(pattern); return new RegExp(pattern); // eslint-disable-line require-unicode-regexp
} }
/** /**
@ -142,7 +142,7 @@ function createAlwaysStylePattern(markers, exceptions) {
function createNeverStylePattern(markers) { function createNeverStylePattern(markers) {
const pattern = `^(${markers.map(escape).join("|")})?[ \t]+`; const pattern = `^(${markers.map(escape).join("|")})?[ \t]+`;
return new RegExp(pattern); return new RegExp(pattern); // eslint-disable-line require-unicode-regexp
} }
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
@ -250,9 +250,9 @@ module.exports = {
// Create RegExp object for valid patterns. // Create RegExp object for valid patterns.
rule[type] = { rule[type] = {
beginRegex: requireSpace ? createAlwaysStylePattern(markers, exceptions) : createNeverStylePattern(markers), beginRegex: requireSpace ? createAlwaysStylePattern(markers, exceptions) : createNeverStylePattern(markers),
endRegex: balanced && requireSpace ? new RegExp(`${createExceptionsPattern(exceptions)}$`) : new RegExp(endNeverPattern), endRegex: balanced && requireSpace ? new RegExp(`${createExceptionsPattern(exceptions)}$`) : new RegExp(endNeverPattern), // eslint-disable-line require-unicode-regexp
hasExceptions: exceptions.length > 0, hasExceptions: exceptions.length > 0,
markers: new RegExp(`^(${markers.map(escape).join("|")})`) markers: new RegExp(`^(${markers.map(escape).join("|")})`) // eslint-disable-line require-unicode-regexp
}; };
return rule; return rule;

View File

@ -15,8 +15,8 @@ const astUtils = require("../util/ast-utils");
// Helpers // Helpers
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const OPEN_PAREN = /\$\{$/; const OPEN_PAREN = /\$\{$/u;
const CLOSE_PAREN = /^\}/; const CLOSE_PAREN = /^\}/u;
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Rule Definition // Rule Definition

View File

@ -30,7 +30,7 @@ module.exports = {
return { return {
BinaryExpression(node) { BinaryExpression(node) {
if (/^(?:[<>]|[!=]=)=?$/.test(node.operator) && (node.left.name === "NaN" || node.right.name === "NaN")) { if (/^(?:[<>]|[!=]=)=?$/u.test(node.operator) && (node.left.name === "NaN" || node.right.name === "NaN")) {
context.report({ node, messageId: "useIsNaN" }); context.report({ node, messageId: "useIsNaN" });
} }
} }

View File

@ -300,7 +300,7 @@ module.exports = {
}); });
} catch (ex) { } catch (ex) {
if (/braces/i.test(ex.message)) { if (/braces/iu.test(ex.message)) {
context.report({ node: jsdocNode, messageId: "missingBrace" }); context.report({ node: jsdocNode, messageId: "missingBrace" });
} else { } else {
context.report({ node: jsdocNode, messageId: "syntaxError" }); context.report({ node: jsdocNode, messageId: "syntaxError" });
@ -482,7 +482,7 @@ module.exports = {
} }
if (options.matchDescription) { if (options.matchDescription) {
const regex = new RegExp(options.matchDescription); const regex = new RegExp(options.matchDescription); // eslint-disable-line require-unicode-regexp
if (!regex.test(jsdoc.description)) { if (!regex.test(jsdoc.description)) {
context.report({ node: jsdocNode, messageId: "unsatisfiedDesc" }); context.report({ node: jsdocNode, messageId: "unsatisfiedDesc" });

View File

@ -117,7 +117,7 @@ module.exports = {
* @returns {void} * @returns {void}
*/ */
function blockScopeVarCheck(node, parent, grandParent) { function blockScopeVarCheck(node, parent, grandParent) {
if (!(/Function/.test(grandParent.type) && if (!(/Function/u.test(grandParent.type) &&
parent.type === "BlockStatement" && parent.type === "BlockStatement" &&
isVarOnTop(node, parent.body))) { isVarOnTop(node, parent.body))) {
context.report({ node, messageId: "top" }); context.report({ node, messageId: "top" });

View File

@ -31,8 +31,8 @@ module.exports = {
{ {
type: "object", type: "object",
properties: { properties: {
before: { type: "boolean", default: false }, before: { type: "boolean" },
after: { type: "boolean", default: true } after: { type: "boolean" }
}, },
additionalProperties: false additionalProperties: false
} }

View File

@ -20,7 +20,7 @@ const astUtils = require("../util/ast-utils");
* @returns {boolean} Whether or not it is a comparison operator. * @returns {boolean} Whether or not it is a comparison operator.
*/ */
function isComparisonOperator(operator) { function isComparisonOperator(operator) {
return (/^(==|===|!=|!==|<|>|<=|>=)$/).test(operator); return (/^(==|===|!=|!==|<|>|<=|>=)$/u).test(operator);
} }
/** /**
@ -29,7 +29,7 @@ function isComparisonOperator(operator) {
* @returns {boolean} Whether or not it is an equality operator. * @returns {boolean} Whether or not it is an equality operator.
*/ */
function isEqualityOperator(operator) { function isEqualityOperator(operator) {
return (/^(==|===)$/).test(operator); return (/^(==|===)$/u).test(operator);
} }
/** /**

View File

@ -16,19 +16,19 @@ const espree = require("espree");
// Helpers // Helpers
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const anyFunctionPattern = /^(?:Function(?:Declaration|Expression)|ArrowFunctionExpression)$/; const anyFunctionPattern = /^(?:Function(?:Declaration|Expression)|ArrowFunctionExpression)$/u;
const anyLoopPattern = /^(?:DoWhile|For|ForIn|ForOf|While)Statement$/; const anyLoopPattern = /^(?:DoWhile|For|ForIn|ForOf|While)Statement$/u;
const arrayOrTypedArrayPattern = /Array$/; const arrayOrTypedArrayPattern = /Array$/u;
const arrayMethodPattern = /^(?:every|filter|find|findIndex|forEach|map|some)$/; const arrayMethodPattern = /^(?:every|filter|find|findIndex|forEach|map|some)$/u;
const bindOrCallOrApplyPattern = /^(?:bind|call|apply)$/; const bindOrCallOrApplyPattern = /^(?:bind|call|apply)$/u;
const breakableTypePattern = /^(?:(?:Do)?While|For(?:In|Of)?|Switch)Statement$/; const breakableTypePattern = /^(?:(?:Do)?While|For(?:In|Of)?|Switch)Statement$/u;
const thisTagPattern = /^[\s*]*@this/m; const thisTagPattern = /^[\s*]*@this/mu;
const COMMENTS_IGNORE_PATTERN = /^\s*(?:eslint|jshint\s+|jslint\s+|istanbul\s+|globals?\s+|exported\s+|jscs)/; const COMMENTS_IGNORE_PATTERN = /^\s*(?:eslint|jshint\s+|jslint\s+|istanbul\s+|globals?\s+|exported\s+|jscs)/u;
const LINEBREAKS = new Set(["\r\n", "\r", "\n", "\u2028", "\u2029"]); const LINEBREAKS = new Set(["\r\n", "\r", "\n", "\u2028", "\u2029"]);
const LINEBREAK_MATCHER = /\r\n|[\r\n\u2028\u2029]/; const LINEBREAK_MATCHER = /\r\n|[\r\n\u2028\u2029]/u;
const SHEBANG_MATCHER = /^#!([^\r\n]+)/; const SHEBANG_MATCHER = /^#!([^\r\n]+)/u;
// A set of node types that can contain a list of statements // A set of node types that can contain a list of statements
const STATEMENT_LIST_PARENTS = new Set(["Program", "BlockStatement", "SwitchCase"]); const STATEMENT_LIST_PARENTS = new Set(["Program", "BlockStatement", "SwitchCase"]);
@ -398,7 +398,7 @@ function getOpeningParenOfParams(node, sourceCode) {
* @returns {RegExp} A global regular expression that matches line terminators * @returns {RegExp} A global regular expression that matches line terminators
*/ */
function createGlobalLinebreakMatcher() { function createGlobalLinebreakMatcher() {
return new RegExp(LINEBREAK_MATCHER.source, "g"); return new RegExp(LINEBREAK_MATCHER.source, "gu");
} }
/** /**
@ -1006,7 +1006,7 @@ module.exports = {
* '5' // false * '5' // false
*/ */
isDecimalInteger(node) { isDecimalInteger(node) {
return node.type === "Literal" && typeof node.value === "number" && /^(0|[1-9]\d*)$/.test(node.raw); return node.type === "Literal" && typeof node.value === "number" && /^(0|[1-9]\d*)$/u.test(node.raw);
}, },
/** /**

View File

@ -38,9 +38,9 @@ module.exports = class ConfigCommentParser {
const items = {}; const items = {};
// Collapse whitespace around `:` and `,` to make parsing easier // Collapse whitespace around `:` and `,` to make parsing easier
const trimmedString = string.replace(/\s*([:,])\s*/g, "$1"); const trimmedString = string.replace(/\s*([:,])\s*/gu, "$1");
trimmedString.split(/\s|,+/).forEach(name => { trimmedString.split(/\s|,+/u).forEach(name => {
if (!name) { if (!name) {
return; return;
} }
@ -90,7 +90,7 @@ module.exports = class ConfigCommentParser {
* But we are supporting that. So this is a fallback for that. * But we are supporting that. So this is a fallback for that.
*/ */
items = {}; items = {};
const normalizedString = string.replace(/([a-zA-Z0-9\-/]+):/g, "\"$1\":").replace(/(]|[0-9])\s+(?=")/, "$1,"); const normalizedString = string.replace(/([a-zA-Z0-9\-/]+):/gu, "\"$1\":").replace(/(\]|[0-9])\s+(?=")/u, "$1,");
try { try {
items = JSON.parse(`{${normalizedString}}`); items = JSON.parse(`{${normalizedString}}`);
@ -128,7 +128,7 @@ module.exports = class ConfigCommentParser {
const items = {}; const items = {};
// Collapse whitespace around commas // Collapse whitespace around commas
string.replace(/\s*,\s*/g, ",").split(/,+/).forEach(name => { string.replace(/\s*,\s*/gu, ",").split(/,+/u).forEach(name => {
const trimmedName = name.trim(); const trimmedName = name.trim();
if (trimmedName) { if (trimmedName) {

Some files were not shown because too many files have changed in this diff Show More