tools: update ESLint to 5.12.1

Update ESLint to 5.12.1

PR-URL: https://github.com/nodejs/node/pull/25573
Reviewed-By: Wyatt Preul <wpreul@gmail.com>
Reviewed-By: Masashi Hirano <shisama07@gmail.com>
This commit is contained in:
cjihrig 2019-01-18 16:09:54 -05:00
parent d1dee495db
commit af102c6d27
No known key found for this signature in database
GPG Key ID: 7434390BDBE9B9C5
117 changed files with 1226 additions and 513 deletions

35
tools/node_modules/eslint/README.md generated vendored
View File

@ -133,7 +133,7 @@ If you are trying to run locally:
* Make sure your plugins (and ESLint) are both in your project's `package.json` as devDependencies (or dependencies, if your project uses ESLint at runtime). * Make sure your plugins (and ESLint) are both in your project's `package.json` as devDependencies (or dependencies, if your project uses ESLint at runtime).
* Make sure you have run `npm install` and all your dependencies are installed. * Make sure you have run `npm install` and all your dependencies are installed.
In all cases, make sure your plugins' peerDependencies have been installed as well. You can use `npm view eslint-plugin-myplugin peerDepencies` to see what peer dependencies `eslint-plugin-myplugin` has. In all cases, make sure your plugins' peerDependencies have been installed as well. You can use `npm view eslint-plugin-myplugin peerDependencies` to see what peer dependencies `eslint-plugin-myplugin` has.
### Does ESLint support JSX? ### Does ESLint support JSX?
@ -195,6 +195,8 @@ These folks keep the project moving and are resources for help.
### Technical Steering Committee (TSC) ### Technical Steering Committee (TSC)
The people who manage releases, review feature requests, and meet regularly to ensure ESLint is properly maintained.
<table> <table>
<tbody> <tbody>
<tr> <tr>
@ -247,7 +249,31 @@ These folks keep the project moving and are resources for help.
</tbody> </tbody>
</table> </table>
### Development Team ### Committers
The people who review and fix bugs and help triage issues.
<table>
<tbody>
<tr>
<td align="center" valign="top" width="11%">
<a href="https://github.com/Aladdin-ADD">
<img src="https://github.com/Aladdin-ADD.png?s=75" width="75px" height="75px"><br/>
<sub>薛定谔的猫</sub></a>
</td>
<td align="center" valign="top" width="11%">
<a href="https://github.com/g-plane">
<img src="https://github.com/g-plane.png?s=75" width="75px" height="75px"><br/>
<sub>Pig Fang</sub></a>
</td>
</tr>
</tbody>
</table>
### Alumni
Former TSC members and committers who previously helped maintain ESLint.
<table> <table>
<tbody> <tbody>
@ -324,11 +350,6 @@ These folks keep the project moving and are resources for help.
<img src="https://github.com/soda0289.png?s=75" width="75px" height="75px"><br/> <img src="https://github.com/soda0289.png?s=75" width="75px" height="75px"><br/>
<sub>Reyad Attiyat</sub></a> <sub>Reyad Attiyat</sub></a>
</td> </td>
<td align="center" valign="top" width="11%">
<a href="https://github.com/Aladdin-ADD">
<img src="https://github.com/Aladdin-ADD.png?s=75" width="75px" height="75px"><br/>
<sub>薛定谔的猫</sub></a>
</td>
<td align="center" valign="top" width="11%"> <td align="center" valign="top" width="11%">
<a href="https://github.com/VictorHom"> <a href="https://github.com/VictorHom">
<img src="https://github.com/VictorHom.png?s=75" width="75px" height="75px"><br/> <img src="https://github.com/VictorHom.png?s=75" width="75px" height="75px"><br/>

277
tools/node_modules/eslint/lib/built-in-rules-index.js generated vendored Normal file
View File

@ -0,0 +1,277 @@
/**
* @fileoverview Collects the built-in rules into a map structure so that they can be imported all at once and without
* using the file-system directly.
* @author Peter (Somogyvari) Metz
*/
"use strict";
/* eslint sort-keys: ["error", "asc"] */
module.exports = {
"accessor-pairs": require("./rules/accessor-pairs"),
"array-bracket-newline": require("./rules/array-bracket-newline"),
"array-bracket-spacing": require("./rules/array-bracket-spacing"),
"array-callback-return": require("./rules/array-callback-return"),
"array-element-newline": require("./rules/array-element-newline"),
"arrow-body-style": require("./rules/arrow-body-style"),
"arrow-parens": require("./rules/arrow-parens"),
"arrow-spacing": require("./rules/arrow-spacing"),
"block-scoped-var": require("./rules/block-scoped-var"),
"block-spacing": require("./rules/block-spacing"),
"brace-style": require("./rules/brace-style"),
"callback-return": require("./rules/callback-return"),
camelcase: require("./rules/camelcase"),
"capitalized-comments": require("./rules/capitalized-comments"),
"class-methods-use-this": require("./rules/class-methods-use-this"),
"comma-dangle": require("./rules/comma-dangle"),
"comma-spacing": require("./rules/comma-spacing"),
"comma-style": require("./rules/comma-style"),
complexity: require("./rules/complexity"),
"computed-property-spacing": require("./rules/computed-property-spacing"),
"consistent-return": require("./rules/consistent-return"),
"consistent-this": require("./rules/consistent-this"),
"constructor-super": require("./rules/constructor-super"),
curly: require("./rules/curly"),
"default-case": require("./rules/default-case"),
"dot-location": require("./rules/dot-location"),
"dot-notation": require("./rules/dot-notation"),
"eol-last": require("./rules/eol-last"),
eqeqeq: require("./rules/eqeqeq"),
"for-direction": require("./rules/for-direction"),
"func-call-spacing": require("./rules/func-call-spacing"),
"func-name-matching": require("./rules/func-name-matching"),
"func-names": require("./rules/func-names"),
"func-style": require("./rules/func-style"),
"function-paren-newline": require("./rules/function-paren-newline"),
"generator-star-spacing": require("./rules/generator-star-spacing"),
"getter-return": require("./rules/getter-return"),
"global-require": require("./rules/global-require"),
"guard-for-in": require("./rules/guard-for-in"),
"handle-callback-err": require("./rules/handle-callback-err"),
"id-blacklist": require("./rules/id-blacklist"),
"id-length": require("./rules/id-length"),
"id-match": require("./rules/id-match"),
"implicit-arrow-linebreak": require("./rules/implicit-arrow-linebreak"),
indent: require("./rules/indent"),
"indent-legacy": require("./rules/indent-legacy"),
"init-declarations": require("./rules/init-declarations"),
"jsx-quotes": require("./rules/jsx-quotes"),
"key-spacing": require("./rules/key-spacing"),
"keyword-spacing": require("./rules/keyword-spacing"),
"line-comment-position": require("./rules/line-comment-position"),
"linebreak-style": require("./rules/linebreak-style"),
"lines-around-comment": require("./rules/lines-around-comment"),
"lines-around-directive": require("./rules/lines-around-directive"),
"lines-between-class-members": require("./rules/lines-between-class-members"),
"max-classes-per-file": require("./rules/max-classes-per-file"),
"max-depth": require("./rules/max-depth"),
"max-len": require("./rules/max-len"),
"max-lines": require("./rules/max-lines"),
"max-lines-per-function": require("./rules/max-lines-per-function"),
"max-nested-callbacks": require("./rules/max-nested-callbacks"),
"max-params": require("./rules/max-params"),
"max-statements": require("./rules/max-statements"),
"max-statements-per-line": require("./rules/max-statements-per-line"),
"multiline-comment-style": require("./rules/multiline-comment-style"),
"multiline-ternary": require("./rules/multiline-ternary"),
"new-cap": require("./rules/new-cap"),
"new-parens": require("./rules/new-parens"),
"newline-after-var": require("./rules/newline-after-var"),
"newline-before-return": require("./rules/newline-before-return"),
"newline-per-chained-call": require("./rules/newline-per-chained-call"),
"no-alert": require("./rules/no-alert"),
"no-array-constructor": require("./rules/no-array-constructor"),
"no-async-promise-executor": require("./rules/no-async-promise-executor"),
"no-await-in-loop": require("./rules/no-await-in-loop"),
"no-bitwise": require("./rules/no-bitwise"),
"no-buffer-constructor": require("./rules/no-buffer-constructor"),
"no-caller": require("./rules/no-caller"),
"no-case-declarations": require("./rules/no-case-declarations"),
"no-catch-shadow": require("./rules/no-catch-shadow"),
"no-class-assign": require("./rules/no-class-assign"),
"no-compare-neg-zero": require("./rules/no-compare-neg-zero"),
"no-cond-assign": require("./rules/no-cond-assign"),
"no-confusing-arrow": require("./rules/no-confusing-arrow"),
"no-console": require("./rules/no-console"),
"no-const-assign": require("./rules/no-const-assign"),
"no-constant-condition": require("./rules/no-constant-condition"),
"no-continue": require("./rules/no-continue"),
"no-control-regex": require("./rules/no-control-regex"),
"no-debugger": require("./rules/no-debugger"),
"no-delete-var": require("./rules/no-delete-var"),
"no-div-regex": require("./rules/no-div-regex"),
"no-dupe-args": require("./rules/no-dupe-args"),
"no-dupe-class-members": require("./rules/no-dupe-class-members"),
"no-dupe-keys": require("./rules/no-dupe-keys"),
"no-duplicate-case": require("./rules/no-duplicate-case"),
"no-duplicate-imports": require("./rules/no-duplicate-imports"),
"no-else-return": require("./rules/no-else-return"),
"no-empty": require("./rules/no-empty"),
"no-empty-character-class": require("./rules/no-empty-character-class"),
"no-empty-function": require("./rules/no-empty-function"),
"no-empty-pattern": require("./rules/no-empty-pattern"),
"no-eq-null": require("./rules/no-eq-null"),
"no-eval": require("./rules/no-eval"),
"no-ex-assign": require("./rules/no-ex-assign"),
"no-extend-native": require("./rules/no-extend-native"),
"no-extra-bind": require("./rules/no-extra-bind"),
"no-extra-boolean-cast": require("./rules/no-extra-boolean-cast"),
"no-extra-label": require("./rules/no-extra-label"),
"no-extra-parens": require("./rules/no-extra-parens"),
"no-extra-semi": require("./rules/no-extra-semi"),
"no-fallthrough": require("./rules/no-fallthrough"),
"no-floating-decimal": require("./rules/no-floating-decimal"),
"no-func-assign": require("./rules/no-func-assign"),
"no-global-assign": require("./rules/no-global-assign"),
"no-implicit-coercion": require("./rules/no-implicit-coercion"),
"no-implicit-globals": require("./rules/no-implicit-globals"),
"no-implied-eval": require("./rules/no-implied-eval"),
"no-inline-comments": require("./rules/no-inline-comments"),
"no-inner-declarations": require("./rules/no-inner-declarations"),
"no-invalid-regexp": require("./rules/no-invalid-regexp"),
"no-invalid-this": require("./rules/no-invalid-this"),
"no-irregular-whitespace": require("./rules/no-irregular-whitespace"),
"no-iterator": require("./rules/no-iterator"),
"no-label-var": require("./rules/no-label-var"),
"no-labels": require("./rules/no-labels"),
"no-lone-blocks": require("./rules/no-lone-blocks"),
"no-lonely-if": require("./rules/no-lonely-if"),
"no-loop-func": require("./rules/no-loop-func"),
"no-magic-numbers": require("./rules/no-magic-numbers"),
"no-misleading-character-class": require("./rules/no-misleading-character-class"),
"no-mixed-operators": require("./rules/no-mixed-operators"),
"no-mixed-requires": require("./rules/no-mixed-requires"),
"no-mixed-spaces-and-tabs": require("./rules/no-mixed-spaces-and-tabs"),
"no-multi-assign": require("./rules/no-multi-assign"),
"no-multi-spaces": require("./rules/no-multi-spaces"),
"no-multi-str": require("./rules/no-multi-str"),
"no-multiple-empty-lines": require("./rules/no-multiple-empty-lines"),
"no-native-reassign": require("./rules/no-native-reassign"),
"no-negated-condition": require("./rules/no-negated-condition"),
"no-negated-in-lhs": require("./rules/no-negated-in-lhs"),
"no-nested-ternary": require("./rules/no-nested-ternary"),
"no-new": require("./rules/no-new"),
"no-new-func": require("./rules/no-new-func"),
"no-new-object": require("./rules/no-new-object"),
"no-new-require": require("./rules/no-new-require"),
"no-new-symbol": require("./rules/no-new-symbol"),
"no-new-wrappers": require("./rules/no-new-wrappers"),
"no-obj-calls": require("./rules/no-obj-calls"),
"no-octal": require("./rules/no-octal"),
"no-octal-escape": require("./rules/no-octal-escape"),
"no-param-reassign": require("./rules/no-param-reassign"),
"no-path-concat": require("./rules/no-path-concat"),
"no-plusplus": require("./rules/no-plusplus"),
"no-process-env": require("./rules/no-process-env"),
"no-process-exit": require("./rules/no-process-exit"),
"no-proto": require("./rules/no-proto"),
"no-prototype-builtins": require("./rules/no-prototype-builtins"),
"no-redeclare": require("./rules/no-redeclare"),
"no-regex-spaces": require("./rules/no-regex-spaces"),
"no-restricted-globals": require("./rules/no-restricted-globals"),
"no-restricted-imports": require("./rules/no-restricted-imports"),
"no-restricted-modules": require("./rules/no-restricted-modules"),
"no-restricted-properties": require("./rules/no-restricted-properties"),
"no-restricted-syntax": require("./rules/no-restricted-syntax"),
"no-return-assign": require("./rules/no-return-assign"),
"no-return-await": require("./rules/no-return-await"),
"no-script-url": require("./rules/no-script-url"),
"no-self-assign": require("./rules/no-self-assign"),
"no-self-compare": require("./rules/no-self-compare"),
"no-sequences": require("./rules/no-sequences"),
"no-shadow": require("./rules/no-shadow"),
"no-shadow-restricted-names": require("./rules/no-shadow-restricted-names"),
"no-spaced-func": require("./rules/no-spaced-func"),
"no-sparse-arrays": require("./rules/no-sparse-arrays"),
"no-sync": require("./rules/no-sync"),
"no-tabs": require("./rules/no-tabs"),
"no-template-curly-in-string": require("./rules/no-template-curly-in-string"),
"no-ternary": require("./rules/no-ternary"),
"no-this-before-super": require("./rules/no-this-before-super"),
"no-throw-literal": require("./rules/no-throw-literal"),
"no-trailing-spaces": require("./rules/no-trailing-spaces"),
"no-undef": require("./rules/no-undef"),
"no-undef-init": require("./rules/no-undef-init"),
"no-undefined": require("./rules/no-undefined"),
"no-underscore-dangle": require("./rules/no-underscore-dangle"),
"no-unexpected-multiline": require("./rules/no-unexpected-multiline"),
"no-unmodified-loop-condition": require("./rules/no-unmodified-loop-condition"),
"no-unneeded-ternary": require("./rules/no-unneeded-ternary"),
"no-unreachable": require("./rules/no-unreachable"),
"no-unsafe-finally": require("./rules/no-unsafe-finally"),
"no-unsafe-negation": require("./rules/no-unsafe-negation"),
"no-unused-expressions": require("./rules/no-unused-expressions"),
"no-unused-labels": require("./rules/no-unused-labels"),
"no-unused-vars": require("./rules/no-unused-vars"),
"no-use-before-define": require("./rules/no-use-before-define"),
"no-useless-call": require("./rules/no-useless-call"),
"no-useless-catch": require("./rules/no-useless-catch"),
"no-useless-computed-key": require("./rules/no-useless-computed-key"),
"no-useless-concat": require("./rules/no-useless-concat"),
"no-useless-constructor": require("./rules/no-useless-constructor"),
"no-useless-escape": require("./rules/no-useless-escape"),
"no-useless-rename": require("./rules/no-useless-rename"),
"no-useless-return": require("./rules/no-useless-return"),
"no-var": require("./rules/no-var"),
"no-void": require("./rules/no-void"),
"no-warning-comments": require("./rules/no-warning-comments"),
"no-whitespace-before-property": require("./rules/no-whitespace-before-property"),
"no-with": require("./rules/no-with"),
"nonblock-statement-body-position": require("./rules/nonblock-statement-body-position"),
"object-curly-newline": require("./rules/object-curly-newline"),
"object-curly-spacing": require("./rules/object-curly-spacing"),
"object-property-newline": require("./rules/object-property-newline"),
"object-shorthand": require("./rules/object-shorthand"),
"one-var": require("./rules/one-var"),
"one-var-declaration-per-line": require("./rules/one-var-declaration-per-line"),
"operator-assignment": require("./rules/operator-assignment"),
"operator-linebreak": require("./rules/operator-linebreak"),
"padded-blocks": require("./rules/padded-blocks"),
"padding-line-between-statements": require("./rules/padding-line-between-statements"),
"prefer-arrow-callback": require("./rules/prefer-arrow-callback"),
"prefer-const": require("./rules/prefer-const"),
"prefer-destructuring": require("./rules/prefer-destructuring"),
"prefer-numeric-literals": require("./rules/prefer-numeric-literals"),
"prefer-object-spread": require("./rules/prefer-object-spread"),
"prefer-promise-reject-errors": require("./rules/prefer-promise-reject-errors"),
"prefer-reflect": require("./rules/prefer-reflect"),
"prefer-rest-params": require("./rules/prefer-rest-params"),
"prefer-spread": require("./rules/prefer-spread"),
"prefer-template": require("./rules/prefer-template"),
"quote-props": require("./rules/quote-props"),
quotes: require("./rules/quotes"),
radix: require("./rules/radix"),
"require-atomic-updates": require("./rules/require-atomic-updates"),
"require-await": require("./rules/require-await"),
"require-jsdoc": require("./rules/require-jsdoc"),
"require-unicode-regexp": require("./rules/require-unicode-regexp"),
"require-yield": require("./rules/require-yield"),
"rest-spread-spacing": require("./rules/rest-spread-spacing"),
semi: require("./rules/semi"),
"semi-spacing": require("./rules/semi-spacing"),
"semi-style": require("./rules/semi-style"),
"sort-imports": require("./rules/sort-imports"),
"sort-keys": require("./rules/sort-keys"),
"sort-vars": require("./rules/sort-vars"),
"space-before-blocks": require("./rules/space-before-blocks"),
"space-before-function-paren": require("./rules/space-before-function-paren"),
"space-in-parens": require("./rules/space-in-parens"),
"space-infix-ops": require("./rules/space-infix-ops"),
"space-unary-ops": require("./rules/space-unary-ops"),
"spaced-comment": require("./rules/spaced-comment"),
strict: require("./rules/strict"),
"switch-colon-spacing": require("./rules/switch-colon-spacing"),
"symbol-description": require("./rules/symbol-description"),
"template-curly-spacing": require("./rules/template-curly-spacing"),
"template-tag-spacing": require("./rules/template-tag-spacing"),
"unicode-bom": require("./rules/unicode-bom"),
"use-isnan": require("./rules/use-isnan"),
"valid-jsdoc": require("./rules/valid-jsdoc"),
"valid-typeof": require("./rules/valid-typeof"),
"vars-on-top": require("./rules/vars-on-top"),
"wrap-iife": require("./rules/wrap-iife"),
"wrap-regex": require("./rules/wrap-regex"),
"yield-star-spacing": require("./rules/yield-star-spacing"),
yoda: require("./rules/yoda")
};

View File

@ -20,7 +20,6 @@ function getMessageType(message) {
return "error"; return "error";
} }
return "warning"; return "warning";
} }
/** /**
@ -50,12 +49,11 @@ module.exports = function(results) {
let diagnostics = {}; let diagnostics = {};
if (messages.length > 0) { if (messages.length > 0) {
testResult = "not ok";
messages.forEach(message => { messages.forEach(message => {
const severity = getMessageType(message);
const diagnostic = { const diagnostic = {
message: message.message, message: message.message,
severity: getMessageType(message), severity,
data: { data: {
line: message.line || 0, line: message.line || 0,
column: message.column || 0, column: message.column || 0,
@ -63,6 +61,11 @@ module.exports = function(results) {
} }
}; };
// This ensures a warning message is not flagged as error
if (severity === "error") {
testResult = "not ok";
}
/* /*
* If we have multiple messages place them under a messages key * If we have multiple messages place them under a messages key
* The first error will be logged as message key * The first error will be logged as message key

View File

@ -12,6 +12,7 @@
const lodash = require("lodash"); const lodash = require("lodash");
const loadRules = require("./load-rules"); const loadRules = require("./load-rules");
const ruleReplacements = require("../conf/replacements").rules; const ruleReplacements = require("../conf/replacements").rules;
const builtInRules = require("./built-in-rules-index");
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Helpers // Helpers
@ -59,8 +60,7 @@ function normalizeRule(rule) {
class Rules { class Rules {
constructor() { constructor() {
this._rules = Object.create(null); this._rules = Object.create(null);
this.defineAll(builtInRules);
this.load();
} }
/** /**
@ -82,6 +82,15 @@ class Rules {
load(rulesDir, cwd) { load(rulesDir, cwd) {
const newRules = loadRules(rulesDir, cwd); const newRules = loadRules(rulesDir, cwd);
this.defineAll(newRules);
}
/**
* Pulls a Map of new rules to the defined ones of this instance.
* @param {Object} newRules Expects to have an object here that maps the rule ID to the rule definition.
* @returns {void}
*/
defineAll(newRules) {
Object.keys(newRules).forEach(ruleId => { Object.keys(newRules).forEach(ruleId => {
this.define(ruleId, newRules[ruleId]); this.define(ruleId, newRules[ruleId]);
}); });

View File

@ -57,7 +57,10 @@ module.exports = {
url: "https://eslint.org/docs/rules/global-require" url: "https://eslint.org/docs/rules/global-require"
}, },
schema: [] schema: [],
messages: {
unexpected: "Unexpected require()."
}
}, },
create(context) { create(context) {
@ -69,7 +72,7 @@ module.exports = {
const isGoodRequire = context.getAncestors().every(parent => ACCEPTABLE_PARENTS.indexOf(parent.type) > -1); const isGoodRequire = context.getAncestors().every(parent => ACCEPTABLE_PARENTS.indexOf(parent.type) > -1);
if (!isGoodRequire) { if (!isGoodRequire) {
context.report({ node, message: "Unexpected require()." }); context.report({ node, messageId: "unexpected" });
} }
} }
} }

View File

@ -20,7 +20,10 @@ module.exports = {
url: "https://eslint.org/docs/rules/guard-for-in" url: "https://eslint.org/docs/rules/guard-for-in"
}, },
schema: [] schema: [],
messages: {
wrap: "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype."
}
}, },
create(context) { create(context) {
@ -65,7 +68,7 @@ module.exports = {
} }
} }
context.report({ node, message: "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype." }); context.report({ node, messageId: "wrap" });
} }
}; };

View File

@ -24,7 +24,10 @@ module.exports = {
{ {
type: "string" type: "string"
} }
] ],
messages: {
expected: "Expected error to be handled."
}
}, },
create(context) { create(context) {
@ -77,7 +80,7 @@ module.exports = {
if (firstParameter && matchesConfiguredErrorName(firstParameter.name)) { if (firstParameter && matchesConfiguredErrorName(firstParameter.name)) {
if (firstParameter.references.length === 0) { if (firstParameter.references.length === 0) {
context.report({ node, message: "Expected error to be handled." }); context.report({ node, messageId: "expected" });
} }
} }
} }

View File

@ -27,6 +27,9 @@ module.exports = {
type: "string" type: "string"
}, },
uniqueItems: true uniqueItems: true
},
messages: {
blacklisted: "Identifier '{{name}}' is blacklisted."
} }
}, },
@ -72,7 +75,7 @@ module.exports = {
function report(node) { function report(node) {
context.report({ context.report({
node, node,
message: "Identifier '{{name}}' is blacklisted.", messageId: "blacklisted",
data: { data: {
name: node.name name: node.name
} }

View File

@ -44,7 +44,11 @@ module.exports = {
}, },
additionalProperties: false additionalProperties: false
} }
] ],
messages: {
tooShort: "Identifier name '{{name}}' is too short (< {{min}}).",
tooLong: "Identifier name '{{name}}' is too long (> {{max}})."
}
}, },
create(context) { create(context) {
@ -107,9 +111,7 @@ module.exports = {
if (isValidExpression && (isValidExpression === true || isValidExpression(parent, node))) { if (isValidExpression && (isValidExpression === true || isValidExpression(parent, node))) {
context.report({ context.report({
node, node,
message: isShort messageId: isShort ? "tooShort" : "tooLong",
? "Identifier name '{{name}}' is too short (< {{min}})."
: "Identifier name '{{name}}' is too long (> {{max}}).",
data: { name, min: minLength, max: maxLength } data: { name, min: minLength, max: maxLength }
}); });
} }

View File

@ -38,7 +38,10 @@ module.exports = {
} }
} }
} }
] ],
messages: {
notMatch: "Identifier '{{name}}' does not match the pattern '{{pattern}}'."
}
}, },
create(context) { create(context) {
@ -116,7 +119,7 @@ module.exports = {
if (!reported.has(node)) { if (!reported.has(node)) {
context.report({ context.report({
node, node,
message: "Identifier '{{name}}' does not match the pattern '{{pattern}}'.", messageId: "notMatch",
data: { data: {
name: node.name, name: node.name,
pattern pattern

View File

@ -30,7 +30,11 @@ module.exports = {
{ {
enum: ["beside", "below"] enum: ["beside", "below"]
} }
] ],
messages: {
expected: "Expected a linebreak before this expression.",
unexpected: "Expected no linebreak before this expression."
}
}, },
create(context) { create(context) {
@ -210,13 +214,13 @@ module.exports = {
if (tokenBefore.loc.end.line === fixerTarget.loc.start.line && option === "below") { if (tokenBefore.loc.end.line === fixerTarget.loc.start.line && option === "below") {
context.report({ context.report({
node: fixerTarget, node: fixerTarget,
message: "Expected a linebreak before this expression.", messageId: "expected",
fix: fixer => fixer.insertTextBefore(fixerTarget, "\n") fix: fixer => fixer.insertTextBefore(fixerTarget, "\n")
}); });
} else if (tokenBefore.loc.end.line !== fixerTarget.loc.start.line && option === "beside") { } else if (tokenBefore.loc.end.line !== fixerTarget.loc.start.line && option === "beside") {
context.report({ context.report({
node: fixerTarget, node: fixerTarget,
message: "Expected no linebreak before this expression.", messageId: "unexpected",
fix: autoFixBesides(tokenBefore, fixerTarget, node) fix: autoFixBesides(tokenBefore, fixerTarget, node)
}); });
} }

View File

@ -169,7 +169,10 @@ module.exports = {
}, },
additionalProperties: false additionalProperties: false
} }
] ],
messages: {
expected: "Expected indentation of {{expected}} but found {{actual}}."
}
}, },
create(context) { create(context) {
@ -268,7 +271,7 @@ module.exports = {
* @param {int} actualTabs The actual number of indentation tabs that were found on this line * @param {int} actualTabs The actual number of indentation tabs that were found on this line
* @returns {string} An error message for this line * @returns {string} An error message for this line
*/ */
function createErrorMessage(expectedAmount, actualSpaces, actualTabs) { function createErrorMessageData(expectedAmount, actualSpaces, actualTabs) {
const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs" const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs"
const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space" const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space"
const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs" const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs"
@ -288,8 +291,10 @@ module.exports = {
} else { } else {
foundStatement = "0"; foundStatement = "0";
} }
return {
return `Expected indentation of ${expectedStatement} but found ${foundStatement}.`; expected: expectedStatement,
actual: foundStatement
};
} }
/** /**
@ -318,7 +323,8 @@ module.exports = {
context.report({ context.report({
node, node,
loc, loc,
message: createErrorMessage(needed, gottenSpaces, gottenTabs), messageId: "expected",
data: createErrorMessageData(needed, gottenSpaces, gottenTabs),
fix: fixer => fixer.replaceTextRange(textRange, desiredIndent) fix: fixer => fixer.replaceTextRange(textRange, desiredIndent)
}); });
} }

View File

@ -599,7 +599,10 @@ module.exports = {
}, },
additionalProperties: false additionalProperties: false
} }
] ],
messages: {
wrongIndentation: "Expected indentation of {{expected}} but found {{actual}}."
}
}, },
create(context) { create(context) {
@ -671,7 +674,7 @@ module.exports = {
* @param {int} actualTabs The actual number of indentation tabs that were found on this line * @param {int} actualTabs The actual number of indentation tabs that were found on this line
* @returns {string} An error message for this line * @returns {string} An error message for this line
*/ */
function createErrorMessage(expectedAmount, actualSpaces, actualTabs) { function createErrorMessageData(expectedAmount, actualSpaces, actualTabs) {
const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs" const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs"
const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space" const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space"
const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs" const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs"
@ -689,8 +692,10 @@ module.exports = {
} else { } else {
foundStatement = "0"; foundStatement = "0";
} }
return {
return `Expected indentation of ${expectedStatement} but found ${foundStatement}.`; expected: expectedStatement,
actual: foundStatement
};
} }
/** /**
@ -706,7 +711,8 @@ module.exports = {
context.report({ context.report({
node: token, node: token,
message: createErrorMessage(neededIndent.length, numSpaces, numTabs), messageId: "wrongIndentation",
data: createErrorMessageData(neededIndent.length, numSpaces, numTabs),
loc: { loc: {
start: { line: token.loc.start.line, column: 0 }, start: { line: token.loc.start.line, column: 0 },
end: { line: token.loc.start.line, column: token.loc.start.column } end: { line: token.loc.start.line, column: token.loc.start.column }

View File

@ -85,6 +85,10 @@ module.exports = {
maxItems: 2 maxItems: 2
} }
] ]
},
messages: {
initialized: "Variable '{{idName}}' should be initialized on declaration.",
notInitialized: "Variable '{{idName}}' should not be initialized on declaration."
} }
}, },
@ -111,23 +115,18 @@ module.exports = {
id = declaration.id, id = declaration.id,
initialized = isInitialized(declaration), initialized = isInitialized(declaration),
isIgnoredForLoop = params.ignoreForLoopInit && isForLoop(node.parent); isIgnoredForLoop = params.ignoreForLoopInit && isForLoop(node.parent);
let messageId = "";
if (id.type !== "Identifier") {
continue;
}
if (mode === MODE_ALWAYS && !initialized) { if (mode === MODE_ALWAYS && !initialized) {
context.report({ messageId = "initialized";
node: declaration,
message: "Variable '{{idName}}' should be initialized on declaration.",
data: {
idName: id.name
}
});
} else if (mode === MODE_NEVER && kind !== "const" && initialized && !isIgnoredForLoop) { } else if (mode === MODE_NEVER && kind !== "const" && initialized && !isIgnoredForLoop) {
messageId = "notInitialized";
}
if (id.type === "Identifier" && messageId) {
context.report({ context.report({
node: declaration, node: declaration,
message: "Variable '{{idName}}' should not be initialized on declaration.", messageId,
data: { data: {
idName: id.name idName: id.name
} }

View File

@ -53,7 +53,10 @@ module.exports = {
{ {
enum: ["prefer-single", "prefer-double"] enum: ["prefer-single", "prefer-double"]
} }
] ],
messages: {
unexpected: "Unexpected usage of {{description}}."
}
}, },
create(context) { create(context) {
@ -77,7 +80,7 @@ module.exports = {
if (attributeValue && astUtils.isStringLiteral(attributeValue) && !usesExpectedQuotes(attributeValue)) { if (attributeValue && astUtils.isStringLiteral(attributeValue) && !usesExpectedQuotes(attributeValue)) {
context.report({ context.report({
node: attributeValue, node: attributeValue,
message: "Unexpected usage of {{description}}.", messageId: "unexpected",
data: { data: {
description: setting.description description: setting.description
}, },

View File

@ -121,11 +121,6 @@ function initOptions(toOptions, fromOptions) {
// Rule Definition // Rule Definition
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const messages = {
key: "{{error}} space after {{computed}}key '{{key}}'.",
value: "{{error}} space before value for {{computed}}key '{{key}}'."
};
module.exports = { module.exports = {
meta: { meta: {
type: "layout", type: "layout",
@ -297,7 +292,13 @@ module.exports = {
additionalProperties: false additionalProperties: false
} }
] ]
}] }],
messages: {
extraKey: "Extra space after {{computed}}key '{{key}}'.",
extraValue: "Extra space before value for {{computed}}key '{{key}}'.",
missingKey: "Missing space after {{computed}}key '{{key}}'.",
missingValue: "Missing space before value for {{computed}}key '{{key}}'."
}
}, },
create(context) { create(context) {
@ -460,12 +461,19 @@ module.exports = {
} }
} }
let messageId = "";
if (isExtra) {
messageId = side === "key" ? "extraKey" : "extraValue";
} else {
messageId = side === "key" ? "missingKey" : "missingValue";
}
context.report({ context.report({
node: property[side], node: property[side],
loc: locStart, loc: locStart,
message: messages[side], messageId,
data: { data: {
error: isExtra ? "Extra" : "Missing",
computed: property.computed ? "computed " : "", computed: property.computed ? "computed " : "",
key: getKey(property) key: getKey(property)
}, },

View File

@ -100,7 +100,13 @@ module.exports = {
}, },
additionalProperties: false additionalProperties: false
} }
] ],
messages: {
expectedBefore: "Expected space(s) before \"{{value}}\".",
expectedAfter: "Expected space(s) after \"{{value}}\".",
unexpectedBefore: "Unexpected space(s) before \"{{value}}\".",
unexpectedAfter: "Unexpected space(s) after \"{{value}}\"."
}
}, },
create(context) { create(context) {
@ -124,7 +130,7 @@ module.exports = {
) { ) {
context.report({ context.report({
loc: token.loc.start, loc: token.loc.start,
message: "Expected space(s) before \"{{value}}\".", messageId: "expectedBefore",
data: token, data: token,
fix(fixer) { fix(fixer) {
return fixer.insertTextBefore(token, " "); return fixer.insertTextBefore(token, " ");
@ -151,7 +157,7 @@ module.exports = {
) { ) {
context.report({ context.report({
loc: token.loc.start, loc: token.loc.start,
message: "Unexpected space(s) before \"{{value}}\".", messageId: "unexpectedBefore",
data: token, data: token,
fix(fixer) { fix(fixer) {
return fixer.removeRange([prevToken.range[1], token.range[0]]); return fixer.removeRange([prevToken.range[1], token.range[0]]);
@ -178,7 +184,7 @@ module.exports = {
) { ) {
context.report({ context.report({
loc: token.loc.start, loc: token.loc.start,
message: "Expected space(s) after \"{{value}}\".", messageId: "expectedAfter",
data: token, data: token,
fix(fixer) { fix(fixer) {
return fixer.insertTextAfter(token, " "); return fixer.insertTextAfter(token, " ");
@ -205,7 +211,7 @@ module.exports = {
) { ) {
context.report({ context.report({
loc: token.loc.start, loc: token.loc.start,
message: "Unexpected space(s) after \"{{value}}\".", messageId: "unexpectedAfter",
data: token, data: token,
fix(fixer) { fix(fixer) {
return fixer.removeRange([token.range[1], nextToken.range[0]]); return fixer.removeRange([token.range[1], nextToken.range[0]]);

View File

@ -47,7 +47,11 @@ module.exports = {
} }
] ]
} }
] ],
messages: {
above: "Expected comment to be above code.",
beside: "Expected comment to be beside code."
}
}, },
create(context) { create(context) {
@ -100,14 +104,14 @@ module.exports = {
if (isOnSameLine) { if (isOnSameLine) {
context.report({ context.report({
node, node,
message: "Expected comment to be above code." messageId: "above"
}); });
} }
} else { } else {
if (!isOnSameLine) { if (!isOnSameLine) {
context.report({ context.report({
node, node,
message: "Expected comment to be beside code." messageId: "beside"
}); });
} }
} }

View File

@ -32,14 +32,14 @@ module.exports = {
{ {
enum: ["unix", "windows"] enum: ["unix", "windows"]
} }
] ],
messages: {
expectedLF: "Expected linebreaks to be 'LF' but found 'CRLF'.",
expectedCRLF: "Expected linebreaks to be 'CRLF' but found 'LF'."
}
}, },
create(context) { create(context) {
const EXPECTED_LF_MSG = "Expected linebreaks to be 'LF' but found 'CRLF'.",
EXPECTED_CRLF_MSG = "Expected linebreaks to be 'CRLF' but found 'LF'.";
const sourceCode = context.getSourceCode(); const sourceCode = context.getSourceCode();
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
@ -89,7 +89,7 @@ module.exports = {
line: i, line: i,
column: sourceCode.lines[i - 1].length column: sourceCode.lines[i - 1].length
}, },
message: expectedLF ? EXPECTED_LF_MSG : EXPECTED_CRLF_MSG, messageId: expectedLF ? "expectedLF" : "expectedCRLF",
fix: createFix(range, expectedLFChars) fix: createFix(range, expectedLFChars)
}); });
} }

View File

@ -112,7 +112,11 @@ module.exports = {
}, },
additionalProperties: false additionalProperties: false
} }
] ],
messages: {
after: "Expected line after comment.",
before: "Expected line before comment."
}
}, },
create(context) { create(context) {
@ -350,7 +354,7 @@ module.exports = {
context.report({ context.report({
node: token, node: token,
message: "Expected line before comment.", messageId: "before",
fix(fixer) { fix(fixer) {
return fixer.insertTextBeforeRange(range, "\n"); return fixer.insertTextBeforeRange(range, "\n");
} }
@ -362,7 +366,7 @@ module.exports = {
!(astUtils.isCommentToken(nextTokenOrComment) && astUtils.isTokenOnSameLine(token, nextTokenOrComment))) { !(astUtils.isCommentToken(nextTokenOrComment) && astUtils.isTokenOnSameLine(token, nextTokenOrComment))) {
context.report({ context.report({
node: token, node: token,
message: "Expected line after comment.", messageId: "after",
fix(fixer) { fix(fixer) {
return fixer.insertTextAfter(token, "\n"); return fixer.insertTextAfter(token, "\n");
} }

View File

@ -45,6 +45,10 @@ module.exports = {
}], }],
fixable: "whitespace", fixable: "whitespace",
messages: {
expected: "Expected newline {{location}} \"{{value}}\" directive.",
unexpected: "Unexpected newline {{location}} \"{{value}}\" directive."
},
deprecated: true, deprecated: true,
replacedBy: ["padding-line-between-statements"] replacedBy: ["padding-line-between-statements"]
}, },
@ -109,9 +113,8 @@ module.exports = {
function reportError(node, location, expected) { function reportError(node, location, expected) {
context.report({ context.report({
node, node,
message: "{{expected}} newline {{location}} \"{{value}}\" directive.", messageId: expected ? "expected" : "unexpected",
data: { data: {
expected: expected ? "Expected" : "Unexpected",
value: node.expression.value, value: node.expression.value,
location location
}, },

View File

@ -36,7 +36,11 @@ module.exports = {
}, },
additionalProperties: false additionalProperties: false
} }
] ],
messages: {
never: "Unexpected blank line between class members.",
always: "Expected blank line between class members."
}
}, },
create(context) { create(context) {
@ -46,9 +50,6 @@ module.exports = {
options[0] = context.options[0] || "always"; options[0] = context.options[0] || "always";
options[1] = context.options[1] || { exceptAfterSingleLine: false }; options[1] = context.options[1] || { exceptAfterSingleLine: false };
const ALWAYS_MESSAGE = "Expected blank line between class members.";
const NEVER_MESSAGE = "Unexpected blank line between class members.";
const sourceCode = context.getSourceCode(); const sourceCode = context.getSourceCode();
/** /**
@ -127,7 +128,7 @@ module.exports = {
(options[0] === "never" && isPadded)) { (options[0] === "never" && isPadded)) {
context.report({ context.report({
node: body[i + 1], node: body[i + 1],
message: isPadded ? NEVER_MESSAGE : ALWAYS_MESSAGE, messageId: isPadded ? "never" : "always",
fix(fixer) { fix(fixer) {
return isPadded return isPadded
? fixer.replaceTextRange([curLast.range[1], nextFirst.range[0]], "\n") ? fixer.replaceTextRange([curLast.range[1], nextFirst.range[0]], "\n")

View File

@ -43,7 +43,10 @@ module.exports = {
} }
] ]
} }
] ],
messages: {
tooDeeply: "Blocks are nested too deeply ({{depth}})."
}
}, },
create(context) { create(context) {
@ -94,7 +97,7 @@ module.exports = {
const len = ++functionStack[functionStack.length - 1]; const len = ++functionStack[functionStack.length - 1];
if (len > maxDepth) { if (len > maxDepth) {
context.report({ node, message: "Blocks are nested too deeply ({{depth}}).", data: { depth: len } }); context.report({ node, messageId: "tooDeeply", data: { depth: len } });
} }
} }

View File

@ -78,7 +78,11 @@ module.exports = {
OPTIONS_OR_INTEGER_SCHEMA, OPTIONS_OR_INTEGER_SCHEMA,
OPTIONS_OR_INTEGER_SCHEMA, OPTIONS_OR_INTEGER_SCHEMA,
OPTIONS_SCHEMA OPTIONS_SCHEMA
] ],
messages: {
max: "Line {{lineNumber}} exceeds the maximum line length of {{maxLength}}.",
maxComment: "Line {{lineNumber}} exceeds the maximum comment line length of {{maxCommentLength}}."
}
}, },
create(context) { create(context) {
@ -341,7 +345,7 @@ module.exports = {
context.report({ context.report({
node, node,
loc: { line: lineNumber, column: 0 }, loc: { line: lineNumber, column: 0 },
message: "Line {{lineNumber}} exceeds the maximum comment line length of {{maxCommentLength}}.", messageId: "maxComment",
data: { data: {
lineNumber: i + 1, lineNumber: i + 1,
maxCommentLength maxCommentLength
@ -352,7 +356,7 @@ module.exports = {
context.report({ context.report({
node, node,
loc: { line: lineNumber, column: 0 }, loc: { line: lineNumber, column: 0 },
message: "Line {{lineNumber}} exceeds the maximum line length of {{maxLength}}.", messageId: "max",
data: { data: {
lineNumber: i + 1, lineNumber: i + 1,
maxLength maxLength

View File

@ -80,7 +80,10 @@ module.exports = {
schema: [ schema: [
OPTIONS_OR_INTEGER_SCHEMA OPTIONS_OR_INTEGER_SCHEMA
] ],
messages: {
exceed: "{{name}} has too many lines ({{lineCount}}). Maximum allowed is {{maxLines}}."
}
}, },
create(context) { create(context) {
@ -201,7 +204,7 @@ module.exports = {
context.report({ context.report({
node, node,
message: "{{name}} has too many lines ({{lineCount}}). Maximum allowed is {{maxLines}}.", messageId: "exceed",
data: { name, lineCount, maxLines } data: { name, lineCount, maxLines }
}); });
} }

View File

@ -51,7 +51,10 @@ module.exports = {
} }
] ]
} }
] ],
messages: {
exceed: "File must be at most {{max}} lines long. It's {{actual}} lines long."
}
}, },
create(context) { create(context) {
@ -134,7 +137,7 @@ module.exports = {
if (lines.length > max) { if (lines.length > max) {
context.report({ context.report({
loc: { line: 1, column: 0 }, loc: { line: 1, column: 0 },
message: "File must be at most {{max}} lines long. It's {{actual}} lines long.", messageId: "exceed",
data: { data: {
max, max,
actual: lines.length actual: lines.length

View File

@ -43,7 +43,10 @@ module.exports = {
} }
] ]
} }
] ],
messages: {
exceed: "Too many nested callbacks ({{num}}). Maximum allowed is {{max}}."
}
}, },
create(context) { create(context) {
@ -86,7 +89,7 @@ module.exports = {
if (callbackStack.length > THRESHOLD) { if (callbackStack.length > THRESHOLD) {
const opts = { num: callbackStack.length, max: THRESHOLD }; const opts = { num: callbackStack.length, max: THRESHOLD };
context.report({ node, message: "Too many nested callbacks ({{num}}). Maximum allowed is {{max}}.", data: opts }); context.report({ node, messageId: "exceed", data: opts });
} }
} }

View File

@ -51,7 +51,10 @@ module.exports = {
} }
] ]
} }
] ],
messages: {
exceed: "{{name}} has too many parameters ({{count}}). Maximum allowed is {{max}}."
}
}, },
create(context) { create(context) {
@ -80,7 +83,7 @@ module.exports = {
context.report({ context.report({
loc: astUtils.getFunctionHeadLoc(node, sourceCode), loc: astUtils.getFunctionHeadLoc(node, sourceCode),
node, node,
message: "{{name}} has too many parameters ({{count}}). Maximum allowed is {{max}}.", messageId: "exceed",
data: { data: {
name: lodash.upperFirst(astUtils.getFunctionNameWithKind(node)), name: lodash.upperFirst(astUtils.getFunctionNameWithKind(node)),
count: node.params.length, count: node.params.length,

View File

@ -36,15 +36,17 @@ module.exports = {
}, },
additionalProperties: false additionalProperties: false
} }
] ],
messages: {
exceed: "This line has {{numberOfStatementsOnThisLine}} {{statements}}. Maximum allowed is {{maxStatementsPerLine}}."
}
}, },
create(context) { create(context) {
const sourceCode = context.getSourceCode(), const sourceCode = context.getSourceCode(),
options = context.options[0] || {}, options = context.options[0] || {},
maxStatementsPerLine = typeof options.max !== "undefined" ? options.max : 1, maxStatementsPerLine = typeof options.max !== "undefined" ? options.max : 1;
message = "This line has {{numberOfStatementsOnThisLine}} {{statements}}. Maximum allowed is {{maxStatementsPerLine}}.";
let lastStatementLine = 0, let lastStatementLine = 0,
numberOfStatementsOnThisLine = 0, numberOfStatementsOnThisLine = 0,
@ -65,7 +67,7 @@ module.exports = {
if (firstExtraStatement) { if (firstExtraStatement) {
context.report({ context.report({
node: firstExtraStatement, node: firstExtraStatement,
message, messageId: "exceed",
data: { data: {
numberOfStatementsOnThisLine, numberOfStatementsOnThisLine,
maxStatementsPerLine, maxStatementsPerLine,

View File

@ -60,7 +60,10 @@ module.exports = {
}, },
additionalProperties: false additionalProperties: false
} }
] ],
messages: {
exceed: "{{name}} has too many statements ({{count}}). Maximum allowed is {{max}}."
}
}, },
create(context) { create(context) {
@ -99,7 +102,7 @@ module.exports = {
context.report({ context.report({
node, node,
message: "{{name}} has too many statements ({{count}}). Maximum allowed is {{max}}.", messageId: "exceed",
data: { name, count, max } data: { name, count, max }
}); });
} }

View File

@ -22,20 +22,21 @@ module.exports = {
}, },
fixable: "whitespace", fixable: "whitespace",
schema: [{ enum: ["starred-block", "separate-lines", "bare-block"] }] schema: [{ enum: ["starred-block", "separate-lines", "bare-block"] }],
messages: {
expectedBlock: "Expected a block comment instead of consecutive line comments.",
startNewline: "Expected a linebreak after '/*'.",
endNewline: "Expected a linebreak before '*/'.",
missingStar: "Expected a '*' at the start of this line.",
alignment: "Expected this line to be aligned with the start of the comment.",
expectedLines: "Expected multiple line comments instead of a block comment."
}
}, },
create(context) { create(context) {
const sourceCode = context.getSourceCode(); const sourceCode = context.getSourceCode();
const option = context.options[0] || "starred-block"; const option = context.options[0] || "starred-block";
const EXPECTED_BLOCK_ERROR = "Expected a block comment instead of consecutive line comments.";
const START_NEWLINE_ERROR = "Expected a linebreak after '/*'.";
const END_NEWLINE_ERROR = "Expected a linebreak before '*/'.";
const MISSING_STAR_ERROR = "Expected a '*' at the start of this line.";
const ALIGNMENT_ERROR = "Expected this line to be aligned with the start of the comment.";
const EXPECTED_LINES_ERROR = "Expected multiple line comments instead of a block comment.";
//---------------------------------------------------------------------- //----------------------------------------------------------------------
// Helpers // Helpers
//---------------------------------------------------------------------- //----------------------------------------------------------------------
@ -127,7 +128,7 @@ module.exports = {
start: commentGroup[0].loc.start, start: commentGroup[0].loc.start,
end: commentGroup[commentGroup.length - 1].loc.end end: commentGroup[commentGroup.length - 1].loc.end
}, },
message: EXPECTED_BLOCK_ERROR, messageId: "expectedBlock",
fix(fixer) { fix(fixer) {
const range = [commentGroup[0].range[0], commentGroup[commentGroup.length - 1].range[1]]; const range = [commentGroup[0].range[0], commentGroup[commentGroup.length - 1].range[1]];
const starredBlock = `/*${convertToStarredBlock(commentGroup[0], commentLines)}*/`; const starredBlock = `/*${convertToStarredBlock(commentGroup[0], commentLines)}*/`;
@ -150,7 +151,7 @@ module.exports = {
start: block.loc.start, start: block.loc.start,
end: { line: block.loc.start.line, column: block.loc.start.column + 2 } end: { line: block.loc.start.line, column: block.loc.start.column + 2 }
}, },
message: START_NEWLINE_ERROR, messageId: "startNewline",
fix: fixer => fixer.insertTextAfterRange([start, start + 2], `\n${expectedLinePrefix}`) fix: fixer => fixer.insertTextAfterRange([start, start + 2], `\n${expectedLinePrefix}`)
}); });
} }
@ -161,7 +162,7 @@ module.exports = {
start: { line: block.loc.end.line, column: block.loc.end.column - 2 }, start: { line: block.loc.end.line, column: block.loc.end.column - 2 },
end: block.loc.end end: block.loc.end
}, },
message: END_NEWLINE_ERROR, messageId: "endNewline",
fix: fixer => fixer.replaceTextRange([block.range[1] - 2, block.range[1]], `\n${expectedLinePrefix}/`) fix: fixer => fixer.replaceTextRange([block.range[1] - 2, block.range[1]], `\n${expectedLinePrefix}/`)
}); });
} }
@ -175,9 +176,9 @@ 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 }
}, },
message: /^\s*\*/.test(lineText) messageId: /^\s*\*/.test(lineText)
? ALIGNMENT_ERROR ? "alignment"
: MISSING_STAR_ERROR, : "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*\*? ?/)[0].length;
@ -209,7 +210,7 @@ module.exports = {
start: block.loc.start, start: block.loc.start,
end: { line: block.loc.start.line, column: block.loc.start.column + 2 } end: { line: block.loc.start.line, column: block.loc.start.column + 2 }
}, },
message: EXPECTED_LINES_ERROR, messageId: "expectedLines",
fix(fixer) { fix(fixer) {
return fixer.replaceText(block, convertToSeparateLines(block, commentLines.filter(line => line))); return fixer.replaceText(block, convertToSeparateLines(block, commentLines.filter(line => line)));
} }
@ -228,7 +229,7 @@ module.exports = {
start: commentGroup[0].loc.start, start: commentGroup[0].loc.start,
end: commentGroup[commentGroup.length - 1].loc.end end: commentGroup[commentGroup.length - 1].loc.end
}, },
message: EXPECTED_BLOCK_ERROR, messageId: "expectedBlock",
fix(fixer) { fix(fixer) {
const range = [commentGroup[0].range[0], commentGroup[commentGroup.length - 1].range[1]]; const range = [commentGroup[0].range[0], commentGroup[commentGroup.length - 1].range[1]];
const block = convertToBlock(commentGroup[0], commentLines.filter(line => line)); const block = convertToBlock(commentGroup[0], commentLines.filter(line => line));
@ -249,7 +250,7 @@ module.exports = {
start: block.loc.start, start: block.loc.start,
end: { line: block.loc.start.line, column: block.loc.start.column + 2 } end: { line: block.loc.start.line, column: block.loc.start.column + 2 }
}, },
message: EXPECTED_BLOCK_ERROR, messageId: "expectedBlock",
fix(fixer) { fix(fixer) {
return fixer.replaceText(block, convertToBlock(block, commentLines.filter(line => line))); return fixer.replaceText(block, convertToBlock(block, commentLines.filter(line => line)));
} }

View File

@ -26,7 +26,13 @@ module.exports = {
{ {
enum: ["always", "always-multiline", "never"] enum: ["always", "always-multiline", "never"]
} }
] ],
messages: {
expectedTestCons: "Expected newline between test and consequent of ternary expression.",
expectedConsAlt: "Expected newline between consequent and alternate of ternary expression.",
unexpectedTestCons: "Unexpected newline between test and consequent of ternary expression.",
unexpectedConsAlt: "Unexpected newline between consequent and alternate of ternary expression."
}
}, },
create(context) { create(context) {
@ -49,11 +55,7 @@ module.exports = {
function reportError(node, parentNode, expected) { function reportError(node, parentNode, expected) {
context.report({ context.report({
node, node,
message: "{{expected}} newline between {{typeOfError}} of ternary expression.", messageId: `${expected ? "expected" : "unexpected"}${node === parentNode.test ? "TestCons" : "ConsAlt"}`
data: {
expected: expected ? "Expected" : "Unexpected",
typeOfError: node === parentNode.test ? "test and consequent" : "consequent and alternate"
}
}); });
} }

View File

@ -117,7 +117,11 @@ module.exports = {
}, },
additionalProperties: false additionalProperties: false
} }
] ],
messages: {
upper: "A function with a name starting with an uppercase letter should only be used as a constructor.",
lower: "A constructor name should not start with a lowercase letter."
}
}, },
create(context) { create(context) {
@ -219,19 +223,19 @@ module.exports = {
} }
/** /**
* Reports the given message for the given node. The location will be the start of the property or the callee. * Reports the given messageId for the given node. The location will be the start of the property or the callee.
* @param {ASTNode} node CallExpression or NewExpression node. * @param {ASTNode} node CallExpression or NewExpression node.
* @param {string} message The message to report. * @param {string} messageId The messageId to report.
* @returns {void} * @returns {void}
*/ */
function report(node, message) { function report(node, messageId) {
let callee = node.callee; let callee = node.callee;
if (callee.type === "MemberExpression") { if (callee.type === "MemberExpression") {
callee = callee.property; callee = callee.property;
} }
context.report({ node, loc: callee.loc.start, message }); context.report({ node, loc: callee.loc.start, messageId });
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
@ -248,7 +252,7 @@ module.exports = {
const isAllowed = capitalization !== "lower" || isCapAllowed(newIsCapExceptions, node, constructorName, newIsCapExceptionPattern); const isAllowed = capitalization !== "lower" || isCapAllowed(newIsCapExceptions, node, constructorName, newIsCapExceptionPattern);
if (!isAllowed) { if (!isAllowed) {
report(node, "A constructor name should not start with a lowercase letter."); report(node, "lower");
} }
} }
}; };
@ -264,7 +268,7 @@ module.exports = {
const isAllowed = capitalization !== "upper" || isCapAllowed(capIsNewExceptions, node, calleeName, capIsNewExceptionPattern); const isAllowed = capitalization !== "upper" || isCapAllowed(capIsNewExceptions, node, calleeName, capIsNewExceptionPattern);
if (!isAllowed) { if (!isAllowed) {
report(node, "A function with a name starting with an uppercase letter should only be used as a constructor."); report(node, "upper");
} }
} }
}; };

View File

@ -30,8 +30,11 @@ module.exports = {
url: "https://eslint.org/docs/rules/new-parens" url: "https://eslint.org/docs/rules/new-parens"
}, },
fixable: "code",
schema: [], schema: [],
fixable: "code" messages: {
missing: "Missing '()' invoking a constructor."
}
}, },
create(context) { create(context) {
@ -50,7 +53,7 @@ module.exports = {
if (!hasParens) { if (!hasParens) {
context.report({ context.report({
node, node,
message: "Missing '()' invoking a constructor.", messageId: "missing",
fix: fixer => fixer.insertTextAfter(node, "()") fix: fixer => fixer.insertTextAfter(node, "()")
}); });
} }

View File

@ -26,14 +26,16 @@ module.exports = {
recommended: false, recommended: false,
url: "https://eslint.org/docs/rules/newline-after-var" url: "https://eslint.org/docs/rules/newline-after-var"
}, },
schema: [ schema: [
{ {
enum: ["never", "always"] enum: ["never", "always"]
} }
], ],
fixable: "whitespace", fixable: "whitespace",
messages: {
expected: "Expected blank line after variable declarations.",
unexpected: "Unexpected blank line after variable declarations."
},
deprecated: true, deprecated: true,
@ -41,10 +43,6 @@ module.exports = {
}, },
create(context) { create(context) {
const ALWAYS_MESSAGE = "Expected blank line after variable declarations.",
NEVER_MESSAGE = "Unexpected blank line after variable declarations.";
const sourceCode = context.getSourceCode(); const sourceCode = context.getSourceCode();
// Default `mode` to "always". // Default `mode` to "always".
@ -214,7 +212,7 @@ module.exports = {
if (mode === "never" && noNextLineToken && !hasNextLineComment) { if (mode === "never" && noNextLineToken && !hasNextLineComment) {
context.report({ context.report({
node, node,
message: NEVER_MESSAGE, messageId: "unexpected",
data: { identifier: node.name }, data: { identifier: node.name },
fix(fixer) { fix(fixer) {
const linesBetween = sourceCode.getText().slice(lastToken.range[1], nextToken.range[0]).split(astUtils.LINEBREAK_MATCHER); const linesBetween = sourceCode.getText().slice(lastToken.range[1], nextToken.range[0]).split(astUtils.LINEBREAK_MATCHER);
@ -233,7 +231,7 @@ module.exports = {
) { ) {
context.report({ context.report({
node, node,
message: ALWAYS_MESSAGE, messageId: "expected",
data: { identifier: node.name }, data: { identifier: node.name },
fix(fixer) { fix(fixer) {
if ((noNextLineToken ? getLastCommentLineOfBlock(nextLineNum) : lastToken.loc.end.line) === nextToken.loc.start.line) { if ((noNextLineToken ? getLastCommentLineOfBlock(nextLineNum) : lastToken.loc.end.line) === nextToken.loc.start.line) {

View File

@ -22,6 +22,10 @@ module.exports = {
fixable: "whitespace", fixable: "whitespace",
schema: [], schema: [],
messages: {
expected: "Expected newline before return statement."
},
deprecated: true, deprecated: true,
replacedBy: ["padding-line-between-statements"] replacedBy: ["padding-line-between-statements"]
}, },
@ -196,7 +200,7 @@ module.exports = {
if (!isFirstNode(node) && !hasNewlineBefore(node)) { if (!isFirstNode(node) && !hasNewlineBefore(node)) {
context.report({ context.report({
node, node,
message: "Expected newline before return statement.", messageId: "expected",
fix(fixer) { fix(fixer) {
if (canFix(node)) { if (canFix(node)) {
const tokenBefore = sourceCode.getTokenBefore(node); const tokenBefore = sourceCode.getTokenBefore(node);

View File

@ -35,7 +35,10 @@ module.exports = {
} }
}, },
additionalProperties: false additionalProperties: false
}] }],
messages: {
expected: "Expected line break before `{{callee}}`."
}
}, },
create(context) { create(context) {
@ -91,7 +94,7 @@ module.exports = {
context.report({ context.report({
node: callee.property, node: callee.property,
loc: callee.property.loc.start, loc: callee.property.loc.start,
message: "Expected line break before `{{callee}}`.", messageId: "expected",
data: { data: {
callee: getPropertyText(callee) callee: getPropertyText(callee)
}, },

View File

@ -20,7 +20,10 @@ module.exports = {
}, },
fixable: null, fixable: null,
schema: [] schema: [],
messages: {
async: "Promise executor functions should not be async."
}
}, },
create(context) { create(context) {
@ -28,7 +31,7 @@ module.exports = {
"NewExpression[callee.name='Promise'][arguments.0.async=true]"(node) { "NewExpression[callee.name='Promise'][arguments.0.async=true]"(node) {
context.report({ context.report({
node: context.getSourceCode().getFirstToken(node.arguments[0], token => token.value === "async"), node: context.getSourceCode().getFirstToken(node.arguments[0], token => token.value === "async"),
message: "Promise executor functions should not be async." messageId: "async"
}); });
} }
}; };

View File

@ -109,7 +109,10 @@ module.exports = {
const isLeftShortCircuit = (isLeftConstant && isLogicalIdentity(node.left, node.operator)); const isLeftShortCircuit = (isLeftConstant && isLogicalIdentity(node.left, node.operator));
const isRightShortCircuit = (isRightConstant && isLogicalIdentity(node.right, node.operator)); const isRightShortCircuit = (isRightConstant && isLogicalIdentity(node.right, node.operator));
return (isLeftConstant && isRightConstant) || isLeftShortCircuit || isRightShortCircuit; return (isLeftConstant && isRightConstant) ||
(node.operator === "||" && isRightConstant && node.right.value) || // in the case of an "OR", we need to know if the right constant value is truthy
isLeftShortCircuit ||
isRightShortCircuit;
} }
case "AssignmentExpression": case "AssignmentExpression":

View File

@ -29,18 +29,17 @@ function getValue(node) {
* @param {ASTNode} node - A node to get. * @param {ASTNode} node - A node to get.
* @param {string} value - The name of the imported or exported module. * @param {string} value - The name of the imported or exported module.
* @param {string[]} array - The array containing other imports or exports in the file. * @param {string[]} array - The array containing other imports or exports in the file.
* @param {string} message - A message to be reported after the name of the module * @param {string} messageId - A messageId to be reported after the name of the module
* *
* @returns {void} No return value * @returns {void} No return value
*/ */
function checkAndReport(context, node, value, array, message) { function checkAndReport(context, node, value, array, messageId) {
if (array.indexOf(value) !== -1) { if (array.indexOf(value) !== -1) {
context.report({ context.report({
node, node,
message: "'{{module}}' {{message}}", messageId,
data: { data: {
module: value, module: value
message
} }
}); });
} }
@ -66,10 +65,10 @@ function handleImports(context, includeExports, importsInFile, exportsInFile) {
const value = getValue(node); const value = getValue(node);
if (value) { if (value) {
checkAndReport(context, node, value, importsInFile, "import is duplicated."); checkAndReport(context, node, value, importsInFile, "import");
if (includeExports) { if (includeExports) {
checkAndReport(context, node, value, exportsInFile, "import is duplicated as export."); checkAndReport(context, node, value, exportsInFile, "importAs");
} }
importsInFile.push(value); importsInFile.push(value);
@ -91,8 +90,8 @@ function handleExports(context, importsInFile, exportsInFile) {
const value = getValue(node); const value = getValue(node);
if (value) { if (value) {
checkAndReport(context, node, value, exportsInFile, "export is duplicated."); checkAndReport(context, node, value, exportsInFile, "export");
checkAndReport(context, node, value, importsInFile, "export is duplicated as import."); checkAndReport(context, node, value, importsInFile, "exportAs");
exportsInFile.push(value); exportsInFile.push(value);
} }
@ -118,7 +117,13 @@ module.exports = {
} }
}, },
additionalProperties: false additionalProperties: false
}] }],
messages: {
import: "'{{module}}' import is duplicated.",
importAs: "'{{module}}' import is duplicated as export.",
export: "'{{module}}' export is duplicated.",
exportAs: "'{{module}}' export is duplicated as import."
}
}, },
create(context) { create(context) {

View File

@ -74,7 +74,11 @@ module.exports = {
}, },
additionalProperties: false additionalProperties: false
} }
] ],
messages: {
case: "Expected a 'break' statement before 'case'.",
default: "Expected a 'break' statement before 'default'."
}
}, },
create(context) { create(context) {
@ -111,8 +115,7 @@ module.exports = {
*/ */
if (fallthroughCase && !hasFallthroughComment(node, context, fallthroughCommentPattern)) { if (fallthroughCase && !hasFallthroughComment(node, context, fallthroughCommentPattern)) {
context.report({ context.report({
message: "Expected a 'break' statement before '{{type}}'.", messageId: node.test ? "case" : "default",
data: { type: node.test ? "case" : "default" },
node node
}); });
} }

View File

@ -27,7 +27,11 @@ module.exports = {
}, },
schema: [], schema: [],
fixable: "code" fixable: "code",
messages: {
leading: "A leading decimal point can be confused with a dot.",
trailing: "A trailing decimal point can be confused with a dot."
}
}, },
create(context) { create(context) {
@ -40,7 +44,7 @@ module.exports = {
if (node.raw.startsWith(".")) { if (node.raw.startsWith(".")) {
context.report({ context.report({
node, node,
message: "A leading decimal point can be confused with a dot.", messageId: "leading",
fix(fixer) { fix(fixer) {
const tokenBefore = sourceCode.getTokenBefore(node); const tokenBefore = sourceCode.getTokenBefore(node);
const needsSpaceBefore = tokenBefore && const needsSpaceBefore = tokenBefore &&
@ -54,7 +58,7 @@ module.exports = {
if (node.raw.indexOf(".") === node.raw.length - 1) { if (node.raw.indexOf(".") === node.raw.length - 1) {
context.report({ context.report({
node, node,
message: "A trailing decimal point can be confused with a dot.", messageId: "trailing",
fix: fixer => fixer.insertTextAfter(node, "0") fix: fixer => fixer.insertTextAfter(node, "0")
}); });
} }

View File

@ -44,7 +44,10 @@ module.exports = {
}, },
additionalProperties: false additionalProperties: false
} }
] ],
messages: {
undef: "'{{name}}' is not defined."
}
}, },
create(context) { create(context) {
@ -64,7 +67,7 @@ module.exports = {
context.report({ context.report({
node: identifier, node: identifier,
message: "'{{name}}' is not defined.", messageId: "undef",
data: identifier data: identifier
}); });
}); });

View File

@ -25,16 +25,17 @@ module.exports = {
url: "https://eslint.org/docs/rules/no-unexpected-multiline" url: "https://eslint.org/docs/rules/no-unexpected-multiline"
}, },
schema: [] schema: [],
messages: {
function: "Unexpected newline between function and ( of function call.",
property: "Unexpected newline between object and [ of property access.",
taggedTemplate: "Unexpected newline between template tag and template literal.",
division: "Unexpected newline between numerator and division operator."
}
}, },
create(context) { create(context) {
const FUNCTION_MESSAGE = "Unexpected newline between function and ( of function call.";
const PROPERTY_MESSAGE = "Unexpected newline between object and [ of property access.";
const TAGGED_TEMPLATE_MESSAGE = "Unexpected newline between template tag and template literal.";
const DIVISION_MESSAGE = "Unexpected newline between numerator and division operator.";
const REGEX_FLAG_MATCHER = /^[gimsuy]+$/; const REGEX_FLAG_MATCHER = /^[gimsuy]+$/;
const sourceCode = context.getSourceCode(); const sourceCode = context.getSourceCode();
@ -43,16 +44,16 @@ module.exports = {
* Check to see if there is a newline between the node and the following open bracket * Check to see if there is a newline between the node and the following open bracket
* line's expression * line's expression
* @param {ASTNode} node The node to check. * @param {ASTNode} node The node to check.
* @param {string} msg The error message to use. * @param {string} messageId The error messageId to use.
* @returns {void} * @returns {void}
* @private * @private
*/ */
function checkForBreakAfter(node, msg) { function checkForBreakAfter(node, messageId) {
const openParen = sourceCode.getTokenAfter(node, astUtils.isNotClosingParenToken); const openParen = sourceCode.getTokenAfter(node, astUtils.isNotClosingParenToken);
const nodeExpressionEnd = sourceCode.getTokenBefore(openParen); const nodeExpressionEnd = sourceCode.getTokenBefore(openParen);
if (openParen.loc.start.line !== nodeExpressionEnd.loc.end.line) { if (openParen.loc.start.line !== nodeExpressionEnd.loc.end.line) {
context.report({ node, loc: openParen.loc.start, message: msg, data: { char: openParen.value } }); context.report({ node, loc: openParen.loc.start, messageId, data: { char: openParen.value } });
} }
} }
@ -66,21 +67,21 @@ module.exports = {
if (!node.computed) { if (!node.computed) {
return; return;
} }
checkForBreakAfter(node.object, PROPERTY_MESSAGE); checkForBreakAfter(node.object, "property");
}, },
TaggedTemplateExpression(node) { TaggedTemplateExpression(node) {
if (node.tag.loc.end.line === node.quasi.loc.start.line) { if (node.tag.loc.end.line === node.quasi.loc.start.line) {
return; return;
} }
context.report({ node, loc: node.loc.start, message: TAGGED_TEMPLATE_MESSAGE }); context.report({ node, loc: node.loc.start, messageId: "taggedTemplate" });
}, },
CallExpression(node) { CallExpression(node) {
if (node.arguments.length === 0) { if (node.arguments.length === 0) {
return; return;
} }
checkForBreakAfter(node.callee, FUNCTION_MESSAGE); checkForBreakAfter(node.callee, "function");
}, },
"BinaryExpression[operator='/'] > BinaryExpression[operator='/'].left"(node) { "BinaryExpression[operator='/'] > BinaryExpression[operator='/'].left"(node) {
@ -92,7 +93,7 @@ module.exports = {
REGEX_FLAG_MATCHER.test(tokenAfterOperator.value) && REGEX_FLAG_MATCHER.test(tokenAfterOperator.value) &&
secondSlash.range[1] === tokenAfterOperator.range[0] secondSlash.range[1] === tokenAfterOperator.range[0]
) { ) {
checkForBreakAfter(node.left, DIVISION_MESSAGE); checkForBreakAfter(node.left, "division");
} }
} }
}; };

View File

@ -51,7 +51,10 @@ module.exports = {
}, },
schema: [], schema: [],
fixable: "code" fixable: "code",
messages: {
unexpected: "Unexpected negating the left operand of '{{operator}}' operator."
}
}, },
create(context) { create(context) {
@ -66,8 +69,8 @@ module.exports = {
context.report({ context.report({
node, node,
loc: node.left.loc, loc: node.left.loc,
message: "Unexpected negating the left operand of '{{operator}}' operator.", messageId: "unexpected",
data: node, data: { operator: node.operator },
fix(fixer) { fix(fixer) {
const negationToken = sourceCode.getFirstToken(node.left); const negationToken = sourceCode.getFirstToken(node.left);

View File

@ -21,7 +21,12 @@ module.exports = {
}, },
schema: [], schema: [],
fixable: "code"
fixable: "code",
messages: {
unused: "'{{name}}:' is defined but never used."
}
}, },
create(context) { create(context) {
@ -53,7 +58,7 @@ module.exports = {
if (!scopeInfo.used) { if (!scopeInfo.used) {
context.report({ context.report({
node: node.label, node: node.label,
message: "'{{name}}:' is defined but never used.", messageId: "unused",
data: node.label, data: node.label,
fix(fixer) { fix(fixer) {

View File

@ -104,7 +104,11 @@ module.exports = {
} }
], ],
fixable: "code" fixable: "code",
messages: {
replaced: "Assignment can be replaced with operator assignment.",
unexpected: "Unexpected operator assignment shorthand."
}
}, },
create(context) { create(context) {
@ -138,7 +142,7 @@ module.exports = {
if (same(left, expr.left)) { if (same(left, expr.left)) {
context.report({ context.report({
node, node,
message: "Assignment can be replaced with operator assignment.", messageId: "replaced",
fix(fixer) { fix(fixer) {
if (canBeFixed(left)) { if (canBeFixed(left)) {
const equalsToken = getOperatorToken(node); const equalsToken = getOperatorToken(node);
@ -160,7 +164,7 @@ module.exports = {
*/ */
context.report({ context.report({
node, node,
message: "Assignment can be replaced with operator assignment." messageId: "replaced"
}); });
} }
} }
@ -175,7 +179,7 @@ module.exports = {
if (node.operator !== "=") { if (node.operator !== "=") {
context.report({ context.report({
node, node,
message: "Unexpected operator assignment shorthand.", messageId: "unexpected",
fix(fixer) { fix(fixer) {
if (canBeFixed(node.left)) { if (canBeFixed(node.left)) {
const operatorToken = getOperatorToken(node); const operatorToken = getOperatorToken(node);

View File

@ -350,7 +350,10 @@ module.exports = {
}, },
additionalProperties: false additionalProperties: false
} }
] ],
messages: {
useConst: "'{{name}}' is never reassigned. Use 'const' instead."
}
}, },
create(context) { create(context) {
@ -445,7 +448,7 @@ module.exports = {
nodesToReport.forEach(node => { nodesToReport.forEach(node => {
context.report({ context.report({
node, node,
message: "'{{name}}' is never reassigned. Use 'const' instead.", messageId: "useConst",
data: node, data: node,
fix: shouldFix ? fixer => fixer.replaceText(sourceCode.getFirstToken(varDeclParent), "const") : null fix: shouldFix ? fixer => fixer.replaceText(sourceCode.getFirstToken(varDeclParent), "const") : null
}); });

View File

@ -46,7 +46,15 @@ module.exports = {
}, },
additionalProperties: false additionalProperties: false
} }
] ],
messages: {
unexpectedBefore: "Unexpected space before unary operator '{{operator}}'.",
unexpectedAfter: "Unexpected space after unary operator '{{operator}}'.",
unexpectedAfterWord: "Unexpected space after unary word operator '{{word}}'.",
wordOperator: "Unary word operator '{{word}}' must be followed by whitespace.",
operator: "Unary operator '{{operator}}' must be followed by whitespace.",
beforeUnaryExpressions: "Space is required before unary expressions '{{token}}'."
}
}, },
create(context) { create(context) {
@ -98,7 +106,7 @@ module.exports = {
if (secondToken.range[0] === firstToken.range[1]) { if (secondToken.range[0] === firstToken.range[1]) {
context.report({ context.report({
node, node,
message: "Unary word operator '{{word}}' must be followed by whitespace.", messageId: "wordOperator",
data: { data: {
word word
}, },
@ -122,7 +130,7 @@ module.exports = {
if (secondToken.range[0] > firstToken.range[1]) { if (secondToken.range[0] > firstToken.range[1]) {
context.report({ context.report({
node, node,
message: "Unexpected space after unary word operator '{{word}}'.", messageId: "unexpectedAfterWord",
data: { data: {
word word
}, },
@ -198,7 +206,7 @@ module.exports = {
if (firstToken.range[1] === secondToken.range[0]) { if (firstToken.range[1] === secondToken.range[0]) {
context.report({ context.report({
node, node,
message: "Unary operator '{{operator}}' must be followed by whitespace.", messageId: "operator",
data: { data: {
operator: firstToken.value operator: firstToken.value
}, },
@ -211,7 +219,7 @@ module.exports = {
if (firstToken.range[1] === secondToken.range[0]) { if (firstToken.range[1] === secondToken.range[0]) {
context.report({ context.report({
node, node,
message: "Space is required before unary expressions '{{token}}'.", messageId: "beforeUnaryExpressions",
data: { data: {
token: secondToken.value token: secondToken.value
}, },
@ -235,7 +243,7 @@ module.exports = {
if (secondToken.range[0] > firstToken.range[1]) { if (secondToken.range[0] > firstToken.range[1]) {
context.report({ context.report({
node, node,
message: "Unexpected space after unary operator '{{operator}}'.", messageId: "unexpectedAfter",
data: { data: {
operator: firstToken.value operator: firstToken.value
}, },
@ -251,7 +259,7 @@ module.exports = {
if (secondToken.range[0] > firstToken.range[1]) { if (secondToken.range[0] > firstToken.range[1]) {
context.report({ context.report({
node, node,
message: "Unexpected space before unary operator '{{operator}}'.", messageId: "unexpectedBefore",
data: { data: {
operator: secondToken.value operator: secondToken.value
}, },

View File

@ -15,19 +15,6 @@ const astUtils = require("../util/ast-utils");
// Helpers // Helpers
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
const messages = {
function: "Use the function form of 'use strict'.",
global: "Use the global form of 'use strict'.",
multiple: "Multiple 'use strict' directives.",
never: "Strict mode is not permitted.",
unnecessary: "Unnecessary 'use strict' directive.",
module: "'use strict' is unnecessary inside of modules.",
implied: "'use strict' is unnecessary when implied strict mode is enabled.",
unnecessaryInClasses: "'use strict' is unnecessary inside of classes.",
nonSimpleParameterList: "'use strict' directive inside a function with non-simple parameter list throws a syntax error since ES2016.",
wrap: "Wrap {{name}} in a function with 'use strict' directive."
};
/** /**
* Gets all of the Use Strict Directives in the Directive Prologue of a group of * Gets all of the Use Strict Directives in the Directive Prologue of a group of
* statements. * statements.
@ -95,7 +82,19 @@ module.exports = {
} }
], ],
fixable: "code" fixable: "code",
messages: {
function: "Use the function form of 'use strict'.",
global: "Use the global form of 'use strict'.",
multiple: "Multiple 'use strict' directives.",
never: "Strict mode is not permitted.",
unnecessary: "Unnecessary 'use strict' directive.",
module: "'use strict' is unnecessary inside of modules.",
implied: "'use strict' is unnecessary when implied strict mode is enabled.",
unnecessaryInClasses: "'use strict' is unnecessary inside of classes.",
nonSimpleParameterList: "'use strict' directive inside a function with non-simple parameter list throws a syntax error since ES2016.",
wrap: "Wrap {{name}} in a function with 'use strict' directive."
}
}, },
create(context) { create(context) {
@ -134,36 +133,36 @@ module.exports = {
* @param {ASTNode[]} nodes Nodes. * @param {ASTNode[]} nodes Nodes.
* @param {string} start Index to start from. * @param {string} start Index to start from.
* @param {string} end Index to end before. * @param {string} end Index to end before.
* @param {string} message Message to display. * @param {string} messageId Message to display.
* @param {boolean} fix `true` if the directive should be fixed (i.e. removed) * @param {boolean} fix `true` if the directive should be fixed (i.e. removed)
* @returns {void} * @returns {void}
*/ */
function reportSlice(nodes, start, end, message, fix) { function reportSlice(nodes, start, end, messageId, fix) {
nodes.slice(start, end).forEach(node => { nodes.slice(start, end).forEach(node => {
context.report({ node, message, fix: fix ? getFixFunction(node) : null }); context.report({ node, messageId, fix: fix ? getFixFunction(node) : null });
}); });
} }
/** /**
* Report all nodes in an array with a given message. * Report all nodes in an array with a given message.
* @param {ASTNode[]} nodes Nodes. * @param {ASTNode[]} nodes Nodes.
* @param {string} message Message to display. * @param {string} messageId Message id to display.
* @param {boolean} fix `true` if the directive should be fixed (i.e. removed) * @param {boolean} fix `true` if the directive should be fixed (i.e. removed)
* @returns {void} * @returns {void}
*/ */
function reportAll(nodes, message, fix) { function reportAll(nodes, messageId, fix) {
reportSlice(nodes, 0, nodes.length, message, fix); reportSlice(nodes, 0, nodes.length, messageId, fix);
} }
/** /**
* Report all nodes in an array, except the first, with a given message. * Report all nodes in an array, except the first, with a given message.
* @param {ASTNode[]} nodes Nodes. * @param {ASTNode[]} nodes Nodes.
* @param {string} message Message to display. * @param {string} messageId Message id to display.
* @param {boolean} fix `true` if the directive should be fixed (i.e. removed) * @param {boolean} fix `true` if the directive should be fixed (i.e. removed)
* @returns {void} * @returns {void}
*/ */
function reportAllExceptFirst(nodes, message, fix) { function reportAllExceptFirst(nodes, messageId, fix) {
reportSlice(nodes, 1, nodes.length, message, fix); reportSlice(nodes, 1, nodes.length, messageId, fix);
} }
/** /**
@ -181,21 +180,21 @@ module.exports = {
if (isStrict) { if (isStrict) {
if (!isSimpleParameterList(node.params)) { if (!isSimpleParameterList(node.params)) {
context.report({ node: useStrictDirectives[0], message: messages.nonSimpleParameterList }); context.report({ node: useStrictDirectives[0], messageId: "nonSimpleParameterList" });
} else if (isParentStrict) { } else if (isParentStrict) {
context.report({ node: useStrictDirectives[0], message: messages.unnecessary, fix: getFixFunction(useStrictDirectives[0]) }); context.report({ node: useStrictDirectives[0], messageId: "unnecessary", fix: getFixFunction(useStrictDirectives[0]) });
} else if (isInClass) { } else if (isInClass) {
context.report({ node: useStrictDirectives[0], message: messages.unnecessaryInClasses, fix: getFixFunction(useStrictDirectives[0]) }); context.report({ node: useStrictDirectives[0], messageId: "unnecessaryInClasses", fix: getFixFunction(useStrictDirectives[0]) });
} }
reportAllExceptFirst(useStrictDirectives, messages.multiple, true); reportAllExceptFirst(useStrictDirectives, "multiple", true);
} else if (isParentGlobal) { } else if (isParentGlobal) {
if (isSimpleParameterList(node.params)) { if (isSimpleParameterList(node.params)) {
context.report({ node, message: messages.function }); context.report({ node, messageId: "function" });
} else { } else {
context.report({ context.report({
node, node,
message: messages.wrap, messageId: "wrap",
data: { name: astUtils.getFunctionNameWithKind(node) } data: { name: astUtils.getFunctionNameWithKind(node) }
}); });
} }
@ -228,10 +227,10 @@ module.exports = {
enterFunctionInFunctionMode(node, useStrictDirectives); enterFunctionInFunctionMode(node, useStrictDirectives);
} else if (useStrictDirectives.length > 0) { } else if (useStrictDirectives.length > 0) {
if (isSimpleParameterList(node.params)) { if (isSimpleParameterList(node.params)) {
reportAll(useStrictDirectives, messages[mode], shouldFix(mode)); reportAll(useStrictDirectives, mode, shouldFix(mode));
} else { } else {
context.report({ node: useStrictDirectives[0], message: messages.nonSimpleParameterList }); context.report({ node: useStrictDirectives[0], messageId: "nonSimpleParameterList" });
reportAllExceptFirst(useStrictDirectives, messages.multiple, true); reportAllExceptFirst(useStrictDirectives, "multiple", true);
} }
} }
} }
@ -246,11 +245,11 @@ module.exports = {
if (mode === "global") { if (mode === "global") {
if (node.body.length > 0 && useStrictDirectives.length === 0) { if (node.body.length > 0 && useStrictDirectives.length === 0) {
context.report({ node, message: messages.global }); context.report({ node, messageId: "global" });
} }
reportAllExceptFirst(useStrictDirectives, messages.multiple, true); reportAllExceptFirst(useStrictDirectives, "multiple", true);
} else { } else {
reportAll(useStrictDirectives, messages[mode], shouldFix(mode)); reportAll(useStrictDirectives, mode, shouldFix(mode));
} }
}, },
FunctionDeclaration: enterFunction, FunctionDeclaration: enterFunction,

View File

@ -36,8 +36,13 @@ module.exports = {
additionalProperties: false additionalProperties: false
} }
], ],
fixable: "whitespace",
fixable: "whitespace" messages: {
expectedBefore: "Expected space(s) before this colon.",
expectedAfter: "Expected space(s) after this colon.",
unexpectedBefore: "Unexpected space(s) before this colon.",
unexpectedAfter: "Unexpected space(s) after this colon."
}
}, },
create(context) { create(context) {
@ -118,8 +123,7 @@ module.exports = {
context.report({ context.report({
node, node,
loc: colonToken.loc, loc: colonToken.loc,
message: "{{verb}} space(s) before this colon.", messageId: beforeSpacing ? "expectedBefore" : "unexpectedBefore",
data: { verb: beforeSpacing ? "Expected" : "Unexpected" },
fix: fixer => fix(fixer, beforeToken, colonToken, beforeSpacing) fix: fixer => fix(fixer, beforeToken, colonToken, beforeSpacing)
}); });
} }
@ -127,8 +131,7 @@ module.exports = {
context.report({ context.report({
node, node,
loc: colonToken.loc, loc: colonToken.loc,
message: "{{verb}} space(s) after this colon.", messageId: afterSpacing ? "expectedAfter" : "unexpectedAfter",
data: { verb: afterSpacing ? "Expected" : "Unexpected" },
fix: fixer => fix(fixer, colonToken, afterToken, afterSpacing) fix: fixer => fix(fixer, colonToken, afterToken, afterSpacing)
}); });
} }

View File

@ -26,8 +26,11 @@ module.exports = {
recommended: false, recommended: false,
url: "https://eslint.org/docs/rules/symbol-description" url: "https://eslint.org/docs/rules/symbol-description"
}, },
fixable: null,
schema: [] schema: [],
messages: {
expected: "Expected Symbol to have a description."
}
}, },
create(context) { create(context) {
@ -43,7 +46,7 @@ module.exports = {
if (node.arguments.length === 0) { if (node.arguments.length === 0) {
context.report({ context.report({
node, node,
message: "Expected Symbol to have a description." messageId: "expected"
}); });
} }
} }

View File

@ -37,13 +37,19 @@ module.exports = {
schema: [ schema: [
{ enum: ["always", "never"] } { enum: ["always", "never"] }
] ],
messages: {
expectedBefore: "Expected space(s) before '}'.",
expectedAfter: "Expected space(s) after '${'.",
unexpectedBefore: "Unexpected space(s) before '}'.",
unexpectedAfter: "Unexpected space(s) after '${'."
}
}, },
create(context) { create(context) {
const sourceCode = context.getSourceCode(); const sourceCode = context.getSourceCode();
const always = context.options[0] === "always"; const always = context.options[0] === "always";
const prefix = always ? "Expected" : "Unexpected"; const prefix = always ? "expected" : "unexpected";
/** /**
* Checks spacing before `}` of a given token. * Checks spacing before `}` of a given token.
@ -60,10 +66,7 @@ module.exports = {
) { ) {
context.report({ context.report({
loc: token.loc.start, loc: token.loc.start,
message: "{{prefix}} space(s) before '}'.", messageId: `${prefix}Before`,
data: {
prefix
},
fix(fixer) { fix(fixer) {
if (always) { if (always) {
return fixer.insertTextBefore(token, " "); return fixer.insertTextBefore(token, " ");
@ -95,10 +98,7 @@ module.exports = {
line: token.loc.end.line, line: token.loc.end.line,
column: token.loc.end.column - 2 column: token.loc.end.column - 2
}, },
message: "{{prefix}} space(s) after '${'.", messageId: `${prefix}After`,
data: {
prefix
},
fix(fixer) { fix(fixer) {
if (always) { if (always) {
return fixer.insertTextAfter(token, " "); return fixer.insertTextAfter(token, " ");

View File

@ -24,7 +24,11 @@ module.exports = {
schema: [ schema: [
{ enum: ["always", "never"] } { enum: ["always", "never"] }
] ],
messages: {
unexpected: "Unexpected space between template tag and template literal.",
missing: "Missing space between template tag and template literal."
}
}, },
create(context) { create(context) {
@ -46,7 +50,7 @@ module.exports = {
context.report({ context.report({
node, node,
loc: tagToken.loc.start, loc: tagToken.loc.start,
message: "Unexpected space between template tag and template literal.", messageId: "unexpected",
fix(fixer) { fix(fixer) {
const comments = sourceCode.getCommentsBefore(node.quasi); const comments = sourceCode.getCommentsBefore(node.quasi);
@ -65,7 +69,7 @@ module.exports = {
context.report({ context.report({
node, node,
loc: tagToken.loc.start, loc: tagToken.loc.start,
message: "Missing space between template tag and template literal.", messageId: "missing",
fix(fixer) { fix(fixer) {
return fixer.insertTextAfter(tagToken, " "); return fixer.insertTextAfter(tagToken, " ");
} }

View File

@ -25,7 +25,11 @@ module.exports = {
{ {
enum: ["always", "never"] enum: ["always", "never"]
} }
] ],
messages: {
expected: "Expected Unicode BOM (Byte Order Mark).",
unexpected: "Unexpected Unicode BOM (Byte Order Mark)."
}
}, },
create(context) { create(context) {
@ -46,7 +50,7 @@ module.exports = {
context.report({ context.report({
node, node,
loc: location, loc: location,
message: "Expected Unicode BOM (Byte Order Mark).", messageId: "expected",
fix(fixer) { fix(fixer) {
return fixer.insertTextBeforeRange([0, 1], "\uFEFF"); return fixer.insertTextBeforeRange([0, 1], "\uFEFF");
} }
@ -55,7 +59,7 @@ module.exports = {
context.report({ context.report({
node, node,
loc: location, loc: location,
message: "Unexpected Unicode BOM (Byte Order Mark).", messageId: "unexpected",
fix(fixer) { fix(fixer) {
return fixer.removeRange([-1, 0]); return fixer.removeRange([-1, 0]);
} }

View File

@ -20,7 +20,10 @@ module.exports = {
url: "https://eslint.org/docs/rules/use-isnan" url: "https://eslint.org/docs/rules/use-isnan"
}, },
schema: [] schema: [],
messages: {
useIsNaN: "Use the isNaN function to compare with NaN."
}
}, },
create(context) { create(context) {
@ -28,7 +31,7 @@ module.exports = {
return { return {
BinaryExpression(node) { BinaryExpression(node) {
if (/^(?:[<>]|[!=]=)=?$/.test(node.operator) && (node.left.name === "NaN" || node.right.name === "NaN")) { if (/^(?:[<>]|[!=]=)=?$/.test(node.operator) && (node.left.name === "NaN" || node.right.name === "NaN")) {
context.report({ node, message: "Use the isNaN function to compare with NaN." }); context.report({ node, messageId: "useIsNaN" });
} }
} }
}; };

View File

@ -65,6 +65,22 @@ module.exports = {
], ],
fixable: "code", fixable: "code",
messages: {
unexpectedTag: "Unexpected @{{title}} tag; function has no return statement.",
expected: "Expected JSDoc for '{{name}}' but found '{{jsdocName}}'.",
use: "Use @{{name}} instead.",
useType: "Use '{{expectedTypeName}}' instead of '{{currentTypeName}}'.",
syntaxError: "JSDoc syntax error.",
missingBrace: "JSDoc type missing brace.",
missingParamDesc: "Missing JSDoc parameter description for '{{name}}'.",
missingParamType: "Missing JSDoc parameter type for '{{name}}'.",
missingReturnType: "Missing JSDoc return type.",
missingReturnDesc: "Missing JSDoc return description.",
missingReturn: "Missing JSDoc @{{returns}} for function.",
missingParam: "Missing JSDoc for parameter '{{name}}'.",
duplicateParam: "Duplicate JSDoc parameter '{{name}}'.",
unsatisfiedDesc: "JSDoc description does not satisfy the regex pattern."
},
deprecated: true, deprecated: true,
replacedBy: [] replacedBy: []
@ -231,7 +247,7 @@ module.exports = {
typeToCheck.expectedTypeName !== typeToCheck.currentType.name) { typeToCheck.expectedTypeName !== typeToCheck.currentType.name) {
context.report({ context.report({
node: jsdocNode, node: jsdocNode,
message: "Use '{{expectedTypeName}}' instead of '{{currentTypeName}}'.", messageId: "useType",
loc: getAbsoluteRange(jsdocNode, typeToCheck.currentType), loc: getAbsoluteRange(jsdocNode, typeToCheck.currentType),
data: { data: {
currentTypeName: typeToCheck.currentType.name, currentTypeName: typeToCheck.currentType.name,
@ -280,9 +296,9 @@ module.exports = {
} catch (ex) { } catch (ex) {
if (/braces/i.test(ex.message)) { if (/braces/i.test(ex.message)) {
context.report({ node: jsdocNode, message: "JSDoc type missing brace." }); context.report({ node: jsdocNode, messageId: "missingBrace" });
} else { } else {
context.report({ node: jsdocNode, message: "JSDoc syntax error." }); context.report({ node: jsdocNode, messageId: "syntaxError" });
} }
return; return;
@ -332,7 +348,7 @@ module.exports = {
context.report({ context.report({
node: jsdocNode, node: jsdocNode,
message: "Use @{{name}} instead.", messageId: "use",
loc: { loc: {
start: entireTagRange.start, start: entireTagRange.start,
end: { end: {
@ -363,7 +379,7 @@ module.exports = {
if (requireParamType && !param.type) { if (requireParamType && !param.type) {
context.report({ context.report({
node: jsdocNode, node: jsdocNode,
message: "Missing JSDoc parameter type for '{{name}}'.", messageId: "missingParamType",
loc: getAbsoluteRange(jsdocNode, param), loc: getAbsoluteRange(jsdocNode, param),
data: { name: param.name } data: { name: param.name }
}); });
@ -371,7 +387,7 @@ module.exports = {
if (!param.description && requireParamDescription) { if (!param.description && requireParamDescription) {
context.report({ context.report({
node: jsdocNode, node: jsdocNode,
message: "Missing JSDoc parameter description for '{{name}}'.", messageId: "missingParamDesc",
loc: getAbsoluteRange(jsdocNode, param), loc: getAbsoluteRange(jsdocNode, param),
data: { name: param.name } data: { name: param.name }
}); });
@ -379,7 +395,7 @@ module.exports = {
if (paramTagsByName[param.name]) { if (paramTagsByName[param.name]) {
context.report({ context.report({
node: jsdocNode, node: jsdocNode,
message: "Duplicate JSDoc parameter '{{name}}'.", messageId: "duplicateParam",
loc: getAbsoluteRange(jsdocNode, param), loc: getAbsoluteRange(jsdocNode, param),
data: { name: param.name } data: { name: param.name }
}); });
@ -392,7 +408,7 @@ module.exports = {
if (!requireReturn && !functionData.returnPresent && (returnsTag.type === null || !isValidReturnType(returnsTag)) && !isAbstract) { if (!requireReturn && !functionData.returnPresent && (returnsTag.type === null || !isValidReturnType(returnsTag)) && !isAbstract) {
context.report({ context.report({
node: jsdocNode, node: jsdocNode,
message: "Unexpected @{{title}} tag; function has no return statement.", messageId: "unexpectedTag",
loc: getAbsoluteRange(jsdocNode, returnsTag), loc: getAbsoluteRange(jsdocNode, returnsTag),
data: { data: {
title: returnsTag.title title: returnsTag.title
@ -400,11 +416,11 @@ module.exports = {
}); });
} else { } else {
if (requireReturnType && !returnsTag.type) { if (requireReturnType && !returnsTag.type) {
context.report({ node: jsdocNode, message: "Missing JSDoc return type." }); context.report({ node: jsdocNode, messageId: "missingReturnType" });
} }
if (!isValidReturnType(returnsTag) && !returnsTag.description && requireReturnDescription) { if (!isValidReturnType(returnsTag) && !returnsTag.description && requireReturnDescription) {
context.report({ node: jsdocNode, message: "Missing JSDoc return description." }); context.report({ node: jsdocNode, messageId: "missingReturnDesc" });
} }
} }
} }
@ -416,7 +432,7 @@ module.exports = {
if (requireReturn || (functionData.returnPresent && !node.async)) { if (requireReturn || (functionData.returnPresent && !node.async)) {
context.report({ context.report({
node: jsdocNode, node: jsdocNode,
message: "Missing JSDoc @{{returns}} for function.", messageId: "missingReturn",
data: { data: {
returns: prefer.returns || "returns" returns: prefer.returns || "returns"
} }
@ -440,7 +456,7 @@ module.exports = {
if (jsdocParamNames[paramsIndex] && (name !== jsdocParamNames[paramsIndex])) { if (jsdocParamNames[paramsIndex] && (name !== jsdocParamNames[paramsIndex])) {
context.report({ context.report({
node: jsdocNode, node: jsdocNode,
message: "Expected JSDoc for '{{name}}' but found '{{jsdocName}}'.", messageId: "expected",
loc: getAbsoluteRange(jsdocNode, paramTagsByName[jsdocParamNames[paramsIndex]]), loc: getAbsoluteRange(jsdocNode, paramTagsByName[jsdocParamNames[paramsIndex]]),
data: { data: {
name, name,
@ -450,7 +466,7 @@ module.exports = {
} else if (!paramTagsByName[name] && !isOverride) { } else if (!paramTagsByName[name] && !isOverride) {
context.report({ context.report({
node: jsdocNode, node: jsdocNode,
message: "Missing JSDoc for parameter '{{name}}'.", messageId: "missingParam",
data: { data: {
name name
} }
@ -464,7 +480,7 @@ module.exports = {
const regex = new RegExp(options.matchDescription); const regex = new RegExp(options.matchDescription);
if (!regex.test(jsdoc.description)) { if (!regex.test(jsdoc.description)) {
context.report({ node: jsdocNode, message: "JSDoc description does not satisfy the regex pattern." }); context.report({ node: jsdocNode, messageId: "unsatisfiedDesc" });
} }
} }

View File

@ -29,7 +29,11 @@ module.exports = {
}, },
additionalProperties: false additionalProperties: false
} }
] ],
messages: {
invalidValue: "Invalid typeof comparison value.",
notString: "Typeof comparisons should be to string literals."
}
}, },
create(context) { create(context) {
@ -65,10 +69,10 @@ module.exports = {
const value = sibling.type === "Literal" ? sibling.value : sibling.quasis[0].value.cooked; const value = sibling.type === "Literal" ? sibling.value : sibling.quasis[0].value.cooked;
if (VALID_TYPES.indexOf(value) === -1) { if (VALID_TYPES.indexOf(value) === -1) {
context.report({ node: sibling, message: "Invalid typeof comparison value." }); context.report({ node: sibling, messageId: "invalidValue" });
} }
} else if (requireStringLiterals && !isTypeofExpression(sibling)) { } else if (requireStringLiterals && !isTypeofExpression(sibling)) {
context.report({ node: sibling, message: "Typeof comparisons should be to string literals." }); context.report({ node: sibling, messageId: "notString" });
} }
} }
} }

View File

@ -20,11 +20,13 @@ module.exports = {
url: "https://eslint.org/docs/rules/vars-on-top" url: "https://eslint.org/docs/rules/vars-on-top"
}, },
schema: [] schema: [],
messages: {
top: "All 'var' declarations must be at the top of the function scope."
}
}, },
create(context) { create(context) {
const errorMessage = "All 'var' declarations must be at the top of the function scope.";
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
// Helpers // Helpers
@ -103,7 +105,7 @@ module.exports = {
*/ */
function globalVarCheck(node, parent) { function globalVarCheck(node, parent) {
if (!isVarOnTop(node, parent.body)) { if (!isVarOnTop(node, parent.body)) {
context.report({ node, message: errorMessage }); context.report({ node, messageId: "top" });
} }
} }
@ -118,7 +120,7 @@ module.exports = {
if (!(/Function/.test(grandParent.type) && if (!(/Function/.test(grandParent.type) &&
parent.type === "BlockStatement" && parent.type === "BlockStatement" &&
isVarOnTop(node, parent.body))) { isVarOnTop(node, parent.body))) {
context.report({ node, message: errorMessage }); context.report({ node, messageId: "top" });
} }
} }

View File

@ -41,7 +41,12 @@ module.exports = {
} }
], ],
fixable: "code" fixable: "code",
messages: {
wrapInvocation: "Wrap an immediate function invocation in parentheses.",
wrapExpression: "Wrap only the function expression in parens.",
moveInvocation: "Move the invocation into the parens that contain the function."
}
}, },
create(context) { create(context) {
@ -99,7 +104,7 @@ module.exports = {
if (!callExpressionWrapped && !functionExpressionWrapped) { if (!callExpressionWrapped && !functionExpressionWrapped) {
context.report({ context.report({
node, node,
message: "Wrap an immediate function invocation in parentheses.", messageId: "wrapInvocation",
fix(fixer) { fix(fixer) {
const nodeToSurround = style === "inside" ? innerNode : node; const nodeToSurround = style === "inside" ? innerNode : node;
@ -109,7 +114,7 @@ module.exports = {
} else if (style === "inside" && !functionExpressionWrapped) { } else if (style === "inside" && !functionExpressionWrapped) {
context.report({ context.report({
node, node,
message: "Wrap only the function expression in parens.", messageId: "wrapExpression",
fix(fixer) { fix(fixer) {
/* /*
@ -129,7 +134,7 @@ module.exports = {
} else if (style === "outside" && !callExpressionWrapped) { } else if (style === "outside" && !callExpressionWrapped) {
context.report({ context.report({
node, node,
message: "Move the invocation into the parens that contain the function.", messageId: "moveInvocation",
fix(fixer) { fix(fixer) {
/* /*

View File

@ -38,7 +38,13 @@ module.exports = {
} }
] ]
} }
] ],
messages: {
missingBefore: "Missing space before *.",
missingAfter: "Missing space after *.",
unexpectedBefore: "Unexpected space before *.",
unexpectedAfter: "Unexpected space after *."
}
}, },
create(context) { create(context) {
@ -70,16 +76,17 @@ module.exports = {
const after = leftToken.value === "*"; const after = leftToken.value === "*";
const spaceRequired = mode[side]; const spaceRequired = mode[side];
const node = after ? leftToken : rightToken; const node = after ? leftToken : rightToken;
const type = spaceRequired ? "Missing" : "Unexpected"; let messageId = "";
const message = "{{type}} space {{side}} *.";
if (spaceRequired) {
messageId = side === "before" ? "missingBefore" : "missingAfter";
} else {
messageId = side === "before" ? "unexpectedBefore" : "unexpectedAfter";
}
context.report({ context.report({
node, node,
message, messageId,
data: {
type,
side
},
fix(fixer) { fix(fixer) {
if (spaceRequired) { if (spaceRequired) {
if (after) { if (after) {

View File

@ -179,7 +179,10 @@ module.exports = {
} }
], ],
fixable: "code" fixable: "code",
messages: {
expected: "Expected literal to be on the {{expectedSide}} side of {{operator}}."
}
}, },
create(context) { create(context) {
@ -297,7 +300,7 @@ module.exports = {
) { ) {
context.report({ context.report({
node, node,
message: "Expected literal to be on the {{expectedSide}} side of {{operator}}.", messageId: "expected",
data: { data: {
operator: node.operator, operator: node.operator,
expectedSide: always ? "left" : "right" expectedSide: always ? "left" : "right"

View File

@ -63,7 +63,7 @@ ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
- [Validation errors](#validation-errors) - [Validation errors](#validation-errors)
- [Plugins](#plugins) - [Plugins](#plugins)
- [Related packages](#related-packages) - [Related packages](#related-packages)
- [Packages using Ajv](#some-packages-using-ajv) - [Some packages using Ajv](#some-packages-using-ajv)
- [Tests, Contributing, History, License](#tests) - [Tests, Contributing, History, License](#tests)
@ -699,13 +699,11 @@ The schema above is also more efficient - it will compile into a faster function
With [option `useDefaults`](#options) Ajv will assign values from `default` keyword in the schemas of `properties` and `items` (when it is the array of schemas) to the missing properties and items. With [option `useDefaults`](#options) Ajv will assign values from `default` keyword in the schemas of `properties` and `items` (when it is the array of schemas) to the missing properties and items.
With the option value `"empty"` properties and items equal to `null` or `""` (empty string) will be considered missing and assigned defaults.
This option modifies original data. This option modifies original data.
__Please note__: by default the default value is inserted in the generated validation code as a literal (starting from v4.0), so the value inserted in the data will be the deep clone of the default in the schema. __Please note__: the default value is inserted in the generated validation code as a literal, so the value inserted in the data will be the deep clone of the default in the schema.
If you need to insert the default value in the data by reference pass the option `useDefaults: "shared"`.
Inserting defaults by reference can be faster (in case you have an object in `default`) and it allows to have dynamic values in defaults, e.g. timestamp, without recompiling the schema. The side effect is that modifying the default value in any validated data instance will change the default in the schema and in other validated data instances. See example 3 below.
Example 1 (`default` in `properties`): Example 1 (`default` in `properties`):
@ -748,32 +746,6 @@ console.log(validate(data)); // true
console.log(data); // [ 1, "foo" ] console.log(data); // [ 1, "foo" ]
``` ```
Example 3 (inserting "defaults" by reference):
```javascript
var ajv = new Ajv({ useDefaults: 'shared' });
var schema = {
properties: {
foo: {
default: { bar: 1 }
}
}
}
var validate = ajv.compile(schema);
var data = {};
console.log(validate(data)); // true
console.log(data); // { foo: { bar: 1 } }
data.foo.bar = 2;
var data2 = {};
console.log(validate(data2)); // true
console.log(data2); // { foo: { bar: 2 } }
```
`default` keywords in other cases are ignored: `default` keywords in other cases are ignored:
- not in `properties` or `items` subschemas - not in `properties` or `items` subschemas
@ -1115,8 +1087,9 @@ Defaults:
- `"failing"` - additional properties that fail schema validation will be removed (where `additionalProperties` keyword is `false` or schema). - `"failing"` - additional properties that fail schema validation will be removed (where `additionalProperties` keyword is `false` or schema).
- _useDefaults_: replace missing properties and items with the values from corresponding `default` keywords. Default behaviour is to ignore `default` keywords. This option is not used if schema is added with `addMetaSchema` method. See examples in [Assigning defaults](#assigning-defaults). Option values: - _useDefaults_: replace missing properties and items with the values from corresponding `default` keywords. Default behaviour is to ignore `default` keywords. This option is not used if schema is added with `addMetaSchema` method. See examples in [Assigning defaults](#assigning-defaults). Option values:
- `false` (default) - do not use defaults - `false` (default) - do not use defaults
- `true` - insert defaults by value (safer and slower, object literal is used). - `true` - insert defaults by value (object literal is used).
- `"shared"` - insert defaults by reference (faster). If the default is an object, it will be shared by all instances of validated data. If you modify the inserted default in the validated data, it will be modified in the schema as well. - `"empty"` - use defaults for properties and items that are present and equal to `null` or `""` (an empty string).
- `"shared"` (deprecated) - insert defaults by reference. If the default is an object, it will be shared by all instances of validated data. If you modify the inserted default in the validated data, it will be modified in the schema as well.
- _coerceTypes_: change data type of data to match `type` keyword. See the example in [Coercing data types](#coercing-data-types) and [coercion rules](https://github.com/epoberezkin/ajv/blob/master/COERCION.md). Option values: - _coerceTypes_: change data type of data to match `type` keyword. See the example in [Coercing data types](#coercing-data-types) and [coercion rules](https://github.com/epoberezkin/ajv/blob/master/COERCION.md). Option values:
- `false` (default) - no type coercion. - `false` (default) - no type coercion.
- `true` - coerce scalar data types. - `true` - coerce scalar data types.
@ -1228,7 +1201,7 @@ If you have published a useful plugin please submit a PR to add it to the next s
- [ajv-errors](https://github.com/epoberezkin/ajv-errors) - plugin for custom error messages - [ajv-errors](https://github.com/epoberezkin/ajv-errors) - plugin for custom error messages
- [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) - internationalised error messages - [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) - internationalised error messages
- [ajv-istanbul](https://github.com/epoberezkin/ajv-istanbul) - plugin to instrument generated validation code to measure test coverage of your schemas - [ajv-istanbul](https://github.com/epoberezkin/ajv-istanbul) - plugin to instrument generated validation code to measure test coverage of your schemas
- [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) - plugin with custom validation keywords (if/then/else, select, typeof, etc.) - [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) - plugin with custom validation keywords (select, typeof, etc.)
- [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) - plugin with keywords $merge and $patch - [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) - plugin with keywords $merge and $patch
- [ajv-pack](https://github.com/epoberezkin/ajv-pack) - produces a compact module exporting validation functions - [ajv-pack](https://github.com/epoberezkin/ajv-pack) - produces a compact module exporting validation functions

View File

@ -1434,7 +1434,8 @@ module.exports = function generate__limit(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -1520,7 +1521,8 @@ module.exports = function generate__limit(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -1598,7 +1600,8 @@ module.exports = function generate__limitItems(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -1681,7 +1684,8 @@ module.exports = function generate__limitLength(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -1759,7 +1763,8 @@ module.exports = function generate__limitProperties(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -1875,7 +1880,8 @@ module.exports = function generate_anyOf(it, $keyword, $ruleType) {
out += ' {} '; out += ' {} ';
} }
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError(vErrors); '; out += ' throw new ValidationError(vErrors); ';
} else { } else {
@ -1952,7 +1958,8 @@ module.exports = function generate_const(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -2031,7 +2038,8 @@ module.exports = function generate_contains(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -2207,7 +2215,8 @@ module.exports = function generate_custom(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -2253,7 +2262,8 @@ module.exports = function generate_custom(it, $keyword, $ruleType) {
out += ' {} '; out += ' {} ';
} }
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError(vErrors); '; out += ' throw new ValidationError(vErrors); ';
} else { } else {
@ -2362,7 +2372,8 @@ module.exports = function generate_dependencies(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -2499,7 +2510,8 @@ module.exports = function generate_enum(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -2650,7 +2662,8 @@ module.exports = function generate_format(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -2751,7 +2764,8 @@ module.exports = function generate_if(it, $keyword, $ruleType) {
out += ' {} '; out += ' {} ';
} }
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError(vErrors); '; out += ' throw new ValidationError(vErrors); ';
} else { } else {
@ -2852,7 +2866,8 @@ module.exports = function generate_items(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -3010,7 +3025,8 @@ module.exports = function generate_multipleOf(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -3076,7 +3092,8 @@ module.exports = function generate_not(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -3171,7 +3188,8 @@ module.exports = function generate_oneOf(it, $keyword, $ruleType) {
out += ' {} '; out += ' {} ';
} }
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError(vErrors); '; out += ' throw new ValidationError(vErrors); ';
} else { } else {
@ -3245,7 +3263,8 @@ module.exports = function generate_pattern(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -3373,7 +3392,8 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -3503,7 +3523,8 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -3655,7 +3676,8 @@ module.exports = function generate_propertyNames(it, $keyword, $ruleType) {
out += ' {} '; out += ' {} ';
} }
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError(vErrors); '; out += ' throw new ValidationError(vErrors); ';
} else { } else {
@ -3717,7 +3739,8 @@ module.exports = function generate_ref(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -3891,7 +3914,8 @@ module.exports = function generate_required(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -3950,7 +3974,8 @@ module.exports = function generate_required(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -4135,7 +4160,8 @@ module.exports = function generate_uniqueItems(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -4208,7 +4234,8 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -4364,7 +4391,8 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -4411,7 +4439,8 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -4460,7 +4489,11 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
var $sch = $schema[$propertyKey]; var $sch = $schema[$propertyKey];
if ($sch.default !== undefined) { if ($sch.default !== undefined) {
var $passData = $data + it.util.getProperty($propertyKey); var $passData = $data + it.util.getProperty($propertyKey);
out += ' if (' + ($passData) + ' === undefined) ' + ($passData) + ' = '; out += ' if (' + ($passData) + ' === undefined ';
if (it.opts.useDefaults == 'empty') {
out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
}
out += ' ) ' + ($passData) + ' = ';
if (it.opts.useDefaults == 'shared') { if (it.opts.useDefaults == 'shared') {
out += ' ' + (it.useDefault($sch.default)) + ' '; out += ' ' + (it.useDefault($sch.default)) + ' ';
} else { } else {
@ -4479,7 +4512,11 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
$sch = arr4[$i += 1]; $sch = arr4[$i += 1];
if ($sch.default !== undefined) { if ($sch.default !== undefined) {
var $passData = $data + '[' + $i + ']'; var $passData = $data + '[' + $i + ']';
out += ' if (' + ($passData) + ' === undefined) ' + ($passData) + ' = '; out += ' if (' + ($passData) + ' === undefined ';
if (it.opts.useDefaults == 'empty') {
out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
}
out += ' ) ' + ($passData) + ' = ';
if (it.opts.useDefaults == 'shared') { if (it.opts.useDefaults == 'shared') {
out += ' ' + (it.useDefault($sch.default)) + ' '; out += ' ' + (it.useDefault($sch.default)) + ' ';
} else { } else {
@ -4547,7 +4584,8 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,12 +1,36 @@
declare var ajv: { declare var ajv: {
(options?: ajv.Options): ajv.Ajv; (options?: ajv.Options): ajv.Ajv;
new (options?: ajv.Options): ajv.Ajv; new(options?: ajv.Options): ajv.Ajv;
ValidationError: ValidationError; ValidationError: typeof AjvErrors.ValidationError;
MissingRefError: MissingRefError; MissingRefError: typeof AjvErrors.MissingRefError;
$dataMetaSchema: object; $dataMetaSchema: object;
} }
declare namespace AjvErrors {
class ValidationError extends Error {
constructor(errors: Array<ajv.ErrorObject>);
message: string;
errors: Array<ajv.ErrorObject>;
ajv: true;
validation: true;
}
class MissingRefError extends Error {
constructor(baseId: string, ref: string, message?: string);
static message: (baseId: string, ref: string) => string;
message: string;
missingRef: string;
missingSchema: string;
}
}
declare namespace ajv { declare namespace ajv {
type ValidationError = AjvErrors.ValidationError;
type MissingRefError = AjvErrors.MissingRefError;
interface Ajv { interface Ajv {
/** /**
* Validate data using schema * Validate data using schema
@ -268,11 +292,11 @@ declare namespace ajv {
} }
type ErrorParameters = RefParams | LimitParams | AdditionalPropertiesParams | type ErrorParameters = RefParams | LimitParams | AdditionalPropertiesParams |
DependenciesParams | FormatParams | ComparisonParams | DependenciesParams | FormatParams | ComparisonParams |
MultipleOfParams | PatternParams | RequiredParams | MultipleOfParams | PatternParams | RequiredParams |
TypeParams | UniqueItemsParams | CustomParams | TypeParams | UniqueItemsParams | CustomParams |
PatternRequiredParams | PropertyNamesParams | PatternRequiredParams | PropertyNamesParams |
IfParams | SwitchParams | NoParams | EnumParams; IfParams | SwitchParams | NoParams | EnumParams;
interface RefParams { interface RefParams {
ref: string; ref: string;
@ -344,29 +368,11 @@ declare namespace ajv {
caseIndex: number; caseIndex: number;
} }
interface NoParams {} interface NoParams { }
interface EnumParams { interface EnumParams {
allowedValues: Array<any>; allowedValues: Array<any>;
} }
} }
declare class ValidationError extends Error {
constructor(errors: Array<ajv.ErrorObject>);
message: string;
errors: Array<ajv.ErrorObject>;
ajv: true;
validation: true;
}
declare class MissingRefError extends Error {
constructor(baseId: string, ref: string, message?: string);
static message: (baseId: string, ref: string) => string;
message: string;
missingRef: string;
missingSchema: string;
}
export = ajv; export = ajv;

View File

@ -1,3 +1,5 @@
'use strict'; 'use strict';
// do NOT remove this file - it would break pre-compiled schemas
// https://github.com/epoberezkin/ajv/issues/889
module.exports = require('fast-deep-equal'); module.exports = require('fast-deep-equal');

View File

@ -1,5 +1,10 @@
{{## def.assignDefault: {{## def.assignDefault:
if ({{=$passData}} === undefined) if ({{=$passData}} === undefined
{{? it.opts.useDefaults == 'empty' }}
|| {{=$passData}} === null
|| {{=$passData}} === ''
{{?}}
)
{{=$passData}} = {{? it.opts.useDefaults == 'shared' }} {{=$passData}} = {{? it.opts.useDefaults == 'shared' }}
{{= it.useDefault($sch.default) }} {{= it.useDefault($sch.default) }}
{{??}} {{??}}

View File

@ -52,7 +52,8 @@ module.exports = function generate__limit(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -138,7 +139,8 @@ module.exports = function generate__limit(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

@ -59,7 +59,8 @@ module.exports = function generate__limitItems(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

@ -64,7 +64,8 @@ module.exports = function generate__limitLength(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

@ -59,7 +59,8 @@ module.exports = function generate__limitProperties(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

@ -52,7 +52,8 @@ module.exports = function generate_anyOf(it, $keyword, $ruleType) {
out += ' {} '; out += ' {} ';
} }
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError(vErrors); '; out += ' throw new ValidationError(vErrors); ';
} else { } else {

View File

@ -38,7 +38,8 @@ module.exports = function generate_const(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

@ -60,7 +60,8 @@ module.exports = function generate_contains(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

@ -153,7 +153,8 @@ module.exports = function generate_custom(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -199,7 +200,8 @@ module.exports = function generate_custom(it, $keyword, $ruleType) {
out += ' {} '; out += ' {} ';
} }
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError(vErrors); '; out += ' throw new ValidationError(vErrors); ';
} else { } else {

View File

@ -80,7 +80,8 @@ module.exports = function generate_dependencies(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

@ -48,7 +48,8 @@ module.exports = function generate_enum(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

@ -132,7 +132,8 @@ module.exports = function generate_format(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

@ -82,7 +82,8 @@ module.exports = function generate_if(it, $keyword, $ruleType) {
out += ' {} '; out += ' {} ';
} }
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError(vErrors); '; out += ' throw new ValidationError(vErrors); ';
} else { } else {

View File

@ -43,7 +43,8 @@ module.exports = function generate_items(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

@ -59,7 +59,8 @@ module.exports = function generate_multipleOf(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

@ -47,7 +47,8 @@ module.exports = function generate_not(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

@ -57,7 +57,8 @@ module.exports = function generate_oneOf(it, $keyword, $ruleType) {
out += ' {} '; out += ' {} ';
} }
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError(vErrors); '; out += ' throw new ValidationError(vErrors); ';
} else { } else {

View File

@ -57,7 +57,8 @@ module.exports = function generate_pattern(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

@ -109,7 +109,8 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -239,7 +240,8 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

@ -61,7 +61,8 @@ module.exports = function generate_propertyNames(it, $keyword, $ruleType) {
out += ' {} '; out += ' {} ';
} }
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError(vErrors); '; out += ' throw new ValidationError(vErrors); ';
} else { } else {

View File

@ -40,7 +40,8 @@ module.exports = function generate_ref(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

@ -89,7 +89,8 @@ module.exports = function generate_required(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -148,7 +149,8 @@ module.exports = function generate_required(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

@ -63,7 +63,8 @@ module.exports = function generate_uniqueItems(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

@ -49,7 +49,8 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -205,7 +206,8 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -252,7 +254,8 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -301,7 +304,11 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
var $sch = $schema[$propertyKey]; var $sch = $schema[$propertyKey];
if ($sch.default !== undefined) { if ($sch.default !== undefined) {
var $passData = $data + it.util.getProperty($propertyKey); var $passData = $data + it.util.getProperty($propertyKey);
out += ' if (' + ($passData) + ' === undefined) ' + ($passData) + ' = '; out += ' if (' + ($passData) + ' === undefined ';
if (it.opts.useDefaults == 'empty') {
out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
}
out += ' ) ' + ($passData) + ' = ';
if (it.opts.useDefaults == 'shared') { if (it.opts.useDefaults == 'shared') {
out += ' ' + (it.useDefault($sch.default)) + ' '; out += ' ' + (it.useDefault($sch.default)) + ' ';
} else { } else {
@ -320,7 +327,11 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
$sch = arr4[$i += 1]; $sch = arr4[$i += 1];
if ($sch.default !== undefined) { if ($sch.default !== undefined) {
var $passData = $data + '[' + $i + ']'; var $passData = $data + '[' + $i + ']';
out += ' if (' + ($passData) + ' === undefined) ' + ($passData) + ' = '; out += ' if (' + ($passData) + ' === undefined ';
if (it.opts.useDefaults == 'empty') {
out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
}
out += ' ) ' + ($passData) + ' = ';
if (it.opts.useDefaults == 'shared') { if (it.opts.useDefaults == 'shared') {
out += ' ' + (it.useDefault($sch.default)) + ' '; out += ' ' + (it.useDefault($sch.default)) + ' ';
} else { } else {
@ -388,7 +399,8 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

@ -91,10 +91,10 @@
"test-fast": "AJV_FAST_TEST=true npm run test-spec", "test-fast": "AJV_FAST_TEST=true npm run test-spec",
"test-karma": "karma start", "test-karma": "karma start",
"test-spec": "mocha spec/*.spec.js -R spec", "test-spec": "mocha spec/*.spec.js -R spec",
"test-ts": "tsc --target ES5 --noImplicitAny lib/ajv.d.ts", "test-ts": "tsc --target ES5 --noImplicitAny --noEmit spec/typescript/index.ts",
"watch": "watch 'npm run build' ./lib/dot" "watch": "watch 'npm run build' ./lib/dot"
}, },
"tonicExampleFilename": ".tonic_example.js", "tonicExampleFilename": ".tonic_example.js",
"typings": "lib/ajv.d.ts", "typings": "lib/ajv.d.ts",
"version": "6.6.2" "version": "6.7.0"
} }

View File

@ -1,4 +1,4 @@
// @flow // @flow strict
type TemplateStringsArray = $ReadOnlyArray<string>; type TemplateStringsArray = $ReadOnlyArray<string>;

View File

@ -67,7 +67,7 @@
"test": "xo && tsc --project types && flow --max-warnings=0 && nyc ava" "test": "xo && tsc --project types && flow --max-warnings=0 && nyc ava"
}, },
"types": "types/index.d.ts", "types": "types/index.d.ts",
"version": "2.4.1", "version": "2.4.2",
"xo": { "xo": {
"envs": [ "envs": [
"node", "node",

View File

@ -485,7 +485,7 @@
"KeyframeEffectReadOnly": false, "KeyframeEffectReadOnly": false,
"length": false, "length": false,
"localStorage": false, "localStorage": false,
"location": false, "location": true,
"Location": false, "Location": false,
"locationbar": false, "locationbar": false,
"matchMedia": false, "matchMedia": false,
@ -931,6 +931,7 @@
"XSLTProcessor": false "XSLTProcessor": false
}, },
"worker": { "worker": {
"addEventListener": false,
"applicationCache": false, "applicationCache": false,
"atob": false, "atob": false,
"Blob": false, "Blob": false,
@ -986,6 +987,7 @@
"postMessage": true, "postMessage": true,
"Promise": false, "Promise": false,
"queueMicrotask": false, "queueMicrotask": false,
"removeEventListener": false,
"Request": false, "Request": false,
"Response": false, "Response": false,
"self": true, "self": true,
@ -1363,25 +1365,99 @@
"Ref": false "Ref": false
}, },
"serviceworker": { "serviceworker": {
"addEventListener": false,
"applicationCache": false,
"atob": false,
"Blob": false,
"BroadcastChannel": false,
"btoa": false,
"Cache": false, "Cache": false,
"caches": false, "caches": false,
"CacheStorage": false, "CacheStorage": false,
"clearInterval": false,
"clearTimeout": false,
"Client": false, "Client": false,
"clients": false, "clients": false,
"Clients": false, "Clients": false,
"close": true,
"console": false,
"ExtendableEvent": false, "ExtendableEvent": false,
"ExtendableMessageEvent": false, "ExtendableMessageEvent": false,
"fetch": false,
"FetchEvent": false, "FetchEvent": false,
"FileReaderSync": false,
"FormData": false,
"Headers": false,
"IDBCursor": false,
"IDBCursorWithValue": false,
"IDBDatabase": false,
"IDBFactory": false,
"IDBIndex": false,
"IDBKeyRange": false,
"IDBObjectStore": false,
"IDBOpenDBRequest": false,
"IDBRequest": false,
"IDBTransaction": false,
"IDBVersionChangeEvent": false,
"ImageData": false,
"importScripts": false, "importScripts": false,
"indexedDB": false,
"location": false,
"MessageChannel": false,
"MessagePort": false,
"name": false,
"navigator": false,
"Notification": false,
"onclose": true,
"onconnect": true,
"onerror": true,
"onfetch": true,
"oninstall": true,
"onlanguagechange": true,
"onmessage": true,
"onmessageerror": true,
"onnotificationclick": true,
"onnotificationclose": true,
"onoffline": true,
"ononline": true,
"onpush": true,
"onpushsubscriptionchange": true,
"onrejectionhandled": true,
"onsync": true,
"onunhandledrejection": true,
"performance": false,
"Performance": false,
"PerformanceEntry": false,
"PerformanceMark": false,
"PerformanceMeasure": false,
"PerformanceNavigation": false,
"PerformanceResourceTiming": false,
"PerformanceTiming": false,
"postMessage": true,
"Promise": false,
"queueMicrotask": false,
"registration": false, "registration": false,
"removeEventListener": false,
"Request": false,
"Response": false,
"self": false, "self": false,
"ServiceWorker": false, "ServiceWorker": false,
"ServiceWorkerContainer": false, "ServiceWorkerContainer": false,
"ServiceWorkerGlobalScope": false, "ServiceWorkerGlobalScope": false,
"ServiceWorkerMessageEvent": false, "ServiceWorkerMessageEvent": false,
"ServiceWorkerRegistration": false, "ServiceWorkerRegistration": false,
"setInterval": false,
"setTimeout": false,
"skipWaiting": false, "skipWaiting": false,
"WindowClient": false "TextDecoder": false,
"TextEncoder": false,
"URL": false,
"URLSearchParams": false,
"WebSocket": false,
"WindowClient": false,
"Worker": false,
"WorkerGlobalScope": false,
"XMLHttpRequest": false
}, },
"atomtest": { "atomtest": {
"advanceClock": false, "advanceClock": false,

View File

@ -41,7 +41,7 @@
"scripts": { "scripts": {
"test": "xo && ava" "test": "xo && ava"
}, },
"version": "11.9.0", "version": "11.10.0",
"xo": { "xo": {
"ignores": [ "ignores": [
"get-browser-globals.js" "get-browser-globals.js"

View File

@ -104,7 +104,7 @@ options:
- `filename` _(default: null)_ - string to be used as a file path in - `filename` _(default: null)_ - string to be used as a file path in
error/warning messages. error/warning messages.
- `onWarning` _(default: null)_ - function to call on warning messages. - `onWarning` _(default: null)_ - function to call on warning messages.
Loader will throw on warnings if this function is not provided. Loader will call this function with an instance of `YAMLException` for each warning.
- `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ - specifies a schema to use. - `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ - specifies a schema to use.
- `FAILSAFE_SCHEMA` - only strings, arrays and plain objects: - `FAILSAFE_SCHEMA` - only strings, arrays and plain objects:
http://www.yaml.org/spec/1.2/spec.html#id2802346 http://www.yaml.org/spec/1.2/spec.html#id2802346
@ -170,6 +170,7 @@ disable exceptions by setting the `skipInvalid` option to `true`.
options: options:
- `indent` _(default: 2)_ - indentation width to use (in spaces). - `indent` _(default: 2)_ - indentation width to use (in spaces).
- `noArrayIndent` _(default: false)_ - when true, will not add an indentation level to array elements
- `skipInvalid` _(default: false)_ - do not throw on invalid types (like function - `skipInvalid` _(default: false)_ - do not throw on invalid types (like function
in the safe schema) and skip pairs and single values with such types. in the safe schema) and skip pairs and single values with such types.
- `flowLevel` (default: -1) - specifies level of nesting, when to switch from - `flowLevel` (default: -1) - specifies level of nesting, when to switch from

View File

@ -1,4 +1,4 @@
/* js-yaml 3.12.0 https://github.com/nodeca/js-yaml */(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.jsyaml = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ /* js-yaml 3.12.1 https://github.com/nodeca/js-yaml */(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.jsyaml = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
'use strict'; 'use strict';
@ -208,16 +208,17 @@ function encodeHex(character) {
} }
function State(options) { function State(options) {
this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;
this.indent = Math.max(1, (options['indent'] || 2)); this.indent = Math.max(1, (options['indent'] || 2));
this.skipInvalid = options['skipInvalid'] || false; this.noArrayIndent = options['noArrayIndent'] || false;
this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); this.skipInvalid = options['skipInvalid'] || false;
this.styleMap = compileStyleMap(this.schema, options['styles'] || null); this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
this.sortKeys = options['sortKeys'] || false; this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
this.lineWidth = options['lineWidth'] || 80; this.sortKeys = options['sortKeys'] || false;
this.noRefs = options['noRefs'] || false; this.lineWidth = options['lineWidth'] || 80;
this.noCompatMode = options['noCompatMode'] || false; this.noRefs = options['noRefs'] || false;
this.condenseFlow = options['condenseFlow'] || false; this.noCompatMode = options['noCompatMode'] || false;
this.condenseFlow = options['condenseFlow'] || false;
this.implicitTypes = this.schema.compiledImplicit; this.implicitTypes = this.schema.compiledImplicit;
this.explicitTypes = this.schema.compiledExplicit; this.explicitTypes = this.schema.compiledExplicit;
@ -837,13 +838,14 @@ function writeNode(state, level, object, block, compact, iskey) {
} }
} }
} else if (type === '[object Array]') { } else if (type === '[object Array]') {
var arrayLevel = (state.noArrayIndent) ? level - 1 : level;
if (block && (state.dump.length !== 0)) { if (block && (state.dump.length !== 0)) {
writeBlockSequence(state, level, state.dump, compact); writeBlockSequence(state, arrayLevel, state.dump, compact);
if (duplicate) { if (duplicate) {
state.dump = '&ref_' + duplicateIndex + state.dump; state.dump = '&ref_' + duplicateIndex + state.dump;
} }
} else { } else {
writeFlowSequence(state, level, state.dump); writeFlowSequence(state, arrayLevel, state.dump);
if (duplicate) { if (duplicate) {
state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
} }

File diff suppressed because one or more lines are too long

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