mirror of
https://github.com/nodejs/node.git
synced 2026-10-28 10:15:07 +08:00
tools: update ESLint to 7.4.0
Update ESLint to 7.4.0 PR-URL: https://github.com/nodejs/node/pull/34205 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de> Reviewed-By: Rich Trott <rtrott@gmail.com>
This commit is contained in:
67 files changed
+832
-636
No files matched your search
+1
-1
@@ -256,7 +256,7 @@ The following companies, organizations, and individuals support ESLint's ongoing
|
||||
<h3>Gold Sponsors</h3>
|
||||
<p><a href="https://www.shopify.com"><img src="https://images.opencollective.com/shopify/e780cd4/logo.png" alt="Shopify" height="96"></a> <a href="https://www.salesforce.com"><img src="https://images.opencollective.com/salesforce/ca8f997/logo.png" alt="Salesforce" height="96"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="96"></a></p><h3>Silver Sponsors</h3>
|
||||
<p><a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a> <a href="https://www.ampproject.org/"><img src="https://images.opencollective.com/amp/c8a3b25/logo.png" alt="AMP Project" height="64"></a></p><h3>Bronze Sponsors</h3>
|
||||
<p><a href="https://www.norgekasino.com"><img src="https://images.opencollective.com/norgekasino/ecfd57a/logo.png" alt="Norgekasino" height="32"></a> <a href="https://www.japanesecasino.com/"><img src="https://images.opencollective.com/japanesecasino/b0ffe3c/logo.png" alt="Japanesecasino" height="32"></a> <a href="https://bruce.agency"><img src="https://images.opencollective.com/brucemade/0c70c59/logo.png" alt="Bruce" height="32"></a> <a href="https://edubirdie.com/"><img src="https://images.opencollective.com/edubirdie2/b1d51ab/logo.png" alt="EduBirdie" height="32"></a> <a href="https://www.casinotop.com/"><img src="https://images.opencollective.com/casinotop-com/10fd95b/logo.png" alt="CasinoTop.com" height="32"></a> <a href="https://www.casinotopp.net/"><img src="https://images.opencollective.com/casino-topp/1dd399a/logo.png" alt="Casino Topp" height="32"></a> <a href="https://writersperhour.com/write-my-essay"><img src="https://images.opencollective.com/writersperhour/5787d4b/logo.png" alt="Writers Per Hour" height="32"></a> <a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="https://cooltechzone.com/netflix-vpn"><img src="https://images.opencollective.com/vpn-netflix/4850160/logo.png" alt="vpn netflix" height="32"></a> <a href="https://www.kasinot.fi"><img src="https://images.opencollective.com/kasinot-fi/e09aa2e/logo.png" alt="Kasinot.fi" height="32"></a> <a href="https://www.pelisivut.com"><img src="https://images.opencollective.com/pelisivut/04f08f2/logo.png" alt="Pelisivut" height="32"></a> <a href="https://www.nettikasinot.org"><img src="https://images.opencollective.com/nettikasinot-org/53a4b44/logo.png" alt="Nettikasinot.org" height="32"></a> <a href="https://www.bonus.com.de/freispiele"><img src="https://images.opencollective.com/bonusfinder-deutschland/646169e/logo.png" alt="BonusFinder Deutschland" height="32"></a> <a href="https://www.bugsnag.com/platforms?utm_source=Open Collective&utm_medium=Website&utm_content=open-source&utm_campaign=2019-community&utm_term="><img src="https://images.opencollective.com/bugsnag-stability-monitoring/c2cef36/logo.png" alt="Bugsnag Stability Monitoring" height="32"></a> <a href="https://mixpanel.com"><img src="https://images.opencollective.com/mixpanel/cd682f7/logo.png" alt="Mixpanel" height="32"></a> <a href="https://www.vpsserver.com"><img src="https://images.opencollective.com/vpsservercom/logo.png" alt="VPS Server" height="32"></a> <a href="https://icons8.com"><img src="https://images.opencollective.com/icons8/0b37d14/logo.png" alt="Free Icons by Icons8" height="32"></a> <a href="https://discordapp.com"><img src="https://images.opencollective.com/discordapp/7e3d9a9/logo.png" alt="Discord" height="32"></a> <a href="https://themeisle.com"><img src="https://images.opencollective.com/themeisle/d5592fe/logo.png" alt="ThemeIsle" height="32"></a> <a href="https://tekhattan.com"><img src="https://images.opencollective.com/tekhattan/bc73c28/logo.png" alt="TekHattan" height="32"></a> <a href="https://www.marfeel.com/"><img src="https://images.opencollective.com/marfeel/4b88e30/logo.png" alt="Marfeel" height="32"></a> <a href="http://www.firesticktricks.com"><img src="https://images.opencollective.com/fire-stick-tricks/b8fbe2c/logo.png" alt="Fire Stick Tricks" height="32"></a></p>
|
||||
<p><a href="https://mytruemedia.com/"><img src="https://images.opencollective.com/my-true-media/03e2168/logo.png" alt="My True Media" height="32"></a> <a href="https://www.norgekasino.com"><img src="https://images.opencollective.com/norgekasino/ecfd57a/logo.png" alt="Norgekasino" height="32"></a> <a href="https://www.japanesecasino.com/"><img src="https://images.opencollective.com/japanesecasino/b0ffe3c/logo.png" alt="Japanesecasino" height="32"></a> <a href="https://bruce.agency"><img src="https://images.opencollective.com/brucemade/0c70c59/logo.png" alt="Bruce" height="32"></a> <a href="https://edubirdie.com/"><img src="https://images.opencollective.com/edubirdie2/b1d51ab/logo.png" alt="EduBirdie" height="32"></a> <a href="https://www.casinotop.com/"><img src="https://images.opencollective.com/casinotop-com/10fd95b/logo.png" alt="CasinoTop.com" height="32"></a> <a href="https://www.casinotopp.net/"><img src="https://images.opencollective.com/casino-topp/1dd399a/logo.png" alt="Casino Topp" height="32"></a> <a href="https://writersperhour.com/write-my-essay"><img src="https://images.opencollective.com/writersperhour/5787d4b/logo.png" alt="Writers Per Hour" height="32"></a> <a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="https://www.kasinot.fi"><img src="https://images.opencollective.com/kasinot-fi/e09aa2e/logo.png" alt="Kasinot.fi" height="32"></a> <a href="https://www.pelisivut.com"><img src="https://images.opencollective.com/pelisivut/04f08f2/logo.png" alt="Pelisivut" height="32"></a> <a href="https://www.nettikasinot.org"><img src="https://images.opencollective.com/nettikasinot-org/53a4b44/logo.png" alt="Nettikasinot.org" height="32"></a> <a href="https://www.bonus.com.de/freispiele"><img src="https://images.opencollective.com/bonusfinder-deutschland/646169e/logo.png" alt="BonusFinder Deutschland" height="32"></a> <a href="https://www.bugsnag.com/platforms?utm_source=Open Collective&utm_medium=Website&utm_content=open-source&utm_campaign=2019-community&utm_term="><img src="https://images.opencollective.com/bugsnag-stability-monitoring/c2cef36/logo.png" alt="Bugsnag Stability Monitoring" height="32"></a> <a href="https://mixpanel.com"><img src="https://images.opencollective.com/mixpanel/cd682f7/logo.png" alt="Mixpanel" height="32"></a> <a href="https://www.vpsserver.com"><img src="https://images.opencollective.com/vpsservercom/logo.png" alt="VPS Server" height="32"></a> <a href="https://icons8.com"><img src="https://images.opencollective.com/icons8/6e889f6/logo.png" alt="Icons8: free icons, photos, illustrations, and music" height="32"></a> <a href="https://discordapp.com"><img src="https://images.opencollective.com/discordapp/7e3d9a9/logo.png" alt="Discord" height="32"></a> <a href="https://themeisle.com"><img src="https://images.opencollective.com/themeisle/d5592fe/logo.png" alt="ThemeIsle" height="32"></a> <a href="https://tekhattan.com"><img src="https://images.opencollective.com/tekhattan/bc73c28/logo.png" alt="TekHattan" height="32"></a> <a href="https://www.marfeel.com/"><img src="https://images.opencollective.com/marfeel/4b88e30/logo.png" alt="Marfeel" height="32"></a> <a href="http://www.firesticktricks.com"><img src="https://images.opencollective.com/fire-stick-tricks/b8fbe2c/logo.png" alt="Fire Stick Tricks" height="32"></a></p>
|
||||
<!--sponsorsend-->
|
||||
|
||||
## <a name="technology-sponsors"></a>Technology Sponsors
|
||||
|
||||
+1
-33
@@ -697,38 +697,6 @@ class ConfigArrayFactory {
|
||||
ctx.matchBasePath
|
||||
);
|
||||
|
||||
/**
|
||||
* Cloning the rule's config as we are setting `useDefaults` to true`
|
||||
* which mutates the config with its default value if present. And when we
|
||||
* refer to a same variable for config for different rules, that referred variable will
|
||||
* be mutated and it will be used for both.
|
||||
*
|
||||
* Example:
|
||||
*
|
||||
* const commonRuleConfig = ['error', {}];
|
||||
*
|
||||
* Now if we use this variable as a config for rules like this
|
||||
*
|
||||
* {
|
||||
* rules: {
|
||||
* "a" : commonRuleConfig,
|
||||
* "b" : commonRuleConfig,
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* And if these rules have default values in their schema, their
|
||||
* config will be mutated with default values, the mutated `commonRuleConfig` will be used for `b` as well and it probably
|
||||
* throw schema voilation errors.
|
||||
*
|
||||
* Refer https://github.com/eslint/eslint/issues/12592
|
||||
*/
|
||||
const clonedRulesConfig = rules && JSON.parse(
|
||||
JSON.stringify(
|
||||
rules,
|
||||
(key, value) => (value === Infinity ? Number.MAX_SAFE_INTEGER : value)
|
||||
)
|
||||
);
|
||||
|
||||
// Flatten `extends`.
|
||||
for (const extendName of extendList.filter(Boolean)) {
|
||||
yield* this._loadExtends(extendName, ctx);
|
||||
@@ -763,7 +731,7 @@ class ConfigArrayFactory {
|
||||
processor,
|
||||
reportUnusedDisableDirectives,
|
||||
root,
|
||||
rules: clonedRulesConfig,
|
||||
rules,
|
||||
settings
|
||||
};
|
||||
|
||||
|
||||
+21
-10
@@ -9,8 +9,6 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const lodash = require("lodash");
|
||||
|
||||
const astUtils = require("./utils/ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -43,6 +41,19 @@ function isTargetMethod(node) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a human-legible description of an array method
|
||||
* @param {string} arrayMethodName A method name to fully qualify
|
||||
* @returns {string} the method name prefixed with `Array.` if it is a class method,
|
||||
* or else `Array.prototype.` if it is an instance method.
|
||||
*/
|
||||
function fullMethodName(arrayMethodName) {
|
||||
if (["from", "of", "isArray"].includes(arrayMethodName)) {
|
||||
return "Array.".concat(arrayMethodName);
|
||||
}
|
||||
return "Array.prototype.".concat(arrayMethodName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether or not a given node is a function expression which is the
|
||||
* callback of an array method, returning the method name.
|
||||
@@ -153,10 +164,10 @@ module.exports = {
|
||||
],
|
||||
|
||||
messages: {
|
||||
expectedAtEnd: "Expected to return a value at the end of {{name}}.",
|
||||
expectedInside: "Expected to return a value in {{name}}.",
|
||||
expectedReturnValue: "{{name}} expected a return value.",
|
||||
expectedNoReturnValue: "{{name}} did not expect a return value."
|
||||
expectedAtEnd: "{{arrayMethodName}}() expects a value to be returned at the end of {{name}}.",
|
||||
expectedInside: "{{arrayMethodName}}() expects a return value from {{name}}.",
|
||||
expectedReturnValue: "{{arrayMethodName}}() expects a return value from {{name}}.",
|
||||
expectedNoReturnValue: "{{arrayMethodName}}() expects no useless return value from {{name}}."
|
||||
}
|
||||
},
|
||||
|
||||
@@ -202,14 +213,13 @@ module.exports = {
|
||||
}
|
||||
|
||||
if (messageId) {
|
||||
let name = astUtils.getFunctionNameWithKind(node);
|
||||
const name = astUtils.getFunctionNameWithKind(node);
|
||||
|
||||
name = messageId === "expectedNoReturnValue" ? lodash.upperFirst(name) : name;
|
||||
context.report({
|
||||
node,
|
||||
loc: astUtils.getFunctionHeadLoc(node, sourceCode),
|
||||
messageId,
|
||||
data: { name }
|
||||
data: { name, arrayMethodName: fullMethodName(funcInfo.arrayMethodName) }
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -273,7 +283,8 @@ module.exports = {
|
||||
node,
|
||||
messageId,
|
||||
data: {
|
||||
name: lodash.upperFirst(astUtils.getFunctionNameWithKind(funcInfo.node))
|
||||
name: astUtils.getFunctionNameWithKind(funcInfo.node),
|
||||
arrayMethodName: fullMethodName(funcInfo.arrayMethodName)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+2
-2
@@ -136,7 +136,7 @@ module.exports = {
|
||||
|
||||
context.report({
|
||||
node,
|
||||
loc: arrowBody.loc.start,
|
||||
loc: arrowBody.loc,
|
||||
messageId,
|
||||
fix(fixer) {
|
||||
const fixes = [];
|
||||
@@ -201,7 +201,7 @@ module.exports = {
|
||||
if (always || (asNeeded && requireReturnForObjectLiteral && arrowBody.type === "ObjectExpression")) {
|
||||
context.report({
|
||||
node,
|
||||
loc: arrowBody.loc.start,
|
||||
loc: arrowBody.loc,
|
||||
messageId: "expectedBlock",
|
||||
fix(fixer) {
|
||||
const fixes = [];
|
||||
|
||||
+100
-117
@@ -15,15 +15,12 @@ const astUtils = require("./utils/ast-utils");
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Get location should be reported by AST node.
|
||||
* @param {ASTNode} node AST Node.
|
||||
* @returns {Location} Location information.
|
||||
* Determines if the given arrow function has block body.
|
||||
* @param {ASTNode} node `ArrowFunctionExpression` node.
|
||||
* @returns {boolean} `true` if the function has block body.
|
||||
*/
|
||||
function getLocation(node) {
|
||||
return {
|
||||
start: node.params[0].loc.start,
|
||||
end: node.params[node.params.length - 1].loc.end
|
||||
};
|
||||
function hasBlockBody(node) {
|
||||
return node.body.type === "BlockStatement";
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -75,126 +72,112 @@ module.exports = {
|
||||
const sourceCode = context.getSourceCode();
|
||||
|
||||
/**
|
||||
* Determines whether a arrow function argument end with `)`
|
||||
* @param {ASTNode} node The arrow function node.
|
||||
* @returns {void}
|
||||
* Finds opening paren of parameters for the given arrow function, if it exists.
|
||||
* It is assumed that the given arrow function has exactly one parameter.
|
||||
* @param {ASTNode} node `ArrowFunctionExpression` node.
|
||||
* @returns {Token|null} the opening paren, or `null` if the given arrow function doesn't have parens of parameters.
|
||||
*/
|
||||
function parens(node) {
|
||||
const isAsync = node.async;
|
||||
const firstTokenOfParam = sourceCode.getFirstToken(node, isAsync ? 1 : 0);
|
||||
|
||||
/**
|
||||
* Remove the parenthesis around a parameter
|
||||
* @param {Fixer} fixer Fixer
|
||||
* @returns {string} fixed parameter
|
||||
*/
|
||||
function fixParamsWithParenthesis(fixer) {
|
||||
const paramToken = sourceCode.getTokenAfter(firstTokenOfParam);
|
||||
|
||||
/*
|
||||
* ES8 allows Trailing commas in function parameter lists and calls
|
||||
* https://github.com/eslint/eslint/issues/8834
|
||||
*/
|
||||
const closingParenToken = sourceCode.getTokenAfter(paramToken, astUtils.isClosingParenToken);
|
||||
const asyncToken = isAsync ? sourceCode.getTokenBefore(firstTokenOfParam) : null;
|
||||
const shouldAddSpaceForAsync = asyncToken && (asyncToken.range[1] === firstTokenOfParam.range[0]);
|
||||
|
||||
return fixer.replaceTextRange([
|
||||
firstTokenOfParam.range[0],
|
||||
closingParenToken.range[1]
|
||||
], `${shouldAddSpaceForAsync ? " " : ""}${paramToken.value}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether there are comments inside the params or not.
|
||||
* @returns {boolean} `true` if there are comments inside of parens, else `false`
|
||||
*/
|
||||
function hasCommentsInParens() {
|
||||
if (astUtils.isOpeningParenToken(firstTokenOfParam)) {
|
||||
const closingParenToken = sourceCode.getTokenAfter(node.params[0], astUtils.isClosingParenToken);
|
||||
|
||||
return closingParenToken && sourceCode.commentsExistBetween(firstTokenOfParam, closingParenToken);
|
||||
}
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
if (hasCommentsInParens()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// "as-needed", { "requireForBlockBody": true }: x => x
|
||||
if (
|
||||
requireForBlockBody &&
|
||||
node.params[0].type === "Identifier" &&
|
||||
!node.params[0].typeAnnotation &&
|
||||
node.body.type !== "BlockStatement" &&
|
||||
!node.returnType
|
||||
) {
|
||||
if (astUtils.isOpeningParenToken(firstTokenOfParam)) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "unexpectedParensInline",
|
||||
loc: getLocation(node),
|
||||
fix: fixParamsWithParenthesis
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
function findOpeningParenOfParams(node) {
|
||||
const tokenBeforeParams = sourceCode.getTokenBefore(node.params[0]);
|
||||
|
||||
if (
|
||||
requireForBlockBody &&
|
||||
node.body.type === "BlockStatement"
|
||||
tokenBeforeParams &&
|
||||
astUtils.isOpeningParenToken(tokenBeforeParams) &&
|
||||
node.range[0] <= tokenBeforeParams.range[0]
|
||||
) {
|
||||
if (!astUtils.isOpeningParenToken(firstTokenOfParam)) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "expectedParensBlock",
|
||||
loc: getLocation(node),
|
||||
fix(fixer) {
|
||||
return fixer.replaceText(firstTokenOfParam, `(${firstTokenOfParam.value})`);
|
||||
}
|
||||
});
|
||||
}
|
||||
return;
|
||||
return tokenBeforeParams;
|
||||
}
|
||||
|
||||
// "as-needed": x => x
|
||||
if (asNeeded &&
|
||||
node.params[0].type === "Identifier" &&
|
||||
!node.params[0].typeAnnotation &&
|
||||
!node.returnType
|
||||
) {
|
||||
if (astUtils.isOpeningParenToken(firstTokenOfParam)) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "unexpectedParens",
|
||||
loc: getLocation(node),
|
||||
fix: fixParamsWithParenthesis
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if (firstTokenOfParam.type === "Identifier") {
|
||||
const after = sourceCode.getTokenAfter(firstTokenOfParam);
|
||||
/**
|
||||
* Finds closing paren of parameters for the given arrow function.
|
||||
* It is assumed that the given arrow function has parens of parameters and that it has exactly one parameter.
|
||||
* @param {ASTNode} node `ArrowFunctionExpression` node.
|
||||
* @returns {Token} the closing paren of parameters.
|
||||
*/
|
||||
function getClosingParenOfParams(node) {
|
||||
return sourceCode.getTokenAfter(node.params[0], astUtils.isClosingParenToken);
|
||||
}
|
||||
|
||||
// (x) => x
|
||||
if (after.value !== ")") {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "expectedParens",
|
||||
loc: getLocation(node),
|
||||
fix(fixer) {
|
||||
return fixer.replaceText(firstTokenOfParam, `(${firstTokenOfParam.value})`);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Determines whether the given arrow function has comments inside parens of parameters.
|
||||
* It is assumed that the given arrow function has parens of parameters.
|
||||
* @param {ASTNode} node `ArrowFunctionExpression` node.
|
||||
* @param {Token} openingParen Opening paren of parameters.
|
||||
* @returns {boolean} `true` if the function has at least one comment inside of parens of parameters.
|
||||
*/
|
||||
function hasCommentsInParensOfParams(node, openingParen) {
|
||||
return sourceCode.commentsExistBetween(openingParen, getClosingParenOfParams(node));
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the given arrow function has unexpected tokens before opening paren of parameters,
|
||||
* in which case it will be assumed that the existing parens of parameters are necessary.
|
||||
* Only tokens within the range of the arrow function (tokens that are part of the arrow function) are taken into account.
|
||||
* Example: <T>(a) => b
|
||||
* @param {ASTNode} node `ArrowFunctionExpression` node.
|
||||
* @param {Token} openingParen Opening paren of parameters.
|
||||
* @returns {boolean} `true` if the function has at least one unexpected token.
|
||||
*/
|
||||
function hasUnexpectedTokensBeforeOpeningParen(node, openingParen) {
|
||||
const expectedCount = node.async ? 1 : 0;
|
||||
|
||||
return sourceCode.getFirstToken(node, { skip: expectedCount }) !== openingParen;
|
||||
}
|
||||
|
||||
return {
|
||||
"ArrowFunctionExpression[params.length=1]": parens
|
||||
"ArrowFunctionExpression[params.length=1]"(node) {
|
||||
const shouldHaveParens = !asNeeded || requireForBlockBody && hasBlockBody(node);
|
||||
const openingParen = findOpeningParenOfParams(node);
|
||||
const hasParens = openingParen !== null;
|
||||
const [param] = node.params;
|
||||
|
||||
if (shouldHaveParens && !hasParens) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: requireForBlockBody ? "expectedParensBlock" : "expectedParens",
|
||||
loc: param.loc,
|
||||
*fix(fixer) {
|
||||
yield fixer.insertTextBefore(param, "(");
|
||||
yield fixer.insertTextAfter(param, ")");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
!shouldHaveParens &&
|
||||
hasParens &&
|
||||
param.type === "Identifier" &&
|
||||
!param.typeAnnotation &&
|
||||
!node.returnType &&
|
||||
!hasCommentsInParensOfParams(node, openingParen) &&
|
||||
!hasUnexpectedTokensBeforeOpeningParen(node, openingParen)
|
||||
) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: requireForBlockBody ? "unexpectedParensInline" : "unexpectedParens",
|
||||
loc: param.loc,
|
||||
*fix(fixer) {
|
||||
const tokenBeforeOpeningParen = sourceCode.getTokenBefore(openingParen);
|
||||
const closingParen = getClosingParenOfParams(node);
|
||||
|
||||
if (
|
||||
tokenBeforeOpeningParen &&
|
||||
tokenBeforeOpeningParen.range[1] === openingParen.range[0] &&
|
||||
!astUtils.canTokensBeAdjacent(tokenBeforeOpeningParen, sourceCode.getFirstToken(param))
|
||||
) {
|
||||
yield fixer.insertTextBefore(openingParen, " ");
|
||||
}
|
||||
|
||||
// remove parens, whitespace inside parens, and possible trailing comma
|
||||
yield fixer.removeRange([openingParen.range[0], param.range[0]]);
|
||||
yield fixer.removeRange([param.range[1], closingParen.range[1]]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
+47
@@ -32,6 +32,10 @@ module.exports = {
|
||||
type: "boolean",
|
||||
default: false
|
||||
},
|
||||
ignoreGlobals: {
|
||||
type: "boolean",
|
||||
default: false
|
||||
},
|
||||
properties: {
|
||||
enum: ["always", "never"]
|
||||
},
|
||||
@@ -61,8 +65,11 @@ module.exports = {
|
||||
let properties = options.properties || "";
|
||||
const ignoreDestructuring = options.ignoreDestructuring;
|
||||
const ignoreImports = options.ignoreImports;
|
||||
const ignoreGlobals = options.ignoreGlobals;
|
||||
const allow = options.allow || [];
|
||||
|
||||
let globalScope;
|
||||
|
||||
if (properties !== "always" && properties !== "never") {
|
||||
properties = "always";
|
||||
}
|
||||
@@ -159,6 +166,37 @@ module.exports = {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given node represents a reference to a global variable that is not declared in the source code.
|
||||
* These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables.
|
||||
* @param {ASTNode} node `Identifier` node to check.
|
||||
* @returns {boolean} `true` if the node is a reference to a global variable.
|
||||
*/
|
||||
function isReferenceToGlobalVariable(node) {
|
||||
const variable = globalScope.set.get(node.name);
|
||||
|
||||
return variable && variable.defs.length === 0 &&
|
||||
variable.references.some(ref => ref.identifier === node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given node represents a reference to a property of an object in an object literal expression.
|
||||
* This allows to differentiate between a global variable that is allowed to be used as a reference, and the key
|
||||
* of the expressed object (which shouldn't be allowed).
|
||||
* @param {ASTNode} node `Identifier` node to check.
|
||||
* @returns {boolean} `true` if the node is a property name of an object literal expression
|
||||
*/
|
||||
function isPropertyNameInObjectLiteral(node) {
|
||||
const parent = node.parent;
|
||||
|
||||
return (
|
||||
parent.type === "Property" &&
|
||||
parent.parent.type === "ObjectExpression" &&
|
||||
!parent.computed &&
|
||||
parent.key === node
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports an AST node as a rule violation.
|
||||
* @param {ASTNode} node The node to report.
|
||||
@@ -174,6 +212,10 @@ module.exports = {
|
||||
|
||||
return {
|
||||
|
||||
Program() {
|
||||
globalScope = context.getScope();
|
||||
},
|
||||
|
||||
Identifier(node) {
|
||||
|
||||
/*
|
||||
@@ -189,6 +231,11 @@ module.exports = {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if it's a global variable
|
||||
if (ignoreGlobals && isReferenceToGlobalVariable(node) && !isPropertyNameInObjectLiteral(node)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// MemberExpressions get special rules
|
||||
if (node.parent.type === "MemberExpression") {
|
||||
|
||||
|
||||
Generated
Vendored
+12
-12
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* @fileoverview Rule that warns when identifier names that are
|
||||
* blacklisted in the configuration are used.
|
||||
* specified in the configuration are used.
|
||||
* @author Keith Cirkel (http://keithcirkel.co.uk)
|
||||
*/
|
||||
|
||||
@@ -117,7 +117,7 @@ module.exports = {
|
||||
description: "disallow specified identifiers",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/id-blacklist"
|
||||
url: "https://eslint.org/docs/rules/id-denylist"
|
||||
},
|
||||
|
||||
schema: {
|
||||
@@ -128,25 +128,25 @@ module.exports = {
|
||||
uniqueItems: true
|
||||
},
|
||||
messages: {
|
||||
blacklisted: "Identifier '{{name}}' is blacklisted."
|
||||
restricted: "Identifier '{{name}}' is restricted."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
|
||||
const blacklist = new Set(context.options);
|
||||
const denyList = new Set(context.options);
|
||||
const reportedNodes = new Set();
|
||||
|
||||
let globalScope;
|
||||
|
||||
/**
|
||||
* Checks whether the given name is blacklisted.
|
||||
* Checks whether the given name is restricted.
|
||||
* @param {string} name The name to check.
|
||||
* @returns {boolean} `true` if the name is blacklisted.
|
||||
* @returns {boolean} `true` if the name is restricted.
|
||||
* @private
|
||||
*/
|
||||
function isBlacklisted(name) {
|
||||
return blacklist.has(name);
|
||||
function isRestricted(name) {
|
||||
return denyList.has(name);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -172,8 +172,8 @@ module.exports = {
|
||||
|
||||
/*
|
||||
* Member access has special rules for checking property names.
|
||||
* Read access to a property with a blacklisted name is allowed, because it can be on an object that user has no control over.
|
||||
* Write access isn't allowed, because it potentially creates a new property with a blacklisted name.
|
||||
* Read access to a property with a restricted name is allowed, because it can be on an object that user has no control over.
|
||||
* Write access isn't allowed, because it potentially creates a new property with a restricted name.
|
||||
*/
|
||||
if (
|
||||
parent.type === "MemberExpression" &&
|
||||
@@ -205,7 +205,7 @@ module.exports = {
|
||||
if (!reportedNodes.has(node)) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "blacklisted",
|
||||
messageId: "restricted",
|
||||
data: {
|
||||
name: node.name
|
||||
}
|
||||
@@ -221,7 +221,7 @@ module.exports = {
|
||||
},
|
||||
|
||||
Identifier(node) {
|
||||
if (isBlacklisted(node.name) && shouldCheck(node)) {
|
||||
if (isRestricted(node.name) && shouldCheck(node)) {
|
||||
report(node);
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -56,7 +56,10 @@ module.exports = new LazyLoadingRuleMap(Object.entries({
|
||||
"grouped-accessor-pairs": () => require("./grouped-accessor-pairs"),
|
||||
"guard-for-in": () => require("./guard-for-in"),
|
||||
"handle-callback-err": () => require("./handle-callback-err"),
|
||||
"id-blacklist": () => require("./id-blacklist"),
|
||||
|
||||
// Renamed to id-denylist.
|
||||
"id-blacklist": () => require("./id-denylist"),
|
||||
"id-denylist": () => require("./id-denylist"),
|
||||
"id-length": () => require("./id-length"),
|
||||
"id-match": () => require("./id-match"),
|
||||
"implicit-arrow-linebreak": () => require("./implicit-arrow-linebreak"),
|
||||
|
||||
+21
-3
@@ -710,6 +710,20 @@ module.exports = {
|
||||
reportsBuffer.reports = reportsBuffer.reports.filter(r => r.node !== node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a node is a MemberExpression at NewExpression's callee.
|
||||
* @param {ASTNode} node node to check.
|
||||
* @returns {boolean} True if the node is a MemberExpression at NewExpression's callee. false otherwise.
|
||||
*/
|
||||
function isMemberExpInNewCallee(node) {
|
||||
if (node.type === "MemberExpression") {
|
||||
return node.parent.type === "NewExpression" && node.parent.callee === node
|
||||
? true
|
||||
: node.parent.object === node && isMemberExpInNewCallee(node.parent);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
return {
|
||||
ArrayExpression(node) {
|
||||
node.elements
|
||||
@@ -950,7 +964,11 @@ module.exports = {
|
||||
LogicalExpression: checkBinaryLogical,
|
||||
|
||||
MemberExpression(node) {
|
||||
const nodeObjHasExcessParens = hasExcessParens(node.object) &&
|
||||
const shouldAllowWrapOnce = isMemberExpInNewCallee(node) &&
|
||||
doesMemberExpressionContainCallExpression(node);
|
||||
const nodeObjHasExcessParens = shouldAllowWrapOnce
|
||||
? hasDoubleExcessParens(node.object)
|
||||
: hasExcessParens(node.object) &&
|
||||
!(
|
||||
isImmediateFunctionPrototypeMethodCall(node.parent) &&
|
||||
node.parent.callee === node &&
|
||||
@@ -974,8 +992,8 @@ module.exports = {
|
||||
}
|
||||
|
||||
if (nodeObjHasExcessParens &&
|
||||
node.object.type === "CallExpression" &&
|
||||
node.parent.type !== "NewExpression") {
|
||||
node.object.type === "CallExpression"
|
||||
) {
|
||||
report(node.object);
|
||||
}
|
||||
|
||||
|
||||
+66
-8
@@ -25,6 +25,15 @@ function isStringLiteral(node) {
|
||||
return node.type === "Literal" && typeof node.value === "string";
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the given node is a regex literal.
|
||||
* @param {ASTNode} node Node to check.
|
||||
* @returns {boolean} True if the node is a regex literal.
|
||||
*/
|
||||
function isRegexLiteral(node) {
|
||||
return node.type === "Literal" && Object.prototype.hasOwnProperty.call(node, "regex");
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the given node is a template literal without expressions.
|
||||
* @param {ASTNode} node Node to check.
|
||||
@@ -50,14 +59,28 @@ module.exports = {
|
||||
url: "https://eslint.org/docs/rules/prefer-regex-literals"
|
||||
},
|
||||
|
||||
schema: [],
|
||||
schema: [
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
disallowRedundantWrapping: {
|
||||
type: "boolean",
|
||||
default: false
|
||||
}
|
||||
},
|
||||
additionalProperties: false
|
||||
}
|
||||
],
|
||||
|
||||
messages: {
|
||||
unexpectedRegExp: "Use a regular expression literal instead of the 'RegExp' constructor."
|
||||
unexpectedRegExp: "Use a regular expression literal instead of the 'RegExp' constructor.",
|
||||
unexpectedRedundantRegExp: "Regular expression literal is unnecessarily wrapped within a 'RegExp' constructor.",
|
||||
unexpectedRedundantRegExpWithFlags: "Use regular expression literal with flags instead of the 'RegExp' constructor."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const [{ disallowRedundantWrapping = false } = {}] = context.options;
|
||||
|
||||
/**
|
||||
* Determines whether the given identifier node is a reference to a global variable.
|
||||
@@ -98,6 +121,40 @@ module.exports = {
|
||||
isStringRawTaggedStaticTemplateLiteral(node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the relevant arguments of the given are all static string literals.
|
||||
* @param {ASTNode} node Node to check.
|
||||
* @returns {boolean} True if all arguments are static strings.
|
||||
*/
|
||||
function hasOnlyStaticStringArguments(node) {
|
||||
const args = node.arguments;
|
||||
|
||||
if ((args.length === 1 || args.length === 2) && args.every(isStaticString)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the arguments of the given node indicate that a regex literal is unnecessarily wrapped.
|
||||
* @param {ASTNode} node Node to check.
|
||||
* @returns {boolean} True if the node already contains a regex literal argument.
|
||||
*/
|
||||
function isUnnecessarilyWrappedRegexLiteral(node) {
|
||||
const args = node.arguments;
|
||||
|
||||
if (args.length === 1 && isRegexLiteral(args[0])) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (args.length === 2 && isRegexLiteral(args[0]) && isStaticString(args[1])) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return {
|
||||
Program() {
|
||||
const scope = context.getScope();
|
||||
@@ -110,12 +167,13 @@ module.exports = {
|
||||
};
|
||||
|
||||
for (const { node } of tracker.iterateGlobalReferences(traceMap)) {
|
||||
const args = node.arguments;
|
||||
|
||||
if (
|
||||
(args.length === 1 || args.length === 2) &&
|
||||
args.every(isStaticString)
|
||||
) {
|
||||
if (disallowRedundantWrapping && isUnnecessarilyWrappedRegexLiteral(node)) {
|
||||
if (node.arguments.length === 2) {
|
||||
context.report({ node, messageId: "unexpectedRedundantRegExpWithFlags" });
|
||||
} else {
|
||||
context.report({ node, messageId: "unexpectedRedundantRegExp" });
|
||||
}
|
||||
} else if (hasOnlyStaticStringArguments(node)) {
|
||||
context.report({ node, messageId: "unexpectedRegExp" });
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -8,7 +8,7 @@
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {
|
||||
"@babel/highlight": "^7.10.3"
|
||||
"@babel/highlight": "^7.10.4"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "Generate errors that contain a code frame that point to source locations.",
|
||||
@@ -16,7 +16,7 @@
|
||||
"chalk": "^2.0.0",
|
||||
"strip-ansi": "^4.0.0"
|
||||
},
|
||||
"gitHead": "2787ee2f967b6d8e1121fca00a8d578d75449a53",
|
||||
"gitHead": "7fd40d86a0d03ff0e9c3ea16b29689945433d4df",
|
||||
"homepage": "https://babeljs.io/",
|
||||
"license": "MIT",
|
||||
"main": "lib/index.js",
|
||||
@@ -29,5 +29,5 @@
|
||||
"url": "git+https://github.com/babel/babel.git",
|
||||
"directory": "packages/babel-code-frame"
|
||||
},
|
||||
"version": "7.10.3"
|
||||
"version": "7.10.4"
|
||||
}
|
||||
Generated
Vendored
+2
-2
@@ -10,7 +10,7 @@
|
||||
"unicode-13.0.0": "^0.8.0"
|
||||
},
|
||||
"exports": "./lib/index.js",
|
||||
"gitHead": "2787ee2f967b6d8e1121fca00a8d578d75449a53",
|
||||
"gitHead": "7fd40d86a0d03ff0e9c3ea16b29689945433d4df",
|
||||
"homepage": "https://github.com/babel/babel#readme",
|
||||
"license": "MIT",
|
||||
"main": "./lib/index.js",
|
||||
@@ -23,5 +23,5 @@
|
||||
"url": "git+https://github.com/babel/babel.git",
|
||||
"directory": "packages/babel-helper-validator-identifier"
|
||||
},
|
||||
"version": "7.10.3"
|
||||
"version": "7.10.4"
|
||||
}
|
||||
+3
-3
@@ -8,7 +8,7 @@
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {
|
||||
"@babel/helper-validator-identifier": "^7.10.3",
|
||||
"@babel/helper-validator-identifier": "^7.10.4",
|
||||
"chalk": "^2.0.0",
|
||||
"js-tokens": "^4.0.0"
|
||||
},
|
||||
@@ -17,7 +17,7 @@
|
||||
"devDependencies": {
|
||||
"strip-ansi": "^4.0.0"
|
||||
},
|
||||
"gitHead": "2787ee2f967b6d8e1121fca00a8d578d75449a53",
|
||||
"gitHead": "7fd40d86a0d03ff0e9c3ea16b29689945433d4df",
|
||||
"homepage": "https://babeljs.io/",
|
||||
"license": "MIT",
|
||||
"main": "lib/index.js",
|
||||
@@ -30,5 +30,5 @@
|
||||
"url": "git+https://github.com/babel/babel.git",
|
||||
"directory": "packages/babel-highlight"
|
||||
},
|
||||
"version": "7.10.3"
|
||||
"version": "7.10.4"
|
||||
}
|
||||
+104
-78
@@ -1,21 +1,28 @@
|
||||
<img align="right" alt="Ajv logo" width="160" src="http://epoberezkin.github.io/ajv/images/ajv_logo.png">
|
||||
<img align="right" alt="Ajv logo" width="160" src="https://ajv.js.org/images/ajv_logo.png">
|
||||
|
||||
# Ajv: Another JSON Schema Validator
|
||||
|
||||
The fastest JSON Schema validator for Node.js and browser. Supports draft-04/06/07.
|
||||
|
||||
[](https://travis-ci.org/epoberezkin/ajv)
|
||||
[](https://travis-ci.org/ajv-validator/ajv)
|
||||
[](https://www.npmjs.com/package/ajv)
|
||||
[](https://www.npmjs.com/package/ajv)
|
||||
[](https://coveralls.io/github/epoberezkin/ajv?branch=master)
|
||||
[](https://coveralls.io/github/ajv-validator/ajv?branch=master)
|
||||
[](https://gitter.im/ajv-validator/ajv)
|
||||
[](https://github.com/sponsors/epoberezkin)
|
||||
|
||||
## Please [sponsor Ajv](https://github.com/sponsors/epoberezkin)
|
||||
|
||||
Dear Ajv users! ❤️
|
||||
## Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin)
|
||||
|
||||
I ask you to support the development of Ajv with donations. 🙏
|
||||
I will get straight to the point - I need your support to ensure that the development of Ajv continues.
|
||||
|
||||
I have developed Ajv for 5 years in my free time, but it is not sustainable. I'd appreciate if you consider supporting its further development with donations:
|
||||
- [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it)
|
||||
- [Ajv Open Collective️](https://opencollective.com/ajv)
|
||||
|
||||
There are many small and large improvements that are long due, including the support of the next versions of JSON Schema specification, improving website and documentation, and making Ajv more modular and maintainable to address its limitations - what Ajv needs to evolve is much more than what I can contribute in my free time.
|
||||
|
||||
I would also really appreciate any advice you could give on how to raise funds for Ajv development - whether some suitable open-source fund I could apply to or some sponsor I should approach.
|
||||
|
||||
Since 2015 Ajv has become widely used, thanks to your help and contributions:
|
||||
|
||||
@@ -25,17 +32,10 @@ Since 2015 Ajv has become widely used, thanks to your help and contributions:
|
||||
- **5,000,000** dependent repositories on GitHub 🚀
|
||||
- **120,000,000** npm downloads per month! 💯
|
||||
|
||||
Your donations will fund futher development - small and large improvements, support of the next versions of JSON Schema specification, and, possibly, the code should be migrated to TypeScript to make it more maintainable.
|
||||
I believe it would benefit all Ajv users to help put together the fund that will be used for its further development - it would allow to bring some additional maintainers to the project.
|
||||
|
||||
I will greatly appreciate anything you can help with to make it happen:
|
||||
Thank you
|
||||
|
||||
- a **personal** donation - from $2 ☕️
|
||||
- your **company** donation - from $10 🍔
|
||||
- a **sponsorship** to get promoted on Ajv or related packages - from $50 💰
|
||||
- an **introduction** to a sponsor who would benefit from the promotion on Ajv page 🤝
|
||||
|
||||
| Please [make donations via my GitHub sponsors page](https://github.com/sponsors/epoberezkin)<br>‼️ **GitHub will DOUBLE them** ‼️ |
|
||||
|---|
|
||||
|
||||
#### Open Collective sponsors
|
||||
|
||||
@@ -57,7 +57,7 @@ I will greatly appreciate anything you can help with to make it happen:
|
||||
|
||||
[JSON Schema draft-07](http://json-schema.org/latest/json-schema-validation.html) is published.
|
||||
|
||||
[Ajv version 6.0.0](https://github.com/epoberezkin/ajv/releases/tag/v6.0.0) that supports draft-07 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas, draft-06 schemas will be supported without changes).
|
||||
[Ajv version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0) that supports draft-07 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas, draft-06 schemas will be supported without changes).
|
||||
|
||||
__Please note__: To use Ajv with draft-06 schemas you need to explicitly add the meta-schema to the validator instance:
|
||||
|
||||
@@ -80,8 +80,9 @@ ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
|
||||
- [Performance](#performance)
|
||||
- [Features](#features)
|
||||
- [Getting started](#getting-started)
|
||||
- [Frequently Asked Questions](https://github.com/epoberezkin/ajv/blob/master/FAQ.md)
|
||||
- [Frequently Asked Questions](https://github.com/ajv-validator/ajv/blob/master/FAQ.md)
|
||||
- [Using in browser](#using-in-browser)
|
||||
- [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp)
|
||||
- [Command line interface](#command-line-interface)
|
||||
- Validation
|
||||
- [Keywords](#validation-keywords)
|
||||
@@ -110,7 +111,8 @@ ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
|
||||
- [Plugins](#plugins)
|
||||
- [Related packages](#related-packages)
|
||||
- [Some packages using Ajv](#some-packages-using-ajv)
|
||||
- [Tests, Contributing, History, Support, License](#tests)
|
||||
- [Tests, Contributing, Changes history](#tests)
|
||||
- [Support, Code of conduct, License](#open-source-software-support)
|
||||
|
||||
|
||||
## Performance
|
||||
@@ -133,24 +135,24 @@ Performance of different validators by [json-schema-benchmark](https://github.co
|
||||
## Features
|
||||
|
||||
- Ajv implements full JSON Schema [draft-06/07](http://json-schema.org/) and draft-04 standards:
|
||||
- all validation keywords (see [JSON Schema validation keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md))
|
||||
- all validation keywords (see [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md))
|
||||
- full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available)
|
||||
- support of circular references between schemas
|
||||
- correct string lengths for strings with unicode pairs (can be turned off)
|
||||
- [formats](#formats) defined by JSON Schema draft-07 standard and custom formats (can be turned off)
|
||||
- [validates schemas against meta-schema](#api-validateschema)
|
||||
- supports [browsers](#using-in-browser) and Node.js 0.10-8.x
|
||||
- supports [browsers](#using-in-browser) and Node.js 0.10-14.x
|
||||
- [asynchronous loading](#asynchronous-schema-compilation) of referenced schemas during compilation
|
||||
- "All errors" validation mode with [option allErrors](#options)
|
||||
- [error messages with parameters](#validation-errors) describing error reasons to allow creating custom error messages
|
||||
- i18n error messages support with [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) package
|
||||
- i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package
|
||||
- [filtering data](#filtering-data) from additional properties
|
||||
- [assigning defaults](#assigning-defaults) to missing properties and items
|
||||
- [coercing data](#coercing-data-types) to the types specified in `type` keywords
|
||||
- [custom keywords](#defining-custom-keywords)
|
||||
- draft-06/07 keywords `const`, `contains`, `propertyNames` and `if/then/else`
|
||||
- draft-06 boolean schemas (`true`/`false` as a schema to always pass/fail).
|
||||
- keywords `switch`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package
|
||||
- keywords `switch`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package
|
||||
- [$data reference](#data-reference) to use values from the validated data as values for the schema keywords
|
||||
- [asynchronous validation](#asynchronous-validation) of custom formats and keywords
|
||||
|
||||
@@ -234,21 +236,31 @@ Ajv is tested with these browsers:
|
||||
|
||||
[](https://saucelabs.com/u/epoberezkin)
|
||||
|
||||
__Please note__: some frameworks, e.g. Dojo, may redefine global require in such way that is not compatible with CommonJS module format. In such case Ajv bundle has to be loaded before the framework and then you can use global Ajv (see issue [#234](https://github.com/epoberezkin/ajv/issues/234)).
|
||||
__Please note__: some frameworks, e.g. Dojo, may redefine global require in such way that is not compatible with CommonJS module format. In such case Ajv bundle has to be loaded before the framework and then you can use global Ajv (see issue [#234](https://github.com/ajv-validator/ajv/issues/234)).
|
||||
|
||||
|
||||
### Ajv and Content Security Policies (CSP)
|
||||
|
||||
If you're using Ajv to compile a schema (the typical use) in a browser document that is loaded with a Content Security Policy (CSP), that policy will require a `script-src` directive that includes the value `'unsafe-eval'`.
|
||||
:warning: NOTE, however, that `unsafe-eval` is NOT recommended in a secure CSP[[1]](https://developer.chrome.com/extensions/contentSecurityPolicy#relaxing-eval), as it has the potential to open the document to cross-site scripting (XSS) attacks.
|
||||
|
||||
In order to make use of Ajv without easing your CSP, you can [pre-compile a schema using the CLI](https://github.com/ajv-validator/ajv-cli#compile-schemas). This will transpile the schema JSON into a JavaScript file that exports a `validate` function that works simlarly to a schema compiled at runtime.
|
||||
|
||||
Note that pre-compilation of schemas is performed using [ajv-pack](https://github.com/ajv-validator/ajv-pack) and there are [some limitations to the schema features it can compile](https://github.com/ajv-validator/ajv-pack#limitations). A successfully pre-compiled schema is equivalent to the same schema compiled at runtime.
|
||||
|
||||
|
||||
## Command line interface
|
||||
|
||||
CLI is available as a separate npm package [ajv-cli](https://github.com/jessedc/ajv-cli). It supports:
|
||||
CLI is available as a separate npm package [ajv-cli](https://github.com/ajv-validator/ajv-cli). It supports:
|
||||
|
||||
- compiling JSON Schemas to test their validity
|
||||
- BETA: generating standalone module exporting a validation function to be used without Ajv (using [ajv-pack](https://github.com/epoberezkin/ajv-pack))
|
||||
- BETA: generating standalone module exporting a validation function to be used without Ajv (using [ajv-pack](https://github.com/ajv-validator/ajv-pack))
|
||||
- migrate schemas to draft-07 (using [json-schema-migrate](https://github.com/epoberezkin/json-schema-migrate))
|
||||
- validating data file(s) against JSON Schema
|
||||
- testing expected validity of data against JSON Schema
|
||||
- referenced schemas
|
||||
- custom meta-schemas
|
||||
- files in JSON and JavaScript format
|
||||
- files in JSON, JSON5, YAML, and JavaScript format
|
||||
- all Ajv options
|
||||
- reporting changes in data after validation in [JSON-patch](https://tools.ietf.org/html/rfc6902) format
|
||||
|
||||
@@ -257,20 +269,20 @@ CLI is available as a separate npm package [ajv-cli](https://github.com/jessedc/
|
||||
|
||||
Ajv supports all validation keywords from draft-07 of JSON Schema standard:
|
||||
|
||||
- [type](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#type)
|
||||
- [for numbers](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf
|
||||
- [for strings](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-strings) - maxLength, minLength, pattern, format
|
||||
- [for arrays](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-arrays) - maxItems, minItems, uniqueItems, items, additionalItems, [contains](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#contains)
|
||||
- [for objects](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minProperties, required, properties, patternProperties, additionalProperties, dependencies, [propertyNames](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#propertynames)
|
||||
- [for all types](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, [const](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#const)
|
||||
- [compound keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf, [if/then/else](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#ifthenelse)
|
||||
- [type](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#type)
|
||||
- [for numbers](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf
|
||||
- [for strings](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-strings) - maxLength, minLength, pattern, format
|
||||
- [for arrays](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-arrays) - maxItems, minItems, uniqueItems, items, additionalItems, [contains](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#contains)
|
||||
- [for objects](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minProperties, required, properties, patternProperties, additionalProperties, dependencies, [propertyNames](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#propertynames)
|
||||
- [for all types](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, [const](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#const)
|
||||
- [compound keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf, [if/then/else](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#ifthenelse)
|
||||
|
||||
With [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package Ajv also supports validation keywords from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON Schema standard:
|
||||
With [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package Ajv also supports validation keywords from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON Schema standard:
|
||||
|
||||
- [patternRequired](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#patternrequired-proposed) - like `required` but with patterns that some property should match.
|
||||
- [formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#formatmaximum--formatminimum-and-exclusiveformatmaximum--exclusiveformatminimum-proposed) - setting limits for date, time, etc.
|
||||
- [patternRequired](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#patternrequired-proposed) - like `required` but with patterns that some property should match.
|
||||
- [formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#formatmaximum--formatminimum-and-exclusiveformatmaximum--exclusiveformatminimum-proposed) - setting limits for date, time, etc.
|
||||
|
||||
See [JSON Schema validation keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md) for more details.
|
||||
See [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md) for more details.
|
||||
|
||||
|
||||
## Annotation keywords
|
||||
@@ -320,7 +332,7 @@ You can add additional formats and replace any of the formats above using [addFo
|
||||
|
||||
The option `unknownFormats` allows changing the default behaviour when an unknown format is encountered. In this case Ajv can either fail schema compilation (default) or ignore it (default in versions before 5.0.0). You also can whitelist specific format(s) to be ignored. See [Options](#options) for details.
|
||||
|
||||
You can find regular expressions used for format validation and the sources that were used in [formats.js](https://github.com/epoberezkin/ajv/blob/master/lib/compile/formats.js).
|
||||
You can find regular expressions used for format validation and the sources that were used in [formats.js](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js).
|
||||
|
||||
|
||||
## <a name="ref"></a>Combining schemas with $ref
|
||||
@@ -429,7 +441,7 @@ var validData = {
|
||||
|
||||
## $merge and $patch keywords
|
||||
|
||||
With the package [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) you can use the keywords `$merge` and `$patch` that allow extending JSON Schemas with patches using formats [JSON Merge Patch (RFC 7396)](https://tools.ietf.org/html/rfc7396) and [JSON Patch (RFC 6902)](https://tools.ietf.org/html/rfc6902).
|
||||
With the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) you can use the keywords `$merge` and `$patch` that allow extending JSON Schemas with patches using formats [JSON Merge Patch (RFC 7396)](https://tools.ietf.org/html/rfc7396) and [JSON Patch (RFC 6902)](https://tools.ietf.org/html/rfc6902).
|
||||
|
||||
To add keywords `$merge` and `$patch` to Ajv instance use this code:
|
||||
|
||||
@@ -488,7 +500,7 @@ The schemas above are equivalent to this schema:
|
||||
|
||||
The properties `source` and `with` in the keywords `$merge` and `$patch` can use absolute or relative `$ref` to point to other schemas previously added to the Ajv instance or to the fragments of the current schema.
|
||||
|
||||
See the package [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) for more information.
|
||||
See the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) for more information.
|
||||
|
||||
|
||||
## Defining custom keywords
|
||||
@@ -536,9 +548,9 @@ console.log(validate(2)); // false
|
||||
console.log(validate(4)); // false
|
||||
```
|
||||
|
||||
Several custom keywords (typeof, instanceof, range and propertyNames) are defined in [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package - they can be used for your schemas and as a starting point for your own custom keywords.
|
||||
Several custom keywords (typeof, instanceof, range and propertyNames) are defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - they can be used for your schemas and as a starting point for your own custom keywords.
|
||||
|
||||
See [Defining custom keywords](https://github.com/epoberezkin/ajv/blob/master/CUSTOM.md) for more details.
|
||||
See [Defining custom keywords](https://github.com/ajv-validator/ajv/blob/master/CUSTOM.md) for more details.
|
||||
|
||||
|
||||
## Asynchronous schema compilation
|
||||
@@ -637,7 +649,7 @@ validate({ userId: 1, postId: 19 })
|
||||
|
||||
### Using transpilers with asynchronous validation functions.
|
||||
|
||||
[ajv-async](https://github.com/epoberezkin/ajv-async) uses [nodent](https://github.com/MatAtBread/nodent) to transpile async functions. To use another transpiler you should separately install it (or load its bundle in the browser).
|
||||
[ajv-async](https://github.com/ajv-validator/ajv-async) uses [nodent](https://github.com/MatAtBread/nodent) to transpile async functions. To use another transpiler you should separately install it (or load its bundle in the browser).
|
||||
|
||||
|
||||
#### Using nodent
|
||||
@@ -681,7 +693,7 @@ Ajv treats JSON schemas as trusted as your application code. This security model
|
||||
|
||||
If your schemas are received from untrusted sources (or generated from untrusted data) there are several scenarios you need to prevent:
|
||||
- compiling schemas can cause stack overflow (if they are too deep)
|
||||
- compiling schemas can be slow (e.g. [#557](https://github.com/epoberezkin/ajv/issues/557))
|
||||
- compiling schemas can be slow (e.g. [#557](https://github.com/ajv-validator/ajv/issues/557))
|
||||
- validating certain data can be slow
|
||||
|
||||
It is difficult to predict all the scenarios, but at the very least it may help to limit the size of untrusted schemas (e.g. limit JSON string length) and also the maximum schema object depth (that can be high for relatively small JSON strings). You also may want to mitigate slow regular expressions in `pattern` and `patternProperties` keywords.
|
||||
@@ -691,7 +703,7 @@ Regardless the measures you take, using untrusted schemas increases security ris
|
||||
|
||||
##### Circular references in JavaScript objects
|
||||
|
||||
Ajv does not support schemas and validated data that have circular references in objects. See [issue #802](https://github.com/epoberezkin/ajv/issues/802).
|
||||
Ajv does not support schemas and validated data that have circular references in objects. See [issue #802](https://github.com/ajv-validator/ajv/issues/802).
|
||||
|
||||
An attempt to compile such schemas or validate such data would cause stack overflow (or will not complete in case of asynchronous validation). Depending on the parser you use, untrusted data can lead to circular references.
|
||||
|
||||
@@ -706,7 +718,7 @@ Some keywords in JSON Schemas can lead to very slow validation for certain data.
|
||||
|
||||
__Please note__: The suggestions above to prevent slow validation would only work if you do NOT use `allErrors: true` in production code (using it would continue validation after validation errors).
|
||||
|
||||
You can validate your JSON schemas against [this meta-schema](https://github.com/epoberezkin/ajv/blob/master/lib/refs/json-schema-secure.json) to check that these recommendations are followed:
|
||||
You can validate your JSON schemas against [this meta-schema](https://github.com/ajv-validator/ajv/blob/master/lib/refs/json-schema-secure.json) to check that these recommendations are followed:
|
||||
|
||||
```javascript
|
||||
const isSchemaSecure = ajv.compile(require('ajv/lib/refs/json-schema-secure.json'));
|
||||
@@ -721,13 +733,17 @@ isSchemaSecure(schema2); // true
|
||||
__Please note__: following all these recommendation is not a guarantee that validation of untrusted data is safe - it can still lead to some undesirable results.
|
||||
|
||||
|
||||
##### Content Security Policies (CSP)
|
||||
See [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp)
|
||||
|
||||
|
||||
## ReDoS attack
|
||||
|
||||
Certain regular expressions can lead to the exponential evaluation time even with relatively short strings.
|
||||
|
||||
Please assess the regular expressions you use in the schemas on their vulnerability to this attack - see [safe-regex](https://github.com/substack/safe-regex), for example.
|
||||
|
||||
__Please note__: some formats that Ajv implements use [regular expressions](https://github.com/epoberezkin/ajv/blob/master/lib/compile/formats.js) that can be vulnerable to ReDoS attack, so if you use Ajv to validate data from untrusted sources __it is strongly recommended__ to consider the following:
|
||||
__Please note__: some formats that Ajv implements use [regular expressions](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js) that can be vulnerable to ReDoS attack, so if you use Ajv to validate data from untrusted sources __it is strongly recommended__ to consider the following:
|
||||
|
||||
- making assessment of "format" implementations in Ajv.
|
||||
- using `format: 'fast'` option that simplifies some of the regular expressions (although it does not guarantee that they are safe).
|
||||
@@ -807,7 +823,7 @@ The intention of the schema above is to allow objects with either the string pro
|
||||
|
||||
With the option `removeAdditional: true` the validation will pass for the object `{ "foo": "abc"}` but will fail for the object `{"bar": 1}`. It happens because while the first subschema in `oneOf` is validated, the property `bar` is removed because it is an additional property according to the standard (because it is not included in `properties` keyword in the same schema).
|
||||
|
||||
While this behaviour is unexpected (issues [#129](https://github.com/epoberezkin/ajv/issues/129), [#134](https://github.com/epoberezkin/ajv/issues/134)), it is correct. To have the expected behaviour (both objects are allowed and additional properties are removed) the schema has to be refactored in this way:
|
||||
While this behaviour is unexpected (issues [#129](https://github.com/ajv-validator/ajv/issues/129), [#134](https://github.com/ajv-validator/ajv/issues/134)), it is correct. To have the expected behaviour (both objects are allowed and additional properties are removed) the schema has to be refactored in this way:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -881,7 +897,7 @@ console.log(data); // [ 1, "foo" ]
|
||||
`default` keywords in other cases are ignored:
|
||||
|
||||
- not in `properties` or `items` subschemas
|
||||
- in schemas inside `anyOf`, `oneOf` and `not` (see [#42](https://github.com/epoberezkin/ajv/issues/42))
|
||||
- in schemas inside `anyOf`, `oneOf` and `not` (see [#42](https://github.com/ajv-validator/ajv/issues/42))
|
||||
- in `if` subschema of `switch` keyword
|
||||
- in schemas generated by custom macro keywords
|
||||
|
||||
@@ -939,7 +955,7 @@ console.log(data); // { "foo": [1], "bar": false }
|
||||
|
||||
The coercion rules, as you can see from the example, are different from JavaScript both to validate user input as expected and to have the coercion reversible (to correctly validate cases where different types are defined in subschemas of "anyOf" and other compound keywords).
|
||||
|
||||
See [Coercion rules](https://github.com/epoberezkin/ajv/blob/master/COERCION.md) for details.
|
||||
See [Coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md) for details.
|
||||
|
||||
|
||||
## API
|
||||
@@ -1057,9 +1073,9 @@ Function should return validation result as `true` or `false`.
|
||||
If object is passed it should have properties `validate`, `compare` and `async`:
|
||||
|
||||
- _validate_: a string, RegExp or a function as described above.
|
||||
- _compare_: an optional comparison function that accepts two strings and compares them according to the format meaning. This function is used with keywords `formatMaximum`/`formatMinimum` (defined in [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package). It should return `1` if the first value is bigger than the second value, `-1` if it is smaller and `0` if it is equal.
|
||||
- _compare_: an optional comparison function that accepts two strings and compares them according to the format meaning. This function is used with keywords `formatMaximum`/`formatMinimum` (defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package). It should return `1` if the first value is bigger than the second value, `-1` if it is smaller and `0` if it is equal.
|
||||
- _async_: an optional `true` value if `validate` is an asynchronous function; in this case it should return a promise that resolves with a value `true` or `false`.
|
||||
- _type_: an optional type of data that the format applies to. It can be `"string"` (default) or `"number"` (see https://github.com/epoberezkin/ajv/issues/291#issuecomment-259923858). If the type of data is different, the validation will pass.
|
||||
- _type_: an optional type of data that the format applies to. It can be `"string"` (default) or `"number"` (see https://github.com/ajv-validator/ajv/issues/291#issuecomment-259923858). If the type of data is different, the validation will pass.
|
||||
|
||||
Custom formats can be also added via `formats` option.
|
||||
|
||||
@@ -1155,6 +1171,7 @@ Defaults:
|
||||
// strict mode options
|
||||
strictDefaults: false,
|
||||
strictKeywords: false,
|
||||
strictNumbers: false,
|
||||
// asynchronous validation options:
|
||||
transpile: undefined, // requires ajv-async package
|
||||
// advanced options:
|
||||
@@ -1169,7 +1186,7 @@ Defaults:
|
||||
errorDataPath: 'object', // deprecated
|
||||
messages: true,
|
||||
sourceCode: false,
|
||||
processCode: undefined, // function (str: string): string {}
|
||||
processCode: undefined, // function (str: string, schema: object): string {}
|
||||
cache: new Cache,
|
||||
serialize: undefined
|
||||
}
|
||||
@@ -1233,7 +1250,7 @@ Defaults:
|
||||
- `true` - insert defaults by value (object literal is used).
|
||||
- `"empty"` - in addition to missing or undefined, use defaults for properties and items that are 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/ajv-validator/ajv/blob/master/COERCION.md). Option values:
|
||||
- `false` (default) - no type coercion.
|
||||
- `true` - coerce scalar data types.
|
||||
- `"array"` - in addition to coercions between scalar types, coerce scalar data to an array with one element and vice versa (as required by the schema).
|
||||
@@ -1249,11 +1266,13 @@ Defaults:
|
||||
- `false` (default) - unknown keywords are not reported
|
||||
- `true` - if an unknown keyword is present, throw an error
|
||||
- `"log"` - if an unknown keyword is present, log warning
|
||||
|
||||
- _strictNumbers_: validate numbers strictly, failing validation for NaN and Infinity. Option values:
|
||||
- `false` (default) - NaN or Infinity will pass validation for numeric types
|
||||
- `true` - NaN or Infinity will not pass validation for numeric types
|
||||
|
||||
##### Asynchronous validation options
|
||||
|
||||
- _transpile_: Requires [ajv-async](https://github.com/epoberezkin/ajv-async) package. It determines whether Ajv transpiles compiled asynchronous validation function. Option values:
|
||||
- _transpile_: Requires [ajv-async](https://github.com/ajv-validator/ajv-async) package. It determines whether Ajv transpiles compiled asynchronous validation function. Option values:
|
||||
- `undefined` (default) - transpile with [nodent](https://github.com/MatAtBread/nodent) if async functions are not supported.
|
||||
- `true` - always transpile with nodent.
|
||||
- `false` - do not transpile; if async functions are not supported an exception will be thrown.
|
||||
@@ -1274,13 +1293,13 @@ Defaults:
|
||||
- _passContext_: pass validation context to custom keyword functions. If this option is `true` and you pass some context to the compiled validation function with `validate.call(context, data)`, the `context` will be available as `this` in your custom keywords. By default `this` is Ajv instance.
|
||||
- _loopRequired_: by default `required` keyword is compiled into a single expression (or a sequence of statements in `allErrors` mode). In case of a very large number of properties in this keyword it may result in a very big validation function. Pass integer to set the number of properties above which `required` keyword will be validated in a loop - smaller validation function size but also worse performance.
|
||||
- _ownProperties_: by default Ajv iterates over all enumerable object properties; when this option is `true` only own enumerable object properties (i.e. found directly on the object rather than on its prototype) are iterated. Contributed by @mbroadst.
|
||||
- _multipleOfPrecision_: by default `multipleOf` keyword is validated by comparing the result of division with parseInt() of that result. It works for dividers that are bigger than 1. For small dividers such as 0.01 the result of the division is usually not integer (even when it should be integer, see issue [#84](https://github.com/epoberezkin/ajv/issues/84)). If you need to use fractional dividers set this option to some positive integer N to have `multipleOf` validated using this formula: `Math.abs(Math.round(division) - division) < 1e-N` (it is slower but allows for float arithmetics deviations).
|
||||
- _multipleOfPrecision_: by default `multipleOf` keyword is validated by comparing the result of division with parseInt() of that result. It works for dividers that are bigger than 1. For small dividers such as 0.01 the result of the division is usually not integer (even when it should be integer, see issue [#84](https://github.com/ajv-validator/ajv/issues/84)). If you need to use fractional dividers set this option to some positive integer N to have `multipleOf` validated using this formula: `Math.abs(Math.round(division) - division) < 1e-N` (it is slower but allows for float arithmetics deviations).
|
||||
- _errorDataPath_ (deprecated): set `dataPath` to point to 'object' (default) or to 'property' when validating keywords `required`, `additionalProperties` and `dependencies`.
|
||||
- _messages_: Include human-readable messages in errors. `true` by default. `false` can be passed when custom messages are used (e.g. with [ajv-i18n](https://github.com/epoberezkin/ajv-i18n)).
|
||||
- _messages_: Include human-readable messages in errors. `true` by default. `false` can be passed when custom messages are used (e.g. with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n)).
|
||||
- _sourceCode_: add `sourceCode` property to validating function (for debugging; this code can be different from the result of toString call).
|
||||
- _processCode_: an optional function to process generated code before it is passed to Function constructor. It can be used to either beautify (the validating function is generated without line-breaks) or to transpile code. Starting from version 5.0.0 this option replaced options:
|
||||
- `beautify` that formatted the generated function using [js-beautify](https://github.com/beautify-web/js-beautify). If you want to beautify the generated code pass `require('js-beautify').js_beautify`.
|
||||
- `transpile` that transpiled asynchronous validation function. You can still use `transpile` option with [ajv-async](https://github.com/epoberezkin/ajv-async) package. See [Asynchronous validation](#asynchronous-validation) for more information.
|
||||
- `beautify` that formatted the generated function using [js-beautify](https://github.com/beautify-web/js-beautify). If you want to beautify the generated code pass a function calling `require('js-beautify').js_beautify` as `processCode: code => js_beautify(code)`.
|
||||
- `transpile` that transpiled asynchronous validation function. You can still use `transpile` option with [ajv-async](https://github.com/ajv-validator/ajv-async) package. See [Asynchronous validation](#asynchronous-validation) for more information.
|
||||
- _cache_: an optional instance of cache to store compiled schemas using stable-stringified schema as a key. For example, set-associative cache [sacjs](https://github.com/epoberezkin/sacjs) can be used. If not passed then a simple hash is used which is good enough for the common use case (a limited number of statically defined schemas). Cache should have methods `put(key, value)`, `get(key)`, `del(key)` and `clear()`.
|
||||
- _serialize_: an optional function to serialize schema to cache key. Pass `false` to use schema itself as a key (e.g., if WeakMap used as a cache). By default [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used.
|
||||
|
||||
@@ -1297,7 +1316,7 @@ Each error is an object with the following properties:
|
||||
- _keyword_: validation keyword.
|
||||
- _dataPath_: the path to the part of the data that was validated. By default `dataPath` uses JavaScript property access notation (e.g., `".prop[1].subProp"`). When the option `jsonPointers` is true (see [Options](#options)) `dataPath` will be set using JSON pointer standard (e.g., `"/prop/1/subProp"`).
|
||||
- _schemaPath_: the path (JSON-pointer as a URI fragment) to the schema of the keyword that failed validation.
|
||||
- _params_: the object with the additional information about error that can be used to create custom error messages (e.g., using [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) package). See below for parameters set by all keywords.
|
||||
- _params_: the object with the additional information about error that can be used to create custom error messages (e.g., using [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package). See below for parameters set by all keywords.
|
||||
- _message_: the standard error message (can be excluded with option `messages` set to false).
|
||||
- _schema_: the schema of the keyword (added with `verbose` option).
|
||||
- _parentSchema_: the schema containing the keyword (added with `verbose` option)
|
||||
@@ -1372,15 +1391,15 @@ If you have published a useful plugin please submit a PR to add it to the next s
|
||||
|
||||
## Related packages
|
||||
|
||||
- [ajv-async](https://github.com/epoberezkin/ajv-async) - plugin to configure async validation mode
|
||||
- [ajv-async](https://github.com/ajv-validator/ajv-async) - plugin to configure async validation mode
|
||||
- [ajv-bsontype](https://github.com/BoLaMN/ajv-bsontype) - plugin to validate mongodb's bsonType formats
|
||||
- [ajv-cli](https://github.com/jessedc/ajv-cli) - command line interface
|
||||
- [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-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 (select, typeof, etc.)
|
||||
- [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-errors](https://github.com/ajv-validator/ajv-errors) - plugin for custom error messages
|
||||
- [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) - internationalised error messages
|
||||
- [ajv-istanbul](https://github.com/ajv-validator/ajv-istanbul) - plugin to instrument generated validation code to measure test coverage of your schemas
|
||||
- [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) - plugin with custom validation keywords (select, typeof, etc.)
|
||||
- [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) - plugin with keywords $merge and $patch
|
||||
- [ajv-pack](https://github.com/ajv-validator/ajv-pack) - produces a compact module exporting validation functions
|
||||
- [ajv-formats-draft2019](https://github.com/luzlab/ajv-formats-draft2019) - format validators for draft2019 that aren't already included in ajv (ie. `idn-hostname`, `idn-email`, `iri`, `iri-reference` and `duration`).
|
||||
|
||||
## Some packages using Ajv
|
||||
@@ -1418,28 +1437,35 @@ npm test
|
||||
|
||||
## Contributing
|
||||
|
||||
All validation functions are generated using doT templates in [dot](https://github.com/epoberezkin/ajv/tree/master/lib/dot) folder. Templates are precompiled so doT is not a run-time dependency.
|
||||
All validation functions are generated using doT templates in [dot](https://github.com/ajv-validator/ajv/tree/master/lib/dot) folder. Templates are precompiled so doT is not a run-time dependency.
|
||||
|
||||
`npm run build` - compiles templates to [dotjs](https://github.com/epoberezkin/ajv/tree/master/lib/dotjs) folder.
|
||||
`npm run build` - compiles templates to [dotjs](https://github.com/ajv-validator/ajv/tree/master/lib/dotjs) folder.
|
||||
|
||||
`npm run watch` - automatically compiles templates when files in dot folder change
|
||||
|
||||
Please see [Contributing guidelines](https://github.com/epoberezkin/ajv/blob/master/CONTRIBUTING.md)
|
||||
Please see [Contributing guidelines](https://github.com/ajv-validator/ajv/blob/master/CONTRIBUTING.md)
|
||||
|
||||
|
||||
## Changes history
|
||||
|
||||
See https://github.com/epoberezkin/ajv/releases
|
||||
See https://github.com/ajv-validator/ajv/releases
|
||||
|
||||
__Please note__: [Changes in version 6.0.0](https://github.com/epoberezkin/ajv/releases/tag/v6.0.0).
|
||||
__Please note__: [Changes in version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0).
|
||||
|
||||
[Version 5.0.0](https://github.com/epoberezkin/ajv/releases/tag/5.0.0).
|
||||
[Version 5.0.0](https://github.com/ajv-validator/ajv/releases/tag/5.0.0).
|
||||
|
||||
[Version 4.0.0](https://github.com/epoberezkin/ajv/releases/tag/4.0.0).
|
||||
[Version 4.0.0](https://github.com/ajv-validator/ajv/releases/tag/4.0.0).
|
||||
|
||||
[Version 3.0.0](https://github.com/epoberezkin/ajv/releases/tag/3.0.0).
|
||||
[Version 3.0.0](https://github.com/ajv-validator/ajv/releases/tag/3.0.0).
|
||||
|
||||
[Version 2.0.0](https://github.com/epoberezkin/ajv/releases/tag/2.0.0).
|
||||
[Version 2.0.0](https://github.com/ajv-validator/ajv/releases/tag/2.0.0).
|
||||
|
||||
|
||||
## Code of conduct
|
||||
|
||||
Please review and follow the [Code of conduct](https://github.com/ajv-validator/ajv/blob/master/CODE_OF_CONDUCT.md).
|
||||
|
||||
Please report any unacceptable behaviour to ajv.validator@gmail.com - it will be reviewed by the project team.
|
||||
|
||||
|
||||
## Open-source software support
|
||||
@@ -1449,4 +1475,4 @@ Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/n
|
||||
|
||||
## License
|
||||
|
||||
[MIT](https://github.com/epoberezkin/ajv/blob/master/LICENSE)
|
||||
[MIT](https://github.com/ajv-validator/ajv/blob/master/LICENSE)
|
||||
+45
-67
@@ -414,7 +414,7 @@ function compile(schema, root, localRefs, baseId) {
|
||||
+ vars(defaults, defaultCode) + vars(customRules, customRuleCode)
|
||||
+ sourceCode;
|
||||
|
||||
if (opts.processCode) sourceCode = opts.processCode(sourceCode);
|
||||
if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema);
|
||||
// console.log('\n\n\n *** \n', JSON.stringify(sourceCode));
|
||||
var validate;
|
||||
try {
|
||||
@@ -1076,8 +1076,6 @@ module.exports = {
|
||||
ucs2length: require('./ucs2length'),
|
||||
varOccurences: varOccurences,
|
||||
varReplace: varReplace,
|
||||
cleanUpCode: cleanUpCode,
|
||||
finalCleanUpCode: finalCleanUpCode,
|
||||
schemaHasRules: schemaHasRules,
|
||||
schemaHasRulesExcept: schemaHasRulesExcept,
|
||||
schemaUnknownRules: schemaUnknownRules,
|
||||
@@ -1099,7 +1097,7 @@ function copy(o, to) {
|
||||
}
|
||||
|
||||
|
||||
function checkDataType(dataType, data, negate) {
|
||||
function checkDataType(dataType, data, strictNumbers, negate) {
|
||||
var EQUAL = negate ? ' !== ' : ' === '
|
||||
, AND = negate ? ' || ' : ' && '
|
||||
, OK = negate ? '!' : ''
|
||||
@@ -1112,15 +1110,18 @@ function checkDataType(dataType, data, negate) {
|
||||
NOT + 'Array.isArray(' + data + '))';
|
||||
case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
|
||||
NOT + '(' + data + ' % 1)' +
|
||||
AND + data + EQUAL + data + ')';
|
||||
AND + data + EQUAL + data +
|
||||
(strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
|
||||
case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' +
|
||||
(strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
|
||||
default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function checkDataTypes(dataTypes, data) {
|
||||
function checkDataTypes(dataTypes, data, strictNumbers) {
|
||||
switch (dataTypes.length) {
|
||||
case 1: return checkDataType(dataTypes[0], data, true);
|
||||
case 1: return checkDataType(dataTypes[0], data, strictNumbers, true);
|
||||
default:
|
||||
var code = '';
|
||||
var types = toHash(dataTypes);
|
||||
@@ -1133,7 +1134,7 @@ function checkDataTypes(dataTypes, data) {
|
||||
}
|
||||
if (types.number) delete types.integer;
|
||||
for (var t in types)
|
||||
code += (code ? ' && ' : '' ) + checkDataType(t, data, true);
|
||||
code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true);
|
||||
|
||||
return code;
|
||||
}
|
||||
@@ -1199,42 +1200,6 @@ function varReplace(str, dataVar, expr) {
|
||||
}
|
||||
|
||||
|
||||
var EMPTY_ELSE = /else\s*{\s*}/g
|
||||
, EMPTY_IF_NO_ELSE = /if\s*\([^)]+\)\s*\{\s*\}(?!\s*else)/g
|
||||
, EMPTY_IF_WITH_ELSE = /if\s*\(([^)]+)\)\s*\{\s*\}\s*else(?!\s*if)/g;
|
||||
function cleanUpCode(out) {
|
||||
return out.replace(EMPTY_ELSE, '')
|
||||
.replace(EMPTY_IF_NO_ELSE, '')
|
||||
.replace(EMPTY_IF_WITH_ELSE, 'if (!($1))');
|
||||
}
|
||||
|
||||
|
||||
var ERRORS_REGEXP = /[^v.]errors/g
|
||||
, REMOVE_ERRORS = /var errors = 0;|var vErrors = null;|validate.errors = vErrors;/g
|
||||
, REMOVE_ERRORS_ASYNC = /var errors = 0;|var vErrors = null;/g
|
||||
, RETURN_VALID = 'return errors === 0;'
|
||||
, RETURN_TRUE = 'validate.errors = null; return true;'
|
||||
, RETURN_ASYNC = /if \(errors === 0\) return data;\s*else throw new ValidationError\(vErrors\);/
|
||||
, RETURN_DATA_ASYNC = 'return data;'
|
||||
, ROOTDATA_REGEXP = /[^A-Za-z_$]rootData[^A-Za-z0-9_$]/g
|
||||
, REMOVE_ROOTDATA = /if \(rootData === undefined\) rootData = data;/;
|
||||
|
||||
function finalCleanUpCode(out, async) {
|
||||
var matches = out.match(ERRORS_REGEXP);
|
||||
if (matches && matches.length == 2) {
|
||||
out = async
|
||||
? out.replace(REMOVE_ERRORS_ASYNC, '')
|
||||
.replace(RETURN_ASYNC, RETURN_DATA_ASYNC)
|
||||
: out.replace(REMOVE_ERRORS, '')
|
||||
.replace(RETURN_VALID, RETURN_TRUE);
|
||||
}
|
||||
|
||||
matches = out.match(ROOTDATA_REGEXP);
|
||||
if (!matches || matches.length !== 3) return out;
|
||||
return out.replace(REMOVE_ROOTDATA, '');
|
||||
}
|
||||
|
||||
|
||||
function schemaHasRules(schema, rules) {
|
||||
if (typeof schema == 'boolean') return !schema;
|
||||
for (var key in schema) if (rules[key]) return true;
|
||||
@@ -1313,7 +1278,7 @@ function getData($data, lvl, paths) {
|
||||
|
||||
function joinPaths (a, b) {
|
||||
if (a == '""') return b;
|
||||
return (a + ' + ' + b).replace(/' \+ '/g, '');
|
||||
return (a + ' + ' + b).replace(/([^\\])' \+ '/g, '$1');
|
||||
}
|
||||
|
||||
|
||||
@@ -1377,7 +1342,7 @@ module.exports = function (metaSchema, keywordsJsonPointers) {
|
||||
keywords[key] = {
|
||||
anyOf: [
|
||||
schema,
|
||||
{ $ref: 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#' }
|
||||
{ $ref: 'https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#' }
|
||||
]
|
||||
};
|
||||
}
|
||||
@@ -1393,7 +1358,7 @@ module.exports = function (metaSchema, keywordsJsonPointers) {
|
||||
var metaSchema = require('./refs/json-schema-draft-07.json');
|
||||
|
||||
module.exports = {
|
||||
$id: 'https://github.com/epoberezkin/ajv/blob/master/lib/definition_schema.js',
|
||||
$id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js',
|
||||
definitions: {
|
||||
simpleTypes: metaSchema.definitions.simpleTypes
|
||||
},
|
||||
@@ -1453,6 +1418,12 @@ module.exports = function generate__limit(it, $keyword, $ruleType) {
|
||||
$op = $isMax ? '<' : '>',
|
||||
$notOp = $isMax ? '>' : '<',
|
||||
$errorKeyword = undefined;
|
||||
if (!($isData || typeof $schema == 'number' || $schema === undefined)) {
|
||||
throw new Error($keyword + ' must be number');
|
||||
}
|
||||
if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) {
|
||||
throw new Error($exclusiveKeyword + ' must be number or boolean');
|
||||
}
|
||||
if ($isDataExcl) {
|
||||
var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),
|
||||
$exclusive = 'exclusive' + $lvl,
|
||||
@@ -1605,6 +1576,9 @@ module.exports = function generate__limitItems(it, $keyword, $ruleType) {
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
if (!($isData || typeof $schema == 'number')) {
|
||||
throw new Error($keyword + ' must be number');
|
||||
}
|
||||
var $op = $keyword == 'maxItems' ? '>' : '<';
|
||||
out += 'if ( ';
|
||||
if ($isData) {
|
||||
@@ -1684,6 +1658,9 @@ module.exports = function generate__limitLength(it, $keyword, $ruleType) {
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
if (!($isData || typeof $schema == 'number')) {
|
||||
throw new Error($keyword + ' must be number');
|
||||
}
|
||||
var $op = $keyword == 'maxLength' ? '>' : '<';
|
||||
out += 'if ( ';
|
||||
if ($isData) {
|
||||
@@ -1768,6 +1745,9 @@ module.exports = function generate__limitProperties(it, $keyword, $ruleType) {
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
if (!($isData || typeof $schema == 'number')) {
|
||||
throw new Error($keyword + ' must be number');
|
||||
}
|
||||
var $op = $keyword == 'maxProperties' ? '>' : '<';
|
||||
out += 'if ( ';
|
||||
if ($isData) {
|
||||
@@ -1868,7 +1848,6 @@ module.exports = function generate_allOf(it, $keyword, $ruleType) {
|
||||
out += ' ' + ($closingBraces.slice(0, -1)) + ' ';
|
||||
}
|
||||
}
|
||||
out = it.util.cleanUpCode(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -1939,7 +1918,6 @@ module.exports = function generate_anyOf(it, $keyword, $ruleType) {
|
||||
if (it.opts.allErrors) {
|
||||
out += ' } ';
|
||||
}
|
||||
out = it.util.cleanUpCode(out);
|
||||
} else {
|
||||
if ($breakOnError) {
|
||||
out += ' if (true) { ';
|
||||
@@ -2102,7 +2080,6 @@ module.exports = function generate_contains(it, $keyword, $ruleType) {
|
||||
if (it.opts.allErrors) {
|
||||
out += ' } ';
|
||||
}
|
||||
out = it.util.cleanUpCode(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -2356,6 +2333,7 @@ module.exports = function generate_dependencies(it, $keyword, $ruleType) {
|
||||
$propertyDeps = {},
|
||||
$ownProperties = it.opts.ownProperties;
|
||||
for ($property in $schema) {
|
||||
if ($property == '__proto__') continue;
|
||||
var $sch = $schema[$property];
|
||||
var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
|
||||
$deps[$property] = $sch;
|
||||
@@ -2502,7 +2480,6 @@ module.exports = function generate_dependencies(it, $keyword, $ruleType) {
|
||||
if ($breakOnError) {
|
||||
out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
|
||||
}
|
||||
out = it.util.cleanUpCode(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -2823,7 +2800,6 @@ module.exports = function generate_if(it, $keyword, $ruleType) {
|
||||
if ($breakOnError) {
|
||||
out += ' else { ';
|
||||
}
|
||||
out = it.util.cleanUpCode(out);
|
||||
} else {
|
||||
if ($breakOnError) {
|
||||
out += ' if (true) { ';
|
||||
@@ -3006,7 +2982,6 @@ module.exports = function generate_items(it, $keyword, $ruleType) {
|
||||
if ($breakOnError) {
|
||||
out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
|
||||
}
|
||||
out = it.util.cleanUpCode(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -3029,6 +3004,9 @@ module.exports = function generate_multipleOf(it, $keyword, $ruleType) {
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
if (!($isData || typeof $schema == 'number')) {
|
||||
throw new Error($keyword + ' must be number');
|
||||
}
|
||||
out += 'var division' + ($lvl) + ';if (';
|
||||
if ($isData) {
|
||||
out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || ';
|
||||
@@ -3348,9 +3326,9 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
|
||||
$dataNxt = $it.dataLevel = it.dataLevel + 1,
|
||||
$nextData = 'data' + $dataNxt,
|
||||
$dataProperties = 'dataProperties' + $lvl;
|
||||
var $schemaKeys = Object.keys($schema || {}),
|
||||
var $schemaKeys = Object.keys($schema || {}).filter(notProto),
|
||||
$pProperties = it.schema.patternProperties || {},
|
||||
$pPropertyKeys = Object.keys($pProperties),
|
||||
$pPropertyKeys = Object.keys($pProperties).filter(notProto),
|
||||
$aProperties = it.schema.additionalProperties,
|
||||
$someProperties = $schemaKeys.length || $pPropertyKeys.length,
|
||||
$noAdditional = $aProperties === false,
|
||||
@@ -3360,7 +3338,13 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
|
||||
$ownProperties = it.opts.ownProperties,
|
||||
$currentBaseId = it.baseId;
|
||||
var $required = it.schema.required;
|
||||
if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required);
|
||||
if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) {
|
||||
var $requiredHash = it.util.toHash($required);
|
||||
}
|
||||
|
||||
function notProto(p) {
|
||||
return p !== '__proto__';
|
||||
}
|
||||
out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;';
|
||||
if ($ownProperties) {
|
||||
out += ' var ' + ($dataProperties) + ' = undefined;';
|
||||
@@ -3655,7 +3639,6 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
|
||||
if ($breakOnError) {
|
||||
out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
|
||||
}
|
||||
out = it.util.cleanUpCode(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -3739,7 +3722,6 @@ module.exports = function generate_propertyNames(it, $keyword, $ruleType) {
|
||||
if ($breakOnError) {
|
||||
out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
|
||||
}
|
||||
out = it.util.cleanUpCode(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -4173,7 +4155,7 @@ module.exports = function generate_uniqueItems(it, $keyword, $ruleType) {
|
||||
} else {
|
||||
out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; ';
|
||||
var $method = 'checkDataType' + ($typeIsArray ? 's' : '');
|
||||
out += ' if (' + (it.util[$method]($itemType, 'item', true)) + ') continue; ';
|
||||
out += ' if (' + (it.util[$method]($itemType, 'item', it.opts.strictNumbers, true)) + ') continue; ';
|
||||
if ($typeIsArray) {
|
||||
out += ' if (typeof item == \'string\') item = \'"\' + item; ';
|
||||
}
|
||||
@@ -4381,7 +4363,7 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
|
||||
var $schemaPath = it.schemaPath + '.type',
|
||||
$errSchemaPath = it.errSchemaPath + '/type',
|
||||
$method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
|
||||
out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { ';
|
||||
out += ' if (' + (it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true)) + ') { ';
|
||||
if ($coerceToTypes) {
|
||||
var $dataType = 'dataType' + $lvl,
|
||||
$coerced = 'coerced' + $lvl;
|
||||
@@ -4534,7 +4516,7 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
|
||||
$rulesGroup = arr2[i2 += 1];
|
||||
if ($shouldUseGroup($rulesGroup)) {
|
||||
if ($rulesGroup.type) {
|
||||
out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data)) + ') { ';
|
||||
out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers)) + ') { ';
|
||||
}
|
||||
if (it.opts.useDefaults) {
|
||||
if ($rulesGroup.type == 'object' && it.schema.properties) {
|
||||
@@ -4702,10 +4684,6 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
|
||||
} else {
|
||||
out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';
|
||||
}
|
||||
out = it.util.cleanUpCode(out);
|
||||
if ($top) {
|
||||
out = it.util.finalCleanUpCode(out, $async);
|
||||
}
|
||||
|
||||
function $shouldUseGroup($rulesGroup) {
|
||||
var rules = $rulesGroup.rules;
|
||||
@@ -4774,7 +4752,7 @@ function addKeyword(keyword, definition) {
|
||||
metaSchema = {
|
||||
anyOf: [
|
||||
metaSchema,
|
||||
{ '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#' }
|
||||
{ '$ref': 'https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#' }
|
||||
]
|
||||
};
|
||||
}
|
||||
@@ -4876,7 +4854,7 @@ function validateKeyword(definition, throwError) {
|
||||
},{"./definition_schema":12,"./dotjs/custom":22}],40:[function(require,module,exports){
|
||||
module.exports={
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$id": "https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#",
|
||||
"$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
|
||||
"description": "Meta-schema for $data reference (JSON Schema extension proposal)",
|
||||
"type": "object",
|
||||
"required": [ "$data" ],
|
||||
|
||||
+2
-2
@@ -1,3 +1,3 @@
|
||||
/* ajv 6.12.2: Another JSON Schema Validator */
|
||||
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Ajv=e()}}(function(){return function o(i,n,l){function c(r,e){if(!n[r]){if(!i[r]){var t="function"==typeof require&&require;if(!e&&t)return t(r,!0);if(u)return u(r,!0);var a=new Error("Cannot find module '"+r+"'");throw a.code="MODULE_NOT_FOUND",a}var s=n[r]={exports:{}};i[r][0].call(s.exports,function(e){return c(i[r][1][e]||e)},s,s.exports,o,i,n,l)}return n[r].exports}for(var u="function"==typeof require&&require,e=0;e<l.length;e++)c(l[e]);return c}({1:[function(e,r,t){"use strict";var a=r.exports=function(){this._cache={}};a.prototype.put=function(e,r){this._cache[e]=r},a.prototype.get=function(e){return this._cache[e]},a.prototype.del=function(e){delete this._cache[e]},a.prototype.clear=function(){this._cache={}}},{}],2:[function(e,r,t){"use strict";var a=e("./error_classes").MissingRef;function s(r,n,t){var l=this;if("function"!=typeof this._opts.loadSchema)throw new Error("options.loadSchema should be a function");"function"==typeof n&&(t=n,n=void 0);var e=c(r).then(function(){var e=l._addSchema(r,void 0,n);return e.validate||function o(i){try{return l._compile(i)}catch(e){if(e instanceof a)return r(e);throw e}function r(e){var r=e.missingSchema;if(s(r))throw new Error("Schema "+r+" is loaded but "+e.missingRef+" cannot be resolved");var t=l._loadingSchemas[r];return t||(t=l._loadingSchemas[r]=l._opts.loadSchema(r)).then(a,a),t.then(function(e){if(!s(r))return c(e).then(function(){s(r)||l.addSchema(e,r,void 0,n)})}).then(function(){return o(i)});function a(){delete l._loadingSchemas[r]}function s(e){return l._refs[e]||l._schemas[e]}}}(e)});return t&&e.then(function(e){t(null,e)},t),e;function c(e){var r=e.$schema;return r&&!l.getSchema(r)?s.call(l,{$ref:r},!0):Promise.resolve()}}r.exports=s},{"./error_classes":3}],3:[function(e,r,t){"use strict";var a=e("./resolve");function s(e,r,t){this.message=t||s.message(e,r),this.missingRef=a.url(e,r),this.missingSchema=a.normalizeId(a.fullPath(this.missingRef))}function o(e){return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e}r.exports={Validation:o(function(e){this.message="validation failed",this.errors=e,this.ajv=this.validation=!0}),MissingRef:o(s)},s.message=function(e,r){return"can't resolve reference "+r+" from id "+e}},{"./resolve":6}],4:[function(e,r,t){"use strict";var a=e("./util"),o=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31],n=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,s=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,l=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,c=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,u=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[Line truncated
|
||||
/* ajv 6.12.3: Another JSON Schema Validator */
|
||||
!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Ajv=e()}(function(){return function o(i,n,l){function c(r,e){if(!n[r]){if(!i[r]){var t="function"==typeof require&&require;if(!e&&t)return t(r,!0);if(u)return u(r,!0);var a=new Error("Cannot find module '"+r+"'");throw a.code="MODULE_NOT_FOUND",a}var s=n[r]={exports:{}};i[r][0].call(s.exports,function(e){return c(i[r][1][e]||e)},s,s.exports,o,i,n,l)}return n[r].exports}for(var u="function"==typeof require&&require,e=0;e<l.length;e++)c(l[e]);return c}({1:[function(e,r,t){"use strict";var a=r.exports=function(){this._cache={}};a.prototype.put=function(e,r){this._cache[e]=r},a.prototype.get=function(e){return this._cache[e]},a.prototype.del=function(e){delete this._cache[e]},a.prototype.clear=function(){this._cache={}}},{}],2:[function(e,r,t){"use strict";var a=e("./error_classes").MissingRef;function s(r,n,t){var l=this;if("function"!=typeof this._opts.loadSchema)throw new Error("options.loadSchema should be a function");"function"==typeof n&&(t=n,n=void 0);var e=c(r).then(function(){var e=l._addSchema(r,void 0,n);return e.validate||function o(i){try{return l._compile(i)}catch(e){if(e instanceof a)return r(e);throw e}function r(e){var r=e.missingSchema;if(s(r))throw new Error("Schema "+r+" is loaded but "+e.missingRef+" cannot be resolved");var t=l._loadingSchemas[r];return t||(t=l._loadingSchemas[r]=l._opts.loadSchema(r)).then(a,a),t.then(function(e){if(!s(r))return c(e).then(function(){s(r)||l.addSchema(e,r,void 0,n)})}).then(function(){return o(i)});function a(){delete l._loadingSchemas[r]}function s(e){return l._refs[e]||l._schemas[e]}}}(e)});return t&&e.then(function(e){t(null,e)},t),e;function c(e){var r=e.$schema;return r&&!l.getSchema(r)?s.call(l,{$ref:r},!0):Promise.resolve()}}r.exports=s},{"./error_classes":3}],3:[function(e,r,t){"use strict";var a=e("./resolve");function s(e,r,t){this.message=t||s.message(e,r),this.missingRef=a.url(e,r),this.missingSchema=a.normalizeId(a.fullPath(this.missingRef))}function o(e){return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e}r.exports={Validation:o(function(e){this.message="validation failed",this.errors=e,this.ajv=this.validation=!0}),MissingRef:o(s)},s.message=function(e,r){return"can't resolve reference "+r+" from id "+e}},{"./resolve":6}],4:[function(e,r,t){"use strict";var a=e("./util"),o=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31],n=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,s=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,l=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,c=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,u=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9KSa-z\xA1-\uD7Line truncated
|
||||
//# sourceMappingURL=ajv.min.js.map
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
|
||||
// do NOT remove this file - it would break pre-compiled schemas
|
||||
// https://github.com/epoberezkin/ajv/issues/889
|
||||
// https://github.com/ajv-validator/ajv/issues/889
|
||||
module.exports = require('fast-deep-equal');
|
||||
+1
-1
@@ -113,7 +113,7 @@ function compile(schema, root, localRefs, baseId) {
|
||||
+ vars(defaults, defaultCode) + vars(customRules, customRuleCode)
|
||||
+ sourceCode;
|
||||
|
||||
if (opts.processCode) sourceCode = opts.processCode(sourceCode);
|
||||
if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema);
|
||||
// console.log('\n\n\n *** \n', JSON.stringify(sourceCode));
|
||||
var validate;
|
||||
try {
|
||||
|
||||
+9
-44
@@ -13,8 +13,6 @@ module.exports = {
|
||||
ucs2length: require('./ucs2length'),
|
||||
varOccurences: varOccurences,
|
||||
varReplace: varReplace,
|
||||
cleanUpCode: cleanUpCode,
|
||||
finalCleanUpCode: finalCleanUpCode,
|
||||
schemaHasRules: schemaHasRules,
|
||||
schemaHasRulesExcept: schemaHasRulesExcept,
|
||||
schemaUnknownRules: schemaUnknownRules,
|
||||
@@ -36,7 +34,7 @@ function copy(o, to) {
|
||||
}
|
||||
|
||||
|
||||
function checkDataType(dataType, data, negate) {
|
||||
function checkDataType(dataType, data, strictNumbers, negate) {
|
||||
var EQUAL = negate ? ' !== ' : ' === '
|
||||
, AND = negate ? ' || ' : ' && '
|
||||
, OK = negate ? '!' : ''
|
||||
@@ -49,15 +47,18 @@ function checkDataType(dataType, data, negate) {
|
||||
NOT + 'Array.isArray(' + data + '))';
|
||||
case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
|
||||
NOT + '(' + data + ' % 1)' +
|
||||
AND + data + EQUAL + data + ')';
|
||||
AND + data + EQUAL + data +
|
||||
(strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
|
||||
case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' +
|
||||
(strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
|
||||
default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function checkDataTypes(dataTypes, data) {
|
||||
function checkDataTypes(dataTypes, data, strictNumbers) {
|
||||
switch (dataTypes.length) {
|
||||
case 1: return checkDataType(dataTypes[0], data, true);
|
||||
case 1: return checkDataType(dataTypes[0], data, strictNumbers, true);
|
||||
default:
|
||||
var code = '';
|
||||
var types = toHash(dataTypes);
|
||||
@@ -70,7 +71,7 @@ function checkDataTypes(dataTypes, data) {
|
||||
}
|
||||
if (types.number) delete types.integer;
|
||||
for (var t in types)
|
||||
code += (code ? ' && ' : '' ) + checkDataType(t, data, true);
|
||||
code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true);
|
||||
|
||||
return code;
|
||||
}
|
||||
@@ -136,42 +137,6 @@ function varReplace(str, dataVar, expr) {
|
||||
}
|
||||
|
||||
|
||||
var EMPTY_ELSE = /else\s*{\s*}/g
|
||||
, EMPTY_IF_NO_ELSE = /if\s*\([^)]+\)\s*\{\s*\}(?!\s*else)/g
|
||||
, EMPTY_IF_WITH_ELSE = /if\s*\(([^)]+)\)\s*\{\s*\}\s*else(?!\s*if)/g;
|
||||
function cleanUpCode(out) {
|
||||
return out.replace(EMPTY_ELSE, '')
|
||||
.replace(EMPTY_IF_NO_ELSE, '')
|
||||
.replace(EMPTY_IF_WITH_ELSE, 'if (!($1))');
|
||||
}
|
||||
|
||||
|
||||
var ERRORS_REGEXP = /[^v.]errors/g
|
||||
, REMOVE_ERRORS = /var errors = 0;|var vErrors = null;|validate.errors = vErrors;/g
|
||||
, REMOVE_ERRORS_ASYNC = /var errors = 0;|var vErrors = null;/g
|
||||
, RETURN_VALID = 'return errors === 0;'
|
||||
, RETURN_TRUE = 'validate.errors = null; return true;'
|
||||
, RETURN_ASYNC = /if \(errors === 0\) return data;\s*else throw new ValidationError\(vErrors\);/
|
||||
, RETURN_DATA_ASYNC = 'return data;'
|
||||
, ROOTDATA_REGEXP = /[^A-Za-z_$]rootData[^A-Za-z0-9_$]/g
|
||||
, REMOVE_ROOTDATA = /if \(rootData === undefined\) rootData = data;/;
|
||||
|
||||
function finalCleanUpCode(out, async) {
|
||||
var matches = out.match(ERRORS_REGEXP);
|
||||
if (matches && matches.length == 2) {
|
||||
out = async
|
||||
? out.replace(REMOVE_ERRORS_ASYNC, '')
|
||||
.replace(RETURN_ASYNC, RETURN_DATA_ASYNC)
|
||||
: out.replace(REMOVE_ERRORS, '')
|
||||
.replace(RETURN_VALID, RETURN_TRUE);
|
||||
}
|
||||
|
||||
matches = out.match(ROOTDATA_REGEXP);
|
||||
if (!matches || matches.length !== 3) return out;
|
||||
return out.replace(REMOVE_ROOTDATA, '');
|
||||
}
|
||||
|
||||
|
||||
function schemaHasRules(schema, rules) {
|
||||
if (typeof schema == 'boolean') return !schema;
|
||||
for (var key in schema) if (rules[key]) return true;
|
||||
@@ -250,7 +215,7 @@ function getData($data, lvl, paths) {
|
||||
|
||||
function joinPaths (a, b) {
|
||||
if (a == '""') return b;
|
||||
return (a + ' + ' + b).replace(/' \+ '/g, '');
|
||||
return (a + ' + ' + b).replace(/([^\\])' \+ '/g, '$1');
|
||||
}
|
||||
|
||||
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ module.exports = function (metaSchema, keywordsJsonPointers) {
|
||||
keywords[key] = {
|
||||
anyOf: [
|
||||
schema,
|
||||
{ $ref: 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#' }
|
||||
{ $ref: 'https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#' }
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
var metaSchema = require('./refs/json-schema-draft-07.json');
|
||||
|
||||
module.exports = {
|
||||
$id: 'https://github.com/epoberezkin/ajv/blob/master/lib/definition_schema.js',
|
||||
$id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js',
|
||||
definitions: {
|
||||
simpleTypes: metaSchema.definitions.simpleTypes
|
||||
},
|
||||
|
||||
+9
@@ -17,6 +17,15 @@
|
||||
, $op = $isMax ? '<' : '>'
|
||||
, $notOp = $isMax ? '>' : '<'
|
||||
, $errorKeyword = undefined;
|
||||
|
||||
if (!($isData || typeof $schema == 'number' || $schema === undefined)) {
|
||||
throw new Error($keyword + ' must be number');
|
||||
}
|
||||
if (!($isDataExcl || $schemaExcl === undefined
|
||||
|| typeof $schemaExcl == 'number'
|
||||
|| typeof $schemaExcl == 'boolean')) {
|
||||
throw new Error($exclusiveKeyword + ' must be number or boolean');
|
||||
}
|
||||
}}
|
||||
|
||||
{{? $isDataExcl }}
|
||||
|
||||
+2
@@ -3,6 +3,8 @@
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{# def.numberKeyword }}
|
||||
|
||||
{{ var $op = $keyword == 'maxItems' ? '>' : '<'; }}
|
||||
if ({{# def.$dataNotType:'number' }} {{=$data}}.length {{=$op}} {{=$schemaValue}}) {
|
||||
{{ var $errorKeyword = $keyword; }}
|
||||
|
||||
+2
@@ -3,6 +3,8 @@
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{# def.numberKeyword }}
|
||||
|
||||
{{ var $op = $keyword == 'maxLength' ? '>' : '<'; }}
|
||||
if ({{# def.$dataNotType:'number' }} {{# def.strLength }} {{=$op}} {{=$schemaValue}}) {
|
||||
{{ var $errorKeyword = $keyword; }}
|
||||
|
||||
+2
@@ -3,6 +3,8 @@
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{# def.numberKeyword }}
|
||||
|
||||
{{ var $op = $keyword == 'maxProperties' ? '>' : '<'; }}
|
||||
if ({{# def.$dataNotType:'number' }} Object.keys({{=$data}}).length {{=$op}} {{=$schemaValue}}) {
|
||||
{{ var $errorKeyword = $keyword; }}
|
||||
|
||||
-2
@@ -30,5 +30,3 @@
|
||||
{{= $closingBraces.slice(0,-1) }}
|
||||
{{?}}
|
||||
{{?}}
|
||||
|
||||
{{# def.cleanUp }}
|
||||
-2
@@ -39,8 +39,6 @@
|
||||
} else {
|
||||
{{# def.resetErrors }}
|
||||
{{? it.opts.allErrors }} } {{?}}
|
||||
|
||||
{{# def.cleanUp }}
|
||||
{{??}}
|
||||
{{? $breakOnError }}
|
||||
if (true) {
|
||||
|
||||
-2
@@ -53,5 +53,3 @@ var {{=$valid}};
|
||||
{{# def.resetErrors }}
|
||||
{{?}}
|
||||
{{? it.opts.allErrors }} } {{?}}
|
||||
|
||||
{{# def.cleanUp }}
|
||||
+7
-6
@@ -112,12 +112,6 @@
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.cleanUp: {{ out = it.util.cleanUpCode(out); }} #}}
|
||||
|
||||
|
||||
{{## def.finalCleanUp: {{ out = it.util.finalCleanUpCode(out, $async); }} #}}
|
||||
|
||||
|
||||
{{## def.$data:
|
||||
{{
|
||||
var $isData = it.opts.$data && $schema && $schema.$data
|
||||
@@ -144,6 +138,13 @@
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.numberKeyword:
|
||||
{{? !($isData || typeof $schema == 'number') }}
|
||||
{{ throw new Error($keyword + ' must be number'); }}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.beginDefOut:
|
||||
{{
|
||||
var $$outStack = $$outStack || [];
|
||||
|
||||
+1
-2
@@ -19,6 +19,7 @@
|
||||
, $ownProperties = it.opts.ownProperties;
|
||||
|
||||
for ($property in $schema) {
|
||||
if ($property == '__proto__') continue;
|
||||
var $sch = $schema[$property];
|
||||
var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
|
||||
$deps[$property] = $sch;
|
||||
@@ -76,5 +77,3 @@ var missing{{=$lvl}};
|
||||
{{= $closingBraces }}
|
||||
if ({{=$errs}} == errors) {
|
||||
{{?}}
|
||||
|
||||
{{# def.cleanUp }}
|
||||
-2
@@ -65,8 +65,6 @@
|
||||
{{# def.extraError:'if' }}
|
||||
}
|
||||
{{? $breakOnError }} else { {{?}}
|
||||
|
||||
{{# def.cleanUp }}
|
||||
{{??}}
|
||||
{{? $breakOnError }}
|
||||
if (true) {
|
||||
|
||||
-2
@@ -96,5 +96,3 @@ var {{=$valid}};
|
||||
{{= $closingBraces }}
|
||||
if ({{=$errs}} == errors) {
|
||||
{{?}}
|
||||
|
||||
{{# def.cleanUp }}
|
||||
+2
@@ -3,6 +3,8 @@
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{# def.numberKeyword }}
|
||||
|
||||
var division{{=$lvl}};
|
||||
if ({{?$isData}}
|
||||
{{=$schemaValue}} !== undefined && (
|
||||
|
||||
+6
-5
@@ -28,9 +28,9 @@
|
||||
, $nextData = 'data' + $dataNxt
|
||||
, $dataProperties = 'dataProperties' + $lvl;
|
||||
|
||||
var $schemaKeys = Object.keys($schema || {})
|
||||
var $schemaKeys = Object.keys($schema || {}).filter(notProto)
|
||||
, $pProperties = it.schema.patternProperties || {}
|
||||
, $pPropertyKeys = Object.keys($pProperties)
|
||||
, $pPropertyKeys = Object.keys($pProperties).filter(notProto)
|
||||
, $aProperties = it.schema.additionalProperties
|
||||
, $someProperties = $schemaKeys.length || $pPropertyKeys.length
|
||||
, $noAdditional = $aProperties === false
|
||||
@@ -42,8 +42,11 @@
|
||||
, $currentBaseId = it.baseId;
|
||||
|
||||
var $required = it.schema.required;
|
||||
if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired)
|
||||
if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) {
|
||||
var $requiredHash = it.util.toHash($required);
|
||||
}
|
||||
|
||||
function notProto(p) { return p !== '__proto__'; }
|
||||
}}
|
||||
|
||||
|
||||
@@ -240,5 +243,3 @@ var {{=$nextValid}} = true;
|
||||
{{= $closingBraces }}
|
||||
if ({{=$errs}} == errors) {
|
||||
{{?}}
|
||||
|
||||
{{# def.cleanUp }}
|
||||
-2
@@ -50,5 +50,3 @@ var {{=$errs}} = errors;
|
||||
{{= $closingBraces }}
|
||||
if ({{=$errs}} == errors) {
|
||||
{{?}}
|
||||
|
||||
{{# def.cleanUp }}
|
||||
+1
-1
@@ -38,7 +38,7 @@
|
||||
for (;i--;) {
|
||||
var item = {{=$data}}[i];
|
||||
{{ var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); }}
|
||||
if ({{= it.util[$method]($itemType, 'item', true) }}) continue;
|
||||
if ({{= it.util[$method]($itemType, 'item', it.opts.strictNumbers, true) }}) continue;
|
||||
{{? $typeIsArray}}
|
||||
if (typeof item == 'string') item = '"' + item;
|
||||
{{?}}
|
||||
|
||||
+2
-8
@@ -140,7 +140,7 @@
|
||||
, $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
|
||||
}}
|
||||
|
||||
if ({{= it.util[$method]($typeSchema, $data, true) }}) {
|
||||
if ({{= it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true) }}) {
|
||||
#}}
|
||||
|
||||
{{? it.schema.$ref && $refKeywords }}
|
||||
@@ -192,7 +192,7 @@
|
||||
{{~ it.RULES:$rulesGroup }}
|
||||
{{? $shouldUseGroup($rulesGroup) }}
|
||||
{{? $rulesGroup.type }}
|
||||
if ({{= it.util.checkDataType($rulesGroup.type, $data) }}) {
|
||||
if ({{= it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers) }}) {
|
||||
{{?}}
|
||||
{{? it.opts.useDefaults }}
|
||||
{{? $rulesGroup.type == 'object' && it.schema.properties }}
|
||||
@@ -254,12 +254,6 @@
|
||||
var {{=$valid}} = errors === errs_{{=$lvl}};
|
||||
{{?}}
|
||||
|
||||
{{# def.cleanUp }}
|
||||
|
||||
{{? $top }}
|
||||
{{# def.finalCleanUp }}
|
||||
{{?}}
|
||||
|
||||
{{
|
||||
function $shouldUseGroup($rulesGroup) {
|
||||
var rules = $rulesGroup.rules;
|
||||
|
||||
+6
@@ -24,6 +24,12 @@ module.exports = function generate__limit(it, $keyword, $ruleType) {
|
||||
$op = $isMax ? '<' : '>',
|
||||
$notOp = $isMax ? '>' : '<',
|
||||
$errorKeyword = undefined;
|
||||
if (!($isData || typeof $schema == 'number' || $schema === undefined)) {
|
||||
throw new Error($keyword + ' must be number');
|
||||
}
|
||||
if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) {
|
||||
throw new Error($exclusiveKeyword + ' must be number or boolean');
|
||||
}
|
||||
if ($isDataExcl) {
|
||||
var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),
|
||||
$exclusive = 'exclusive' + $lvl,
|
||||
|
||||
+3
@@ -17,6 +17,9 @@ module.exports = function generate__limitItems(it, $keyword, $ruleType) {
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
if (!($isData || typeof $schema == 'number')) {
|
||||
throw new Error($keyword + ' must be number');
|
||||
}
|
||||
var $op = $keyword == 'maxItems' ? '>' : '<';
|
||||
out += 'if ( ';
|
||||
if ($isData) {
|
||||
|
||||
+3
@@ -17,6 +17,9 @@ module.exports = function generate__limitLength(it, $keyword, $ruleType) {
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
if (!($isData || typeof $schema == 'number')) {
|
||||
throw new Error($keyword + ' must be number');
|
||||
}
|
||||
var $op = $keyword == 'maxLength' ? '>' : '<';
|
||||
out += 'if ( ';
|
||||
if ($isData) {
|
||||
|
||||
+3
@@ -17,6 +17,9 @@ module.exports = function generate__limitProperties(it, $keyword, $ruleType) {
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
if (!($isData || typeof $schema == 'number')) {
|
||||
throw new Error($keyword + ' must be number');
|
||||
}
|
||||
var $op = $keyword == 'maxProperties' ? '>' : '<';
|
||||
out += 'if ( ';
|
||||
if ($isData) {
|
||||
|
||||
-1
@@ -38,6 +38,5 @@ module.exports = function generate_allOf(it, $keyword, $ruleType) {
|
||||
out += ' ' + ($closingBraces.slice(0, -1)) + ' ';
|
||||
}
|
||||
}
|
||||
out = it.util.cleanUpCode(out);
|
||||
return out;
|
||||
}
|
||||
-1
@@ -64,7 +64,6 @@ module.exports = function generate_anyOf(it, $keyword, $ruleType) {
|
||||
if (it.opts.allErrors) {
|
||||
out += ' } ';
|
||||
}
|
||||
out = it.util.cleanUpCode(out);
|
||||
} else {
|
||||
if ($breakOnError) {
|
||||
out += ' if (true) { ';
|
||||
|
||||
-1
@@ -77,6 +77,5 @@ module.exports = function generate_contains(it, $keyword, $ruleType) {
|
||||
if (it.opts.allErrors) {
|
||||
out += ' } ';
|
||||
}
|
||||
out = it.util.cleanUpCode(out);
|
||||
return out;
|
||||
}
|
||||
+1
-1
@@ -17,6 +17,7 @@ module.exports = function generate_dependencies(it, $keyword, $ruleType) {
|
||||
$propertyDeps = {},
|
||||
$ownProperties = it.opts.ownProperties;
|
||||
for ($property in $schema) {
|
||||
if ($property == '__proto__') continue;
|
||||
var $sch = $schema[$property];
|
||||
var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
|
||||
$deps[$property] = $sch;
|
||||
@@ -163,6 +164,5 @@ module.exports = function generate_dependencies(it, $keyword, $ruleType) {
|
||||
if ($breakOnError) {
|
||||
out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
|
||||
}
|
||||
out = it.util.cleanUpCode(out);
|
||||
return out;
|
||||
}
|
||||
-1
@@ -94,7 +94,6 @@ module.exports = function generate_if(it, $keyword, $ruleType) {
|
||||
if ($breakOnError) {
|
||||
out += ' else { ';
|
||||
}
|
||||
out = it.util.cleanUpCode(out);
|
||||
} else {
|
||||
if ($breakOnError) {
|
||||
out += ' if (true) { ';
|
||||
|
||||
-1
@@ -136,6 +136,5 @@ module.exports = function generate_items(it, $keyword, $ruleType) {
|
||||
if ($breakOnError) {
|
||||
out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
|
||||
}
|
||||
out = it.util.cleanUpCode(out);
|
||||
return out;
|
||||
}
|
||||
+3
@@ -16,6 +16,9 @@ module.exports = function generate_multipleOf(it, $keyword, $ruleType) {
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
if (!($isData || typeof $schema == 'number')) {
|
||||
throw new Error($keyword + ' must be number');
|
||||
}
|
||||
out += 'var division' + ($lvl) + ';if (';
|
||||
if ($isData) {
|
||||
out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || ';
|
||||
|
||||
+9
-4
@@ -18,9 +18,9 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
|
||||
$dataNxt = $it.dataLevel = it.dataLevel + 1,
|
||||
$nextData = 'data' + $dataNxt,
|
||||
$dataProperties = 'dataProperties' + $lvl;
|
||||
var $schemaKeys = Object.keys($schema || {}),
|
||||
var $schemaKeys = Object.keys($schema || {}).filter(notProto),
|
||||
$pProperties = it.schema.patternProperties || {},
|
||||
$pPropertyKeys = Object.keys($pProperties),
|
||||
$pPropertyKeys = Object.keys($pProperties).filter(notProto),
|
||||
$aProperties = it.schema.additionalProperties,
|
||||
$someProperties = $schemaKeys.length || $pPropertyKeys.length,
|
||||
$noAdditional = $aProperties === false,
|
||||
@@ -30,7 +30,13 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
|
||||
$ownProperties = it.opts.ownProperties,
|
||||
$currentBaseId = it.baseId;
|
||||
var $required = it.schema.required;
|
||||
if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required);
|
||||
if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) {
|
||||
var $requiredHash = it.util.toHash($required);
|
||||
}
|
||||
|
||||
function notProto(p) {
|
||||
return p !== '__proto__';
|
||||
}
|
||||
out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;';
|
||||
if ($ownProperties) {
|
||||
out += ' var ' + ($dataProperties) + ' = undefined;';
|
||||
@@ -325,6 +331,5 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
|
||||
if ($breakOnError) {
|
||||
out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
|
||||
}
|
||||
out = it.util.cleanUpCode(out);
|
||||
return out;
|
||||
}
|
||||
-1
@@ -77,6 +77,5 @@ module.exports = function generate_propertyNames(it, $keyword, $ruleType) {
|
||||
if ($breakOnError) {
|
||||
out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
|
||||
}
|
||||
out = it.util.cleanUpCode(out);
|
||||
return out;
|
||||
}
|
||||
+1
-1
@@ -29,7 +29,7 @@ module.exports = function generate_uniqueItems(it, $keyword, $ruleType) {
|
||||
} else {
|
||||
out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; ';
|
||||
var $method = 'checkDataType' + ($typeIsArray ? 's' : '');
|
||||
out += ' if (' + (it.util[$method]($itemType, 'item', true)) + ') continue; ';
|
||||
out += ' if (' + (it.util[$method]($itemType, 'item', it.opts.strictNumbers, true)) + ') continue; ';
|
||||
if ($typeIsArray) {
|
||||
out += ' if (typeof item == \'string\') item = \'"\' + item; ';
|
||||
}
|
||||
|
||||
+2
-6
@@ -149,7 +149,7 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
|
||||
var $schemaPath = it.schemaPath + '.type',
|
||||
$errSchemaPath = it.errSchemaPath + '/type',
|
||||
$method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
|
||||
out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { ';
|
||||
out += ' if (' + (it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true)) + ') { ';
|
||||
if ($coerceToTypes) {
|
||||
var $dataType = 'dataType' + $lvl,
|
||||
$coerced = 'coerced' + $lvl;
|
||||
@@ -302,7 +302,7 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
|
||||
$rulesGroup = arr2[i2 += 1];
|
||||
if ($shouldUseGroup($rulesGroup)) {
|
||||
if ($rulesGroup.type) {
|
||||
out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data)) + ') { ';
|
||||
out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers)) + ') { ';
|
||||
}
|
||||
if (it.opts.useDefaults) {
|
||||
if ($rulesGroup.type == 'object' && it.schema.properties) {
|
||||
@@ -470,10 +470,6 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
|
||||
} else {
|
||||
out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';
|
||||
}
|
||||
out = it.util.cleanUpCode(out);
|
||||
if ($top) {
|
||||
out = it.util.finalCleanUpCode(out, $async);
|
||||
}
|
||||
|
||||
function $shouldUseGroup($rulesGroup) {
|
||||
var rules = $rulesGroup.rules;
|
||||
|
||||
+1
-1
@@ -46,7 +46,7 @@ function addKeyword(keyword, definition) {
|
||||
metaSchema = {
|
||||
anyOf: [
|
||||
metaSchema,
|
||||
{ '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#' }
|
||||
{ '$ref': 'https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#' }
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$id": "https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#",
|
||||
"$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
|
||||
"description": "Meta-schema for $data reference (JSON Schema extension proposal)",
|
||||
"type": "object",
|
||||
"required": [ "$data" ],
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$id": "https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-secure.json#",
|
||||
"$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/json-schema-secure.json#",
|
||||
"title": "Meta-schema for the security assessment of JSON Schemas",
|
||||
"description": "If a JSON Schema fails validation against this meta-schema, it may be unsafe to validate untrusted data",
|
||||
"definitions": {
|
||||
|
||||
+11
-7
@@ -3,7 +3,7 @@
|
||||
"name": "Evgeny Poberezkin"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/epoberezkin/ajv/issues"
|
||||
"url": "https://github.com/ajv-validator/ajv/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"collective": {
|
||||
@@ -27,7 +27,7 @@
|
||||
"coveralls": "^3.0.1",
|
||||
"del-cli": "^3.0.0",
|
||||
"dot": "^1.0.3",
|
||||
"eslint": "^6.0.0",
|
||||
"eslint": "^7.3.1",
|
||||
"gh-pages-generator": "^0.2.3",
|
||||
"glob": "^7.0.0",
|
||||
"if-node-version": "^1.0.0",
|
||||
@@ -38,11 +38,11 @@
|
||||
"karma-chrome-launcher": "^3.0.0",
|
||||
"karma-mocha": "^2.0.0",
|
||||
"karma-sauce-launcher": "^4.1.3",
|
||||
"mocha": "^7.0.1",
|
||||
"mocha": "^8.0.1",
|
||||
"nyc": "^15.0.0",
|
||||
"pre-commit": "^1.1.1",
|
||||
"require-globify": "^1.3.0",
|
||||
"typescript": "^2.8.3",
|
||||
"typescript": "^3.9.5",
|
||||
"uglify-js": "^3.6.9",
|
||||
"watch": "^1.0.0"
|
||||
},
|
||||
@@ -53,7 +53,11 @@
|
||||
"LICENSE",
|
||||
".tonic_example.js"
|
||||
],
|
||||
"homepage": "https://github.com/epoberezkin/ajv",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/epoberezkin"
|
||||
},
|
||||
"homepage": "https://github.com/ajv-validator/ajv",
|
||||
"keywords": [
|
||||
"JSON",
|
||||
"schema",
|
||||
@@ -79,7 +83,7 @@
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/epoberezkin/ajv.git"
|
||||
"url": "git+https://github.com/ajv-validator/ajv.git"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "del-cli lib/dotjs/*.js \"!lib/dotjs/index.js\" && node scripts/compile-dots.js",
|
||||
@@ -102,5 +106,5 @@
|
||||
},
|
||||
"tonicExampleFilename": ".tonic_example.js",
|
||||
"typings": "lib/ajv.d.ts",
|
||||
"version": "6.12.2"
|
||||
"version": "6.12.3"
|
||||
}
|
||||
+1
-1
@@ -8,7 +8,7 @@ if [[ -n $TRAVIS_TAG && $TRAVIS_JOB_NUMBER =~ ".3" ]]; then
|
||||
git config user.email "$GIT_USER_EMAIL"
|
||||
git config user.name "$GIT_USER_NAME"
|
||||
|
||||
git clone https://${GITHUB_TOKEN}@github.com/epoberezkin/ajv-dist.git ../ajv-dist
|
||||
git clone https://${GITHUB_TOKEN}@github.com/ajv-validator/ajv-dist.git ../ajv-dist
|
||||
|
||||
rm -rf ../ajv-dist/dist
|
||||
mkdir ../ajv-dist/dist
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ set -e
|
||||
if [[ "$TRAVIS_BRANCH" == "master" && "$TRAVIS_PULL_REQUEST" == "false" && $TRAVIS_JOB_NUMBER =~ ".3" ]]; then
|
||||
git diff --name-only $TRAVIS_COMMIT_RANGE | grep -qE '\.md$|^LICENSE$|travis-gh-pages$' && {
|
||||
rm -rf ../gh-pages
|
||||
git clone -b gh-pages --single-branch https://${GITHUB_TOKEN}@github.com/epoberezkin/ajv.git ../gh-pages
|
||||
git clone -b gh-pages --single-branch https://${GITHUB_TOKEN}@github.com/ajv-validator/ajv.git ../gh-pages
|
||||
mkdir -p ../gh-pages/_source
|
||||
cp *.md ../gh-pages/_source
|
||||
cp LICENSE ../gh-pages/_source
|
||||
|
||||
+53
-17
@@ -141,6 +141,48 @@ _(`gray` is the U.S. spelling, `grey` is more commonly used in the Canada and U.
|
||||
|
||||
* reset
|
||||
|
||||
## Aliases
|
||||
|
||||
Create custom aliases for styles.
|
||||
|
||||
```js
|
||||
const colors = require('ansi-colors');
|
||||
|
||||
colors.alias('primary', colors.yellow);
|
||||
colors.alias('secondary', colors.bold);
|
||||
|
||||
console.log(colors.primary.secondary('Foo'));
|
||||
```
|
||||
|
||||
## Themes
|
||||
|
||||
A theme is an object of custom aliases.
|
||||
|
||||
```js
|
||||
const colors = require('ansi-colors');
|
||||
|
||||
colors.theme({
|
||||
danger: colors.red,
|
||||
dark: colors.dim.gray,
|
||||
disabled: colors.gray,
|
||||
em: colors.italic,
|
||||
heading: colors.bold.underline,
|
||||
info: colors.cyan,
|
||||
muted: colors.dim,
|
||||
primary: colors.blue,
|
||||
strong: colors.bold,
|
||||
success: colors.green,
|
||||
underline: colors.underline,
|
||||
warning: colors.yellow
|
||||
});
|
||||
|
||||
// Now, we can use our custom styles alongside the built-in styles!
|
||||
console.log(colors.danger.strong.em('Error!'));
|
||||
console.log(colors.warning('Heads up!'));
|
||||
console.log(colors.info('Did you know...'));
|
||||
console.log(colors.success.bold('It worked!'));
|
||||
```
|
||||
|
||||
## Performance
|
||||
|
||||
**Libraries tested**
|
||||
@@ -244,16 +286,16 @@ You might also be interested in these projects:
|
||||
|
||||
### Contributors
|
||||
|
||||
| **Commits** | **Contributor** |
|
||||
| --- | --- |
|
||||
| 42 | [doowb](https://github.com/doowb) |
|
||||
| 38 | [jonschlinkert](https://github.com/jonschlinkert) |
|
||||
| 6 | [lukeed](https://github.com/lukeed) |
|
||||
| 2 | [Silic0nS0ldier](https://github.com/Silic0nS0ldier) |
|
||||
| 1 | [dwieeb](https://github.com/dwieeb) |
|
||||
| 1 | [jorgebucaran](https://github.com/jorgebucaran) |
|
||||
| 1 | [madhavarshney](https://github.com/madhavarshney) |
|
||||
| 1 | [chapterjason](https://github.com/chapterjason) |
|
||||
| **Commits** | **Contributor** |
|
||||
| --- | --- |
|
||||
| 48 | [jonschlinkert](https://github.com/jonschlinkert) |
|
||||
| 42 | [doowb](https://github.com/doowb) |
|
||||
| 6 | [lukeed](https://github.com/lukeed) |
|
||||
| 2 | [Silic0nS0ldier](https://github.com/Silic0nS0ldier) |
|
||||
| 1 | [dwieeb](https://github.com/dwieeb) |
|
||||
| 1 | [jorgebucaran](https://github.com/jorgebucaran) |
|
||||
| 1 | [madhavarshney](https://github.com/madhavarshney) |
|
||||
| 1 | [chapterjason](https://github.com/chapterjason) |
|
||||
|
||||
### Author
|
||||
|
||||
@@ -263,12 +305,6 @@ You might also be interested in these projects:
|
||||
* [Twitter Profile](https://twitter.com/doowb)
|
||||
* [LinkedIn Profile](https://linkedin.com/in/woodwardbrian)
|
||||
|
||||
Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)!
|
||||
|
||||
<a href="https://www.patreon.com/jonschlinkert">
|
||||
<img src="https://c5.patreon.com/external/logo/become_a_patron_button@2x.png" height="50">
|
||||
</a>
|
||||
|
||||
### License
|
||||
|
||||
Copyright © 2019, [Brian Woodward](https://github.com/doowb).
|
||||
@@ -276,4 +312,4 @@ Released under the [MIT License](LICENSE).
|
||||
|
||||
***
|
||||
|
||||
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 03, 2019._
|
||||
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on July 01, 2019._
|
||||
+170
-110
@@ -1,117 +1,177 @@
|
||||
'use strict';
|
||||
|
||||
const colors = { enabled: true, visible: true, styles: {}, keys: {} };
|
||||
|
||||
if ('FORCE_COLOR' in process.env) {
|
||||
colors.enabled = process.env.FORCE_COLOR !== '0';
|
||||
}
|
||||
|
||||
const ansi = style => {
|
||||
style.open = `\u001b[${style.codes[0]}m`;
|
||||
style.close = `\u001b[${style.codes[1]}m`;
|
||||
style.regex = new RegExp(`\\u001b\\[${style.codes[1]}m`, 'g');
|
||||
return style;
|
||||
};
|
||||
|
||||
const wrap = (style, str, nl) => {
|
||||
let { open, close, regex } = style;
|
||||
str = open + (str.includes(close) ? str.replace(regex, close + open) : str) + close;
|
||||
// see https://github.com/chalk/chalk/pull/92, thanks to the
|
||||
// chalk contributors for this fix. However, we've confirmed that
|
||||
// this issue is also present in Windows terminals
|
||||
return nl ? str.replace(/\r?\n/g, `${close}$&${open}`) : str;
|
||||
};
|
||||
|
||||
const style = (input, stack) => {
|
||||
if (input === '' || input == null) return '';
|
||||
if (colors.enabled === false) return input;
|
||||
if (colors.visible === false) return '';
|
||||
let str = '' + input;
|
||||
let nl = str.includes('\n');
|
||||
let n = stack.length;
|
||||
while (n-- > 0) str = wrap(colors.styles[stack[n]], str, nl);
|
||||
return str;
|
||||
};
|
||||
|
||||
const define = (name, codes, type) => {
|
||||
colors.styles[name] = ansi({ name, codes });
|
||||
let t = colors.keys[type] || (colors.keys[type] = []);
|
||||
t.push(name);
|
||||
|
||||
Reflect.defineProperty(colors, name, {
|
||||
get() {
|
||||
let color = input => style(input, color.stack);
|
||||
Reflect.setPrototypeOf(color, colors);
|
||||
color.stack = this.stack ? this.stack.concat(name) : [name];
|
||||
return color;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
define('reset', [0, 0], 'modifier');
|
||||
define('bold', [1, 22], 'modifier');
|
||||
define('dim', [2, 22], 'modifier');
|
||||
define('italic', [3, 23], 'modifier');
|
||||
define('underline', [4, 24], 'modifier');
|
||||
define('inverse', [7, 27], 'modifier');
|
||||
define('hidden', [8, 28], 'modifier');
|
||||
define('strikethrough', [9, 29], 'modifier');
|
||||
|
||||
define('black', [30, 39], 'color');
|
||||
define('red', [31, 39], 'color');
|
||||
define('green', [32, 39], 'color');
|
||||
define('yellow', [33, 39], 'color');
|
||||
define('blue', [34, 39], 'color');
|
||||
define('magenta', [35, 39], 'color');
|
||||
define('cyan', [36, 39], 'color');
|
||||
define('white', [37, 39], 'color');
|
||||
define('gray', [90, 39], 'color');
|
||||
define('grey', [90, 39], 'color');
|
||||
|
||||
define('bgBlack', [40, 49], 'bg');
|
||||
define('bgRed', [41, 49], 'bg');
|
||||
define('bgGreen', [42, 49], 'bg');
|
||||
define('bgYellow', [43, 49], 'bg');
|
||||
define('bgBlue', [44, 49], 'bg');
|
||||
define('bgMagenta', [45, 49], 'bg');
|
||||
define('bgCyan', [46, 49], 'bg');
|
||||
define('bgWhite', [47, 49], 'bg');
|
||||
|
||||
define('blackBright', [90, 39], 'bright');
|
||||
define('redBright', [91, 39], 'bright');
|
||||
define('greenBright', [92, 39], 'bright');
|
||||
define('yellowBright', [93, 39], 'bright');
|
||||
define('blueBright', [94, 39], 'bright');
|
||||
define('magentaBright', [95, 39], 'bright');
|
||||
define('cyanBright', [96, 39], 'bright');
|
||||
define('whiteBright', [97, 39], 'bright');
|
||||
|
||||
define('bgBlackBright', [100, 49], 'bgBright');
|
||||
define('bgRedBright', [101, 49], 'bgBright');
|
||||
define('bgGreenBright', [102, 49], 'bgBright');
|
||||
define('bgYellowBright', [103, 49], 'bgBright');
|
||||
define('bgBlueBright', [104, 49], 'bgBright');
|
||||
define('bgMagentaBright', [105, 49], 'bgBright');
|
||||
define('bgCyanBright', [106, 49], 'bgBright');
|
||||
define('bgWhiteBright', [107, 49], 'bgBright');
|
||||
const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
|
||||
const identity = val => val;
|
||||
|
||||
/* eslint-disable no-control-regex */
|
||||
// this is a modified, optimized version of
|
||||
// https://github.com/chalk/ansi-regex (MIT License)
|
||||
const re = colors.ansiRegex = /[\u001b\u009b][[\]#;?()]*(?:(?:(?:[^\W_]*;?[^\W_]*)\u0007)|(?:(?:[0-9]{1,4}(;[0-9]{0,4})*)?[~0-9=<>cf-nqrtyA-PRZ]))/g;
|
||||
// this is a modified version of https://github.com/chalk/ansi-regex (MIT License)
|
||||
const ANSI_REGEX = /[\u001b\u009b][[\]#;?()]*(?:(?:(?:[^\W_]*;?[^\W_]*)\u0007)|(?:(?:[0-9]{1,4}(;[0-9]{0,4})*)?[~0-9=<>cf-nqrtyA-PRZ]))/g;
|
||||
|
||||
colors.hasColor = colors.hasAnsi = str => {
|
||||
re.lastIndex = 0;
|
||||
return !!str && typeof str === 'string' && re.test(str);
|
||||
const create = () => {
|
||||
const colors = { enabled: true, visible: true, styles: {}, keys: {} };
|
||||
|
||||
if ('FORCE_COLOR' in process.env) {
|
||||
colors.enabled = process.env.FORCE_COLOR !== '0';
|
||||
}
|
||||
|
||||
const ansi = style => {
|
||||
let open = style.open = `\u001b[${style.codes[0]}m`;
|
||||
let close = style.close = `\u001b[${style.codes[1]}m`;
|
||||
let regex = style.regex = new RegExp(`\\u001b\\[${style.codes[1]}m`, 'g');
|
||||
style.wrap = (input, newline) => {
|
||||
if (input.includes(close)) input = input.replace(regex, close + open);
|
||||
let output = open + input + close;
|
||||
// see https://github.com/chalk/chalk/pull/92, thanks to the
|
||||
// chalk contributors for this fix. However, we've confirmed that
|
||||
// this issue is also present in Windows terminals
|
||||
return newline ? output.replace(/\r*\n/g, `${close}$&${open}`) : output;
|
||||
};
|
||||
return style;
|
||||
};
|
||||
|
||||
const wrap = (style, input, newline) => {
|
||||
return typeof style === 'function' ? style(input) : style.wrap(input, newline);
|
||||
};
|
||||
|
||||
const style = (input, stack) => {
|
||||
if (input === '' || input == null) return '';
|
||||
if (colors.enabled === false) return input;
|
||||
if (colors.visible === false) return '';
|
||||
let str = '' + input;
|
||||
let nl = str.includes('\n');
|
||||
let n = stack.length;
|
||||
if (n > 0 && stack.includes('unstyle')) {
|
||||
stack = [...new Set(['unstyle', ...stack])].reverse();
|
||||
}
|
||||
while (n-- > 0) str = wrap(colors.styles[stack[n]], str, nl);
|
||||
return str;
|
||||
};
|
||||
|
||||
const define = (name, codes, type) => {
|
||||
colors.styles[name] = ansi({ name, codes });
|
||||
let keys = colors.keys[type] || (colors.keys[type] = []);
|
||||
keys.push(name);
|
||||
|
||||
Reflect.defineProperty(colors, name, {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
set(value) {
|
||||
colors.alias(name, value);
|
||||
},
|
||||
get() {
|
||||
let color = input => style(input, color.stack);
|
||||
Reflect.setPrototypeOf(color, colors);
|
||||
color.stack = this.stack ? this.stack.concat(name) : [name];
|
||||
return color;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
define('reset', [0, 0], 'modifier');
|
||||
define('bold', [1, 22], 'modifier');
|
||||
define('dim', [2, 22], 'modifier');
|
||||
define('italic', [3, 23], 'modifier');
|
||||
define('underline', [4, 24], 'modifier');
|
||||
define('inverse', [7, 27], 'modifier');
|
||||
define('hidden', [8, 28], 'modifier');
|
||||
define('strikethrough', [9, 29], 'modifier');
|
||||
|
||||
define('black', [30, 39], 'color');
|
||||
define('red', [31, 39], 'color');
|
||||
define('green', [32, 39], 'color');
|
||||
define('yellow', [33, 39], 'color');
|
||||
define('blue', [34, 39], 'color');
|
||||
define('magenta', [35, 39], 'color');
|
||||
define('cyan', [36, 39], 'color');
|
||||
define('white', [37, 39], 'color');
|
||||
define('gray', [90, 39], 'color');
|
||||
define('grey', [90, 39], 'color');
|
||||
|
||||
define('bgBlack', [40, 49], 'bg');
|
||||
define('bgRed', [41, 49], 'bg');
|
||||
define('bgGreen', [42, 49], 'bg');
|
||||
define('bgYellow', [43, 49], 'bg');
|
||||
define('bgBlue', [44, 49], 'bg');
|
||||
define('bgMagenta', [45, 49], 'bg');
|
||||
define('bgCyan', [46, 49], 'bg');
|
||||
define('bgWhite', [47, 49], 'bg');
|
||||
|
||||
define('blackBright', [90, 39], 'bright');
|
||||
define('redBright', [91, 39], 'bright');
|
||||
define('greenBright', [92, 39], 'bright');
|
||||
define('yellowBright', [93, 39], 'bright');
|
||||
define('blueBright', [94, 39], 'bright');
|
||||
define('magentaBright', [95, 39], 'bright');
|
||||
define('cyanBright', [96, 39], 'bright');
|
||||
define('whiteBright', [97, 39], 'bright');
|
||||
|
||||
define('bgBlackBright', [100, 49], 'bgBright');
|
||||
define('bgRedBright', [101, 49], 'bgBright');
|
||||
define('bgGreenBright', [102, 49], 'bgBright');
|
||||
define('bgYellowBright', [103, 49], 'bgBright');
|
||||
define('bgBlueBright', [104, 49], 'bgBright');
|
||||
define('bgMagentaBright', [105, 49], 'bgBright');
|
||||
define('bgCyanBright', [106, 49], 'bgBright');
|
||||
define('bgWhiteBright', [107, 49], 'bgBright');
|
||||
|
||||
colors.ansiRegex = ANSI_REGEX;
|
||||
colors.hasColor = colors.hasAnsi = str => {
|
||||
colors.ansiRegex.lastIndex = 0;
|
||||
return typeof str === 'string' && str !== '' && colors.ansiRegex.test(str);
|
||||
};
|
||||
|
||||
colors.alias = (name, color) => {
|
||||
let fn = typeof color === 'string' ? colors[color] : color;
|
||||
|
||||
if (typeof fn !== 'function') {
|
||||
throw new TypeError('Expected alias to be the name of an existing color (string) or a function');
|
||||
}
|
||||
|
||||
if (!fn.stack) {
|
||||
Reflect.defineProperty(fn, 'name', { value: name });
|
||||
colors.styles[name] = fn;
|
||||
fn.stack = [name];
|
||||
}
|
||||
|
||||
Reflect.defineProperty(colors, name, {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
set(value) {
|
||||
colors.alias(name, value);
|
||||
},
|
||||
get() {
|
||||
let color = input => style(input, color.stack);
|
||||
Reflect.setPrototypeOf(color, colors);
|
||||
color.stack = this.stack ? this.stack.concat(fn.stack) : fn.stack;
|
||||
return color;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
colors.theme = custom => {
|
||||
if (!isObject(custom)) throw new TypeError('Expected theme to be an object');
|
||||
for (let name of Object.keys(custom)) {
|
||||
colors.alias(name, custom[name]);
|
||||
}
|
||||
return colors;
|
||||
};
|
||||
|
||||
colors.alias('unstyle', str => {
|
||||
if (typeof str === 'string' && str !== '') {
|
||||
colors.ansiRegex.lastIndex = 0;
|
||||
return str.replace(colors.ansiRegex, '');
|
||||
}
|
||||
return '';
|
||||
});
|
||||
|
||||
colors.alias('noop', str => str);
|
||||
colors.none = colors.clear = colors.noop;
|
||||
|
||||
colors.stripColor = colors.unstyle;
|
||||
colors.symbols = require('./symbols');
|
||||
colors.define = define;
|
||||
return colors;
|
||||
};
|
||||
|
||||
colors.unstyle = str => {
|
||||
re.lastIndex = 0;
|
||||
return typeof str === 'string' ? str.replace(re, '') : str;
|
||||
};
|
||||
|
||||
colors.none = colors.clear = colors.noop = str => str; // no-op, for programmatic usage
|
||||
colors.stripColor = colors.unstyle;
|
||||
colors.symbols = require('./symbols');
|
||||
colors.define = define;
|
||||
module.exports = colors;
|
||||
module.exports = create();
|
||||
module.exports.create = create;
|
||||
+4
-4
@@ -28,10 +28,10 @@
|
||||
"deprecated": false,
|
||||
"description": "Easily add ANSI colors to your text and symbols in the terminal. A faster drop-in replacement for chalk, kleur and turbocolor (without the dependencies and rendering bugs).",
|
||||
"devDependencies": {
|
||||
"decache": "^4.4.0",
|
||||
"gulp-format-md": "^1.0.0",
|
||||
"decache": "^4.5.1",
|
||||
"gulp-format-md": "^2.0.0",
|
||||
"justified": "^1.0.1",
|
||||
"mocha": "^5.2.0",
|
||||
"mocha": "^6.1.4",
|
||||
"text-table": "^0.2.0"
|
||||
},
|
||||
"engines": {
|
||||
@@ -125,5 +125,5 @@
|
||||
"kleur"
|
||||
]
|
||||
},
|
||||
"version": "3.2.4"
|
||||
"version": "4.1.1"
|
||||
}
|
||||
+44
-20
@@ -1,46 +1,70 @@
|
||||
'use strict';
|
||||
|
||||
const isHyper = process.env.TERM_PROGRAM === 'Hyper';
|
||||
const isWindows = process.platform === 'win32';
|
||||
const isLinux = process.platform === 'linux';
|
||||
|
||||
const windows = {
|
||||
const common = {
|
||||
ballotDisabled: '☒',
|
||||
ballotOff: '☐',
|
||||
ballotOn: '☑',
|
||||
bullet: '•',
|
||||
check: '√',
|
||||
cross: '×',
|
||||
ellipsis: '...',
|
||||
bulletWhite: '◦',
|
||||
fullBlock: '█',
|
||||
heart: '❤',
|
||||
info: 'i',
|
||||
identicalTo: '≡',
|
||||
line: '─',
|
||||
mark: '※',
|
||||
middot: '·',
|
||||
minus: '-',
|
||||
plus: '+',
|
||||
question: '?',
|
||||
questionSmall: '﹖',
|
||||
pointer: '>',
|
||||
pointerSmall: '»',
|
||||
warning: '‼'
|
||||
multiplication: '×',
|
||||
obelus: '÷',
|
||||
pencilDownRight: '✎',
|
||||
pencilRight: '✏',
|
||||
pencilUpRight: '✐',
|
||||
percent: '%',
|
||||
pilcrow2: '❡',
|
||||
pilcrow: '¶',
|
||||
plusMinus: '±',
|
||||
section: '§',
|
||||
starsOff: '☆',
|
||||
starsOn: '★',
|
||||
upDownArrow: '↕'
|
||||
};
|
||||
|
||||
const other = {
|
||||
const windows = Object.assign({}, common, {
|
||||
check: '√',
|
||||
cross: '×',
|
||||
ellipsisLarge: '...',
|
||||
ellipsis: '...',
|
||||
info: 'i',
|
||||
question: '?',
|
||||
questionSmall: '?',
|
||||
pointer: '>',
|
||||
pointerSmall: '»',
|
||||
radioOff: '( )',
|
||||
radioOn: '(*)',
|
||||
warning: '‼'
|
||||
});
|
||||
|
||||
const other = Object.assign({}, common, {
|
||||
ballotCross: '✘',
|
||||
bullet: '•',
|
||||
check: '✔',
|
||||
cross: '✖',
|
||||
ellipsisLarge: '⋯',
|
||||
ellipsis: '…',
|
||||
heart: '❤',
|
||||
info: 'ℹ',
|
||||
line: '─',
|
||||
middot: '·',
|
||||
minus: '-',
|
||||
plus: '+',
|
||||
question: '?',
|
||||
questionFull: '?',
|
||||
questionSmall: '﹖',
|
||||
pointer: isLinux ? '▸' : '❯',
|
||||
pointerSmall: isLinux ? '‣' : '›',
|
||||
radioOff: '◯',
|
||||
radioOn: '◉',
|
||||
warning: '⚠'
|
||||
};
|
||||
});
|
||||
|
||||
module.exports = isWindows ? windows : other;
|
||||
module.exports = (isWindows && !isHyper) ? windows : other;
|
||||
Reflect.defineProperty(module.exports, 'common', { enumerable: false, value: common });
|
||||
Reflect.defineProperty(module.exports, 'windows', { enumerable: false, value: windows });
|
||||
Reflect.defineProperty(module.exports, 'other', { enumerable: false, value: other });
|
||||
+28
-28
@@ -1705,34 +1705,34 @@ $ npm install -g verbose/verb#dev verb-generate-readme && verb
|
||||
|
||||
#### Contributors
|
||||
|
||||
| **Commits** | **Contributor** |
|
||||
| --- | --- |
|
||||
| 283 | [jonschlinkert](https://github.com/jonschlinkert) |
|
||||
| 82 | [doowb](https://github.com/doowb) |
|
||||
| 32 | [rajat-sr](https://github.com/rajat-sr) |
|
||||
| 20 | [318097](https://github.com/318097) |
|
||||
| 15 | [g-plane](https://github.com/g-plane) |
|
||||
| 12 | [pixelass](https://github.com/pixelass) |
|
||||
| 5 | [adityavyas611](https://github.com/adityavyas611) |
|
||||
| 5 | [satotake](https://github.com/satotake) |
|
||||
| 3 | [tunnckoCore](https://github.com/tunnckoCore) |
|
||||
| 3 | [Ovyerus](https://github.com/Ovyerus) |
|
||||
| 3 | [sw-yx](https://github.com/sw-yx) |
|
||||
| 2 | [DanielRuf](https://github.com/DanielRuf) |
|
||||
| 2 | [GabeL7r](https://github.com/GabeL7r) |
|
||||
| 1 | [AlCalzone](https://github.com/AlCalzone) |
|
||||
| 1 | [hipstersmoothie](https://github.com/hipstersmoothie) |
|
||||
| 1 | [danieldelcore](https://github.com/danieldelcore) |
|
||||
| 1 | [ImgBotApp](https://github.com/ImgBotApp) |
|
||||
| 1 | [jsonkao](https://github.com/jsonkao) |
|
||||
| 1 | [knpwrs](https://github.com/knpwrs) |
|
||||
| 1 | [yeskunall](https://github.com/yeskunall) |
|
||||
| 1 | [mischah](https://github.com/mischah) |
|
||||
| 1 | [renarsvilnis](https://github.com/renarsvilnis) |
|
||||
| 1 | [sbugert](https://github.com/sbugert) |
|
||||
| 1 | [stephencweiss](https://github.com/stephencweiss) |
|
||||
| 1 | [skellock](https://github.com/skellock) |
|
||||
| 1 | [whxaxes](https://github.com/whxaxes) |
|
||||
| **Commits** | **Contributor** |
|
||||
| --- | --- |
|
||||
| 283 | [jonschlinkert](https://github.com/jonschlinkert) |
|
||||
| 82 | [doowb](https://github.com/doowb) |
|
||||
| 32 | [rajat-sr](https://github.com/rajat-sr) |
|
||||
| 20 | [318097](https://github.com/318097) |
|
||||
| 15 | [g-plane](https://github.com/g-plane) |
|
||||
| 12 | [pixelass](https://github.com/pixelass) |
|
||||
| 5 | [adityavyas611](https://github.com/adityavyas611) |
|
||||
| 5 | [satotake](https://github.com/satotake) |
|
||||
| 3 | [tunnckoCore](https://github.com/tunnckoCore) |
|
||||
| 3 | [Ovyerus](https://github.com/Ovyerus) |
|
||||
| 3 | [sw-yx](https://github.com/sw-yx) |
|
||||
| 2 | [DanielRuf](https://github.com/DanielRuf) |
|
||||
| 2 | [GabeL7r](https://github.com/GabeL7r) |
|
||||
| 1 | [AlCalzone](https://github.com/AlCalzone) |
|
||||
| 1 | [hipstersmoothie](https://github.com/hipstersmoothie) |
|
||||
| 1 | [danieldelcore](https://github.com/danieldelcore) |
|
||||
| 1 | [ImgBotApp](https://github.com/ImgBotApp) |
|
||||
| 1 | [jsonkao](https://github.com/jsonkao) |
|
||||
| 1 | [knpwrs](https://github.com/knpwrs) |
|
||||
| 1 | [yeskunall](https://github.com/yeskunall) |
|
||||
| 1 | [mischah](https://github.com/mischah) |
|
||||
| 1 | [renarsvilnis](https://github.com/renarsvilnis) |
|
||||
| 1 | [sbugert](https://github.com/sbugert) |
|
||||
| 1 | [stephencweiss](https://github.com/stephencweiss) |
|
||||
| 1 | [skellock](https://github.com/skellock) |
|
||||
| 1 | [whxaxes](https://github.com/whxaxes) |
|
||||
|
||||
#### Author
|
||||
|
||||
|
||||
+1
@@ -10,3 +10,4 @@ class ConfirmPrompt extends BooleanPrompt {
|
||||
}
|
||||
|
||||
module.exports = ConfirmPrompt;
|
||||
|
||||
+1
@@ -63,3 +63,4 @@ symbols.merge = options => {
|
||||
};
|
||||
|
||||
module.exports = symbols;
|
||||
|
||||
+2
-2
@@ -18,7 +18,7 @@
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
"ansi-colors": "^3.2.1"
|
||||
"ansi-colors": "^4.1.1"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "Stylish, intuitive and user-friendly prompt system. Fast and lightweight enough for small projects, powerful and extensible enough for the most advanced use cases.",
|
||||
@@ -121,5 +121,5 @@
|
||||
"prompt-skeleton"
|
||||
]
|
||||
},
|
||||
"version": "2.3.5"
|
||||
"version": "2.3.6"
|
||||
}
|
||||
+1
-1
@@ -153,5 +153,5 @@
|
||||
"test:cli": "mocha",
|
||||
"webpack": "node Makefile.js webpack"
|
||||
},
|
||||
"version": "7.3.1"
|
||||
"version": "7.4.0"
|
||||
}
|
||||
Reference in new issue
Block a user