Socket
Socket
Sign inDemoInstall

schema-utils

Package Overview
Dependencies
9
Maintainers
2
Versions
39
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 4.0.0 to 4.0.1

26

declarations/validate.d.ts

@@ -25,3 +25,29 @@ export type JSONSchema4 = import("json-schema").JSONSchema4;

};
/** @typedef {import("json-schema").JSONSchema4} JSONSchema4 */
/** @typedef {import("json-schema").JSONSchema6} JSONSchema6 */
/** @typedef {import("json-schema").JSONSchema7} JSONSchema7 */
/** @typedef {import("ajv").ErrorObject} ErrorObject */
/**
* @typedef {Object} Extend
* @property {string=} formatMinimum
* @property {string=} formatMaximum
* @property {string=} formatExclusiveMinimum
* @property {string=} formatExclusiveMaximum
* @property {string=} link
*/
/** @typedef {(JSONSchema4 | JSONSchema6 | JSONSchema7) & Extend} Schema */
/** @typedef {ErrorObject & { children?: Array<ErrorObject>}} SchemaUtilErrorObject */
/**
* @callback PostFormatter
* @param {string} formattedError
* @param {SchemaUtilErrorObject} error
* @returns {string}
*/
/**
* @typedef {Object} ValidationErrorConfiguration
* @property {string=} name
* @property {string=} baseDataPath
* @property {PostFormatter=} postFormatter
*/
/**
* @param {Schema} schema

@@ -28,0 +54,0 @@ * @param {Array<object> | object} options

1

dist/index.js

@@ -7,3 +7,2 @@ "use strict";

} = require("./validate");
module.exports = {

@@ -10,0 +9,0 @@ validate,

@@ -7,9 +7,5 @@ "use strict";

exports.default = void 0;
/** @typedef {import("ajv").default} Ajv */
/** @typedef {import("ajv").SchemaValidateFunction} SchemaValidateFunction */
/** @typedef {import("ajv").AnySchemaObject} AnySchemaObject */
/** @typedef {import("../validate").SchemaUtilErrorObject} SchemaUtilErrorObject */

@@ -39,2 +35,3 @@

}
/**

@@ -46,4 +43,2 @@ * @param {boolean} shouldBeAbsolute

*/
function getErrorFor(shouldBeAbsolute, schema, data) {

@@ -53,2 +48,3 @@ const message = shouldBeAbsolute ? `The provided value ${JSON.stringify(data)} is not an absolute path!` : `A relative path is expected. However, the provided value ${JSON.stringify(data)} is an absolute path!`;

}
/**

@@ -59,4 +55,2 @@ *

*/
function addAbsolutePathKeyword(ajv) {

@@ -67,3 +61,2 @@ ajv.addKeyword({

errors: true,
/**

@@ -79,13 +72,11 @@ * @param {boolean} schema

const isExclamationMarkPresent = data.includes("!");
if (isExclamationMarkPresent) {
callback.errors = [errorMessage(`The provided value ${JSON.stringify(data)} contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.`, parentSchema, data)];
passes = false;
} // ?:[A-Za-z]:\\ - Windows absolute path
}
// ?:[A-Za-z]:\\ - Windows absolute path
// \\\\ - Windows network absolute path
// \/ - Unix-like OS absolute path
const isCorrectAbsolutePath = schema === /^(?:[A-Za-z]:(\\|\/)|\\\\|\/)/.test(data);
if (!isCorrectAbsolutePath) {

@@ -95,15 +86,11 @@ callback.errors = [getErrorFor(schema, parentSchema, data)];

}
return passes;
};
callback.errors = [];
return callback;
}
});
return ajv;
}
var _default = addAbsolutePathKeyword;
exports.default = _default;
"use strict";
const Range = require("./Range");
/** @typedef {import("../validate").Schema} Schema */

@@ -11,10 +12,8 @@

*/
module.exports.stringHints = function stringHints(schema, logic) {
const hints = [];
let type = "string";
const currentSchema = { ...schema
const currentSchema = {
...schema
};
if (!logic) {

@@ -28,3 +27,2 @@ const tmpLength = currentSchema.minLength;

}
if (typeof currentSchema.minLength === "number") {

@@ -38,3 +36,2 @@ if (currentSchema.minLength === 1) {

}
if (typeof currentSchema.maxLength === "number") {

@@ -48,21 +45,17 @@ if (currentSchema.maxLength === 0) {

}
if (currentSchema.pattern) {
hints.push(`should${logic ? "" : " not"} match pattern ${JSON.stringify(currentSchema.pattern)}`);
}
if (currentSchema.format) {
hints.push(`should${logic ? "" : " not"} match format ${JSON.stringify(currentSchema.format)}`);
}
if (currentSchema.formatMinimum) {
hints.push(`should be ${currentSchema.formatExclusiveMinimum ? ">" : ">="} ${JSON.stringify(currentSchema.formatMinimum)}`);
}
if (currentSchema.formatMaximum) {
hints.push(`should be ${currentSchema.formatExclusiveMaximum ? "<" : "<="} ${JSON.stringify(currentSchema.formatMaximum)}`);
}
return [type].concat(hints);
};
/**

@@ -73,35 +66,25 @@ * @param {Schema} schema

*/
module.exports.numberHints = function numberHints(schema, logic) {
const hints = [schema.type === "integer" ? "integer" : "number"];
const range = new Range();
if (typeof schema.minimum === "number") {
range.left(schema.minimum);
}
if (typeof schema.exclusiveMinimum === "number") {
range.left(schema.exclusiveMinimum, true);
}
if (typeof schema.maximum === "number") {
range.right(schema.maximum);
}
if (typeof schema.exclusiveMaximum === "number") {
range.right(schema.exclusiveMaximum, true);
}
const rangeFormat = range.format(logic);
if (rangeFormat) {
hints.push(rangeFormat);
}
if (typeof schema.multipleOf === "number") {
hints.push(`should${logic ? "" : " not"} be multiple of ${schema.multipleOf}`);
}
return hints;
};

@@ -12,2 +12,3 @@ "use strict";

*/
class Range {

@@ -23,5 +24,5 @@ /**

}
return exclusive ? "<" : "<=";
}
/**

@@ -33,4 +34,2 @@ * @param {number} value

*/
static formatRight(value, logic, exclusive) {

@@ -40,5 +39,5 @@ if (logic === false) {

}
return `should be ${Range.getOperator("right", exclusive)} ${value}`;
}
/**

@@ -50,4 +49,2 @@ * @param {number} value

*/
static formatLeft(value, logic, exclusive) {

@@ -57,5 +54,5 @@ if (logic === false) {

}
return `should be ${Range.getOperator("left", exclusive)} ${value}`;
}
/**

@@ -69,4 +66,2 @@ * @param {number} start left side value

*/
static formatRange(start, end, startExclusive, endExclusive, logic) {

@@ -79,2 +74,3 @@ let result = "should be";

}
/**

@@ -85,13 +81,8 @@ * @param {Array<RangeValue>} values

*/
static getRangeValue(values, logic) {
let minMax = logic ? Infinity : -Infinity;
let j = -1;
const predicate = logic ?
/** @type {RangeValueCallback} */
([value]) => value <= minMax :
/** @type {RangeValueCallback} */
const predicate = logic ? /** @type {RangeValueCallback} */
([value]) => value <= minMax : /** @type {RangeValueCallback} */
([value]) => value >= minMax;
for (let i = 0; i < values.length; i++) {

@@ -103,10 +94,7 @@ if (predicate(values[i])) {

}
if (j > -1) {
return values[j];
}
return [Infinity, true];
}
constructor() {

@@ -116,5 +104,5 @@ /** @type {Array<RangeValue>} */

/** @type {Array<RangeValue>} */
this._right = [];
}
/**

@@ -124,7 +112,6 @@ * @param {number} value

*/
left(value, exclusive = false) {
this._left.push([value, exclusive]);
}
/**

@@ -134,7 +121,6 @@ * @param {number} value

*/
right(value, exclusive = false) {
this._right.push([value, exclusive]);
}
/**

@@ -144,34 +130,28 @@ * @param {boolean} logic is not logic applied

*/
format(logic = true) {
const [start, leftExclusive] = Range.getRangeValue(this._left, logic);
const [end, rightExclusive] = Range.getRangeValue(this._right, !logic);
if (!Number.isFinite(start) && !Number.isFinite(end)) {
return "";
}
const realStart = leftExclusive ? start + 1 : start;
const realEnd = rightExclusive ? end - 1 : end; // e.g. 5 < x < 7, 5 < x <= 6, 6 <= x <= 6
const realEnd = rightExclusive ? end - 1 : end;
// e.g. 5 < x < 7, 5 < x <= 6, 6 <= x <= 6
if (realStart === realEnd) {
return `should be ${logic ? "" : "!"}= ${realStart}`;
} // e.g. 4 < x < ∞
}
// e.g. 4 < x < ∞
if (Number.isFinite(start) && !Number.isFinite(end)) {
return Range.formatLeft(start, logic, leftExclusive);
} // e.g. ∞ < x < 4
}
// e.g. ∞ < x < 4
if (!Number.isFinite(start) && Number.isFinite(end)) {
return Range.formatRight(end, logic, rightExclusive);
}
return Range.formatRange(start, end, leftExclusive, rightExclusive, logic);
}
}
module.exports = Range;

@@ -13,21 +13,57 @@ "use strict";

exports.validate = validate;
var _absolutePath = _interopRequireDefault(require("./keywords/absolutePath"));
var _ValidationError = _interopRequireDefault(require("./ValidationError"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @template T
* @param fn {(function(): any) | undefined}
* @returns {function(): T}
*/
const memoize = fn => {
let cache = false;
/** @type {T} */
let result;
return () => {
if (cache) {
return result;
}
result = /** @type {function(): any} */fn();
cache = true;
// Allow to clean up memory for fn
// and all dependent resources
// eslint-disable-next-line no-undefined, no-param-reassign
fn = undefined;
return result;
};
};
const getAjv = memoize(() => {
// Use CommonJS require for ajv libs so TypeScript consumers aren't locked into esModuleInterop (see #110).
// eslint-disable-next-line global-require
const Ajv = require("ajv").default;
// eslint-disable-next-line global-require
const ajvKeywords = require("ajv-keywords").default;
// eslint-disable-next-line global-require
const addFormats = require("ajv-formats").default;
// Use CommonJS require for ajv libs so TypeScript consumers aren't locked into esModuleInterop (see #110).
const Ajv = require("ajv").default;
/**
* @type {Ajv}
*/
const ajv = new Ajv({
strict: false,
allErrors: true,
verbose: true,
$data: true
});
ajvKeywords(ajv, ["instanceof", "patternRequired"]);
addFormats(ajv, {
keywords: true
});
// Custom keywords
(0, _absolutePath.default)(ajv);
return ajv;
});
const ajvKeywords = require("ajv-keywords").default;
const addFormats = require("ajv-formats").default;
/** @typedef {import("json-schema").JSONSchema4} JSONSchema4 */
/** @typedef {import("json-schema").JSONSchema6} JSONSchema6 */
/** @typedef {import("json-schema").JSONSchema7} JSONSchema7 */
/** @typedef {import("ajv").ErrorObject} ErrorObject */

@@ -63,19 +99,2 @@

/**
* @type {Ajv}
*/
const ajv = new Ajv({
strict: false,
allErrors: true,
verbose: true,
$data: true
});
ajvKeywords(ajv, ["instanceof", "patternRequired"]);
addFormats(ajv, {
keywords: true
}); // Custom keywords
(0, _absolutePath.default)(ajv);
/**
* @param {Schema} schema

@@ -86,6 +105,4 @@ * @param {Array<object> | object} options

*/
function validate(schema, options, configuration) {
let errors = [];
if (Array.isArray(options)) {

@@ -101,3 +118,2 @@ errors = Array.from(options, nestedOptions => validateObject(schema, nestedOptions));

error.instancePath = `[${idx}]${error.instancePath}`;
if (error.children) {

@@ -107,3 +123,2 @@ error.children.forEach(applyPrefix);

};
list.forEach(applyPrefix);

@@ -118,3 +133,2 @@ });

}
if (errors.length > 0) {

@@ -124,2 +138,3 @@ throw new _ValidationError.default(errors, schema, configuration);

}
/**

@@ -130,6 +145,4 @@ * @param {Schema} schema

*/
function validateObject(schema, options) {
const compiledSchema = ajv.compile(schema);
const compiledSchema = getAjv().compile(schema);
const valid = compiledSchema(options);

@@ -139,2 +152,3 @@ if (valid) return [];

}
/**

@@ -144,11 +158,6 @@ * @param {Array<ErrorObject>} errors

*/
function filterErrors(errors) {
/** @type {Array<SchemaUtilErrorObject>} */
let newErrors = [];
for (const error of
/** @type {Array<SchemaUtilErrorObject>} */
errors) {
for (const error of /** @type {Array<SchemaUtilErrorObject>} */errors) {
const {

@@ -158,3 +167,2 @@ instancePath

/** @type {Array<SchemaUtilErrorObject>} */
let children = [];

@@ -165,5 +173,5 @@ newErrors = newErrors.filter(oldError => {

children = children.concat(oldError.children.slice(0));
} // eslint-disable-next-line no-undefined, no-param-reassign
}
// eslint-disable-next-line no-undefined, no-param-reassign
oldError.children = undefined;

@@ -173,14 +181,10 @@ children.push(oldError);

}
return true;
});
if (children.length) {
error.children = children;
}
newErrors.push(error);
}
return newErrors;
}

@@ -7,3 +7,2 @@ "use strict";

exports.default = void 0;
const {

@@ -13,17 +12,12 @@ stringHints,

} = require("./util/hints");
/** @typedef {import("json-schema").JSONSchema6} JSONSchema6 */
/** @typedef {import("json-schema").JSONSchema7} JSONSchema7 */
/** @typedef {import("./validate").Schema} Schema */
/** @typedef {import("./validate").ValidationErrorConfiguration} ValidationErrorConfiguration */
/** @typedef {import("./validate").PostFormatter} PostFormatter */
/** @typedef {import("./validate").SchemaUtilErrorObject} SchemaUtilErrorObject */
/** @enum {number} */
const SPECIFICITY = {

@@ -63,2 +57,3 @@ type: 1,

};
/**

@@ -68,6 +63,6 @@ * @param {string} value

*/
function isNumeric(value) {
return /^-?\d+$/.test(value);
}
/**

@@ -79,4 +74,2 @@ *

*/
function filterMax(array, fn) {

@@ -86,2 +79,3 @@ const evaluatedMax = array.reduce((max, item) => Math.max(max, fn(item)), 0);

}
/**

@@ -92,4 +86,2 @@ *

*/
function filterChildren(children) {

@@ -109,7 +101,6 @@ let newChildren = children;

*/
error => SPECIFICITY[
/** @type {keyof typeof SPECIFICITY} */
error.keyword] || 2);
error => SPECIFICITY[/** @type {keyof typeof SPECIFICITY} */error.keyword] || 2);
return newChildren;
}
/**

@@ -121,7 +112,4 @@ * Find all children errors

*/
function findAllChildren(children, schemaPaths) {
let i = children.length - 1;
const predicate =

@@ -133,3 +121,2 @@ /**

schemaPath => children[i].schemaPath.indexOf(schemaPath) !== 0;
while (i > -1 && !schemaPaths.every(predicate)) {

@@ -144,5 +131,5 @@ if (children[i].keyword === "anyOf" || children[i].keyword === "oneOf") {

}
return i + 1;
}
/**

@@ -153,4 +140,2 @@ * Extracts all refs from schema

*/
function extractRefs(error) {

@@ -160,7 +145,5 @@ const {

} = error;
if (!Array.isArray(schema)) {
return [];
}
return schema.map(({

@@ -170,2 +153,3 @@ $ref

}
/**

@@ -176,15 +160,10 @@ * Groups children by their first level parent (assuming that error is root)

*/
function groupChildrenByFirstChild(children) {
const result = [];
let i = children.length - 1;
while (i > 0) {
const child = children[i];
if (child.keyword === "anyOf" || child.keyword === "oneOf") {
const refs = extractRefs(child);
const childrenStart = findAllChildren(children.slice(0, i), refs.concat(child.schemaPath));
if (childrenStart !== i) {

@@ -201,12 +180,10 @@ result.push(Object.assign({}, child, {

}
i -= 1;
}
if (i === 0) {
result.push(children[i]);
}
return result.reverse();
}
/**

@@ -217,7 +194,6 @@ * @param {string} str

*/
function indent(str, prefix) {
return str.replace(/\n(?!$)/g, `\n${prefix}`);
}
/**

@@ -227,7 +203,6 @@ * @param {Schema} schema

*/
function hasNotInSchema(schema) {
return !!schema.not;
}
/**

@@ -237,4 +212,2 @@ * @param {Schema} schema

*/
function findFirstTypedSchema(schema) {

@@ -244,5 +217,5 @@ if (hasNotInSchema(schema)) {

}
return schema;
}
/**

@@ -252,4 +225,2 @@ * @param {Schema} schema

*/
function canApplyNot(schema) {

@@ -259,2 +230,3 @@ const typedSchema = findFirstTypedSchema(schema);

}
/**

@@ -264,7 +236,6 @@ * @param {any} maybeObj

*/
function isObject(maybeObj) {
return typeof maybeObj === "object" && maybeObj !== null;
}
/**

@@ -274,7 +245,6 @@ * @param {Schema} schema

*/
function likeNumber(schema) {
return schema.type === "number" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined";
}
/**

@@ -284,7 +254,6 @@ * @param {Schema} schema

*/
function likeInteger(schema) {
return schema.type === "integer" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined";
}
/**

@@ -294,7 +263,6 @@ * @param {Schema} schema

*/
function likeString(schema) {
return schema.type === "string" || typeof schema.minLength !== "undefined" || typeof schema.maxLength !== "undefined" || typeof schema.pattern !== "undefined" || typeof schema.format !== "undefined" || typeof schema.formatMinimum !== "undefined" || typeof schema.formatMaximum !== "undefined";
}
/**

@@ -304,7 +272,6 @@ * @param {Schema} schema

*/
function likeBoolean(schema) {
return schema.type === "boolean";
}
/**

@@ -314,7 +281,6 @@ * @param {Schema} schema

*/
function likeArray(schema) {
return schema.type === "array" || typeof schema.minItems === "number" || typeof schema.maxItems === "number" || typeof schema.uniqueItems !== "undefined" || typeof schema.items !== "undefined" || typeof schema.additionalItems !== "undefined" || typeof schema.contains !== "undefined";
}
/**

@@ -324,7 +290,6 @@ * @param {Schema & {patternRequired?: Array<string>}} schema

*/
function likeObject(schema) {
return schema.type === "object" || typeof schema.minProperties !== "undefined" || typeof schema.maxProperties !== "undefined" || typeof schema.required !== "undefined" || typeof schema.properties !== "undefined" || typeof schema.patternProperties !== "undefined" || typeof schema.additionalProperties !== "undefined" || typeof schema.dependencies !== "undefined" || typeof schema.propertyNames !== "undefined" || typeof schema.patternRequired !== "undefined";
}
/**

@@ -334,7 +299,6 @@ * @param {Schema} schema

*/
function likeNull(schema) {
return schema.type === "null";
}
/**

@@ -344,4 +308,2 @@ * @param {string} type

*/
function getArticle(type) {

@@ -351,5 +313,5 @@ if (/^[aeiou]/i.test(type)) {

}
return "a";
}
/**

@@ -359,4 +321,2 @@ * @param {Schema=} schema

*/
function getSchemaNonTypes(schema) {

@@ -366,3 +326,2 @@ if (!schema) {

}
if (!schema.type) {

@@ -372,11 +331,8 @@ if (likeNumber(schema) || likeInteger(schema)) {

}
if (likeString(schema)) {
return " | should be any non-string";
}
if (likeArray(schema)) {
return " | should be any non-array";
}
if (likeObject(schema)) {

@@ -386,5 +342,5 @@ return " | should be any non-object";

}
return "";
}
/**

@@ -394,7 +350,6 @@ * @param {Array<string>} hints

*/
function formatHints(hints) {
return hints.length > 0 ? `(${hints.join(", ")})` : "";
}
/**

@@ -405,4 +360,2 @@ * @param {Schema} schema

*/
function getHints(schema, logic) {

@@ -414,6 +367,4 @@ if (likeNumber(schema) || likeInteger(schema)) {

}
return [];
}
class ValidationError extends Error {

@@ -427,17 +378,13 @@ /**

super();
/** @type {string} */
this.name = "ValidationError";
/** @type {Array<SchemaUtilErrorObject>} */
this.errors = errors;
/** @type {Schema} */
this.schema = schema;
let headerNameFromSchema;
let baseDataPathFromSchema;
if (schema.title && (!configuration.name || !configuration.baseDataPath)) {
const splittedTitleFromSchema = schema.title.match(/^(.+) (.+)$/);
if (splittedTitleFromSchema) {

@@ -447,3 +394,2 @@ if (!configuration.name) {

}
if (!configuration.baseDataPath) {

@@ -454,18 +400,17 @@ [,, baseDataPathFromSchema] = splittedTitleFromSchema;

}
/** @type {string} */
this.headerName = configuration.name || headerNameFromSchema || "Object";
/** @type {string} */
this.baseDataPath = configuration.baseDataPath || baseDataPathFromSchema || "configuration";
this.baseDataPath = configuration.baseDataPath || baseDataPathFromSchema || "configuration";
/** @type {PostFormatter | null} */
this.postFormatter = configuration.postFormatter || null;
const header = `Invalid ${this.baseDataPath} object. ${this.headerName} has been initialized using ${getArticle(this.baseDataPath)} ${this.baseDataPath} object that does not match the API schema.\n`;
/** @type {string} */
this.message = `${header}${this.formatValidationErrors(errors)}`;
Error.captureStackTrace(this, this.constructor);
}
/**

@@ -475,22 +420,15 @@ * @param {string} path

*/
getSchemaPart(path) {
const newPath = path.split("/");
let schemaPart = this.schema;
for (let i = 1; i < newPath.length; i++) {
const inner = schemaPart[
/** @type {keyof Schema} */
newPath[i]];
const inner = schemaPart[/** @type {keyof Schema} */newPath[i]];
if (!inner) {
break;
}
schemaPart = inner;
}
return schemaPart;
}
/**

@@ -502,7 +440,4 @@ * @param {Schema} schema

*/
formatSchema(schema, logic = true, prevSchemas = []) {
let newLogic = logic;
const formatInnerSchema =

@@ -519,10 +454,7 @@ /**

}
if (prevSchemas.includes(innerSchema)) {
return "(recursive)";
}
return this.formatSchema(innerSchema, newLogic, prevSchemas.concat(schema));
};
if (hasNotInSchema(schema) && !likeObject(schema)) {

@@ -533,3 +465,2 @@ if (canApplyNot(schema.not)) {

}
const needApplyLogicHere = !schema.not.not;

@@ -540,11 +471,6 @@ const prefix = logic ? "" : "non ";

}
if (
/** @type {Schema & {instanceof: string | Array<string>}} */
schema.instanceof) {
if ( /** @type {Schema & {instanceof: string | Array<string>}} */schema.instanceof) {
const {
instanceof: value
} =
/** @type {Schema & {instanceof: string | Array<string>}} */
schema;
} = /** @type {Schema & {instanceof: string | Array<string>}} */schema;
const values = !Array.isArray(value) ? [value] : value;

@@ -558,38 +484,22 @@ return values.map(

}
if (schema.enum) {
return (
/** @type {Array<any>} */
schema.enum.map(item => JSON.stringify(item)).join(" | ")
return (/** @type {Array<any>} */schema.enum.map(item => JSON.stringify(item)).join(" | ")
);
}
if (typeof schema.const !== "undefined") {
return JSON.stringify(schema.const);
}
if (schema.oneOf) {
return (
/** @type {Array<Schema>} */
schema.oneOf.map(item => formatInnerSchema(item, true)).join(" | ")
return (/** @type {Array<Schema>} */schema.oneOf.map(item => formatInnerSchema(item, true)).join(" | ")
);
}
if (schema.anyOf) {
return (
/** @type {Array<Schema>} */
schema.anyOf.map(item => formatInnerSchema(item, true)).join(" | ")
return (/** @type {Array<Schema>} */schema.anyOf.map(item => formatInnerSchema(item, true)).join(" | ")
);
}
if (schema.allOf) {
return (
/** @type {Array<Schema>} */
schema.allOf.map(item => formatInnerSchema(item, true)).join(" & ")
return (/** @type {Array<Schema>} */schema.allOf.map(item => formatInnerSchema(item, true)).join(" & ")
);
}
if (
/** @type {JSONSchema7} */
schema.if) {
if ( /** @type {JSONSchema7} */schema.if) {
const {

@@ -599,12 +509,8 @@ if: ifValue,

else: elseValue
} =
/** @type {JSONSchema7} */
schema;
} = /** @type {JSONSchema7} */schema;
return `${ifValue ? `if ${formatInnerSchema(ifValue)}` : ""}${thenValue ? ` then ${formatInnerSchema(thenValue)}` : ""}${elseValue ? ` else ${formatInnerSchema(elseValue)}` : ""}`;
}
if (schema.$ref) {
return formatInnerSchema(this.getSchemaPart(schema.$ref), true);
}
if (likeNumber(schema) || likeInteger(schema)) {

@@ -615,3 +521,2 @@ const [type, ...hints] = getHints(schema, logic);

}
if (likeString(schema)) {

@@ -622,7 +527,5 @@ const [type, ...hints] = getHints(schema, logic);

}
if (likeBoolean(schema)) {
return `${logic ? "" : "non-"}boolean`;
}
if (likeArray(schema)) {

@@ -632,24 +535,17 @@ // not logic already applied in formatValidationError

const hints = [];
if (typeof schema.minItems === "number") {
hints.push(`should not have fewer than ${schema.minItems} item${schema.minItems > 1 ? "s" : ""}`);
}
if (typeof schema.maxItems === "number") {
hints.push(`should not have more than ${schema.maxItems} item${schema.maxItems > 1 ? "s" : ""}`);
}
if (schema.uniqueItems) {
hints.push("should not have duplicate items");
}
const hasAdditionalItems = typeof schema.additionalItems === "undefined" || Boolean(schema.additionalItems);
let items = "";
if (schema.items) {
if (Array.isArray(schema.items) && schema.items.length > 0) {
items = `${
/** @type {Array<Schema>} */
schema.items.map(item => formatInnerSchema(item)).join(", ")}`;
/** @type {Array<Schema>} */schema.items.map(item => formatInnerSchema(item)).join(", ")}`;
if (hasAdditionalItems) {

@@ -671,10 +567,7 @@ if (schema.additionalItems && isObject(schema.additionalItems) && Object.keys(schema.additionalItems).length > 0) {

}
if (schema.contains && Object.keys(schema.contains).length > 0) {
hints.push(`should contains at least one ${this.formatSchema(schema.contains)} item`);
}
return `[${items}${hasAdditionalItems ? ", ..." : ""}]${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`;
}
if (likeObject(schema)) {

@@ -684,11 +577,8 @@ // not logic already applied in formatValidationError

const hints = [];
if (typeof schema.minProperties === "number") {
hints.push(`should not have fewer than ${schema.minProperties} ${schema.minProperties > 1 ? "properties" : "property"}`);
}
if (typeof schema.maxProperties === "number") {
hints.push(`should not have more than ${schema.maxProperties} ${schema.minProperties && schema.minProperties > 1 ? "properties" : "property"}`);
}
if (schema.patternProperties && Object.keys(schema.patternProperties).length > 0) {

@@ -698,15 +588,12 @@ const patternProperties = Object.keys(schema.patternProperties);

}
const properties = schema.properties ? Object.keys(schema.properties) : [];
/** @type {Array<string>} */
// @ts-ignore
const required = schema.required ? schema.required : [];
const allProperties = [...new Set(
/** @type {Array<string>} */
[].concat(required).concat(properties))];
const allProperties = [...new Set( /** @type {Array<string>} */[].concat(required).concat(properties))];
const objectStructure = allProperties.map(property => {
const isRequired = required.includes(property); // Some properties need quotes, maybe we should add check
const isRequired = required.includes(property);
// Some properties need quotes, maybe we should add check
// Maybe we should output type of property (`foo: string`), but it is looks very unreadable
return `${property}${isRequired ? "" : "?"}`;

@@ -718,10 +605,6 @@ }).concat(typeof schema.additionalProperties === "undefined" || Boolean(schema.additionalProperties) ? schema.additionalProperties && isObject(schema.additionalProperties) ? [`<key>: ${formatInnerSchema(schema.additionalProperties)}`] : ["…"] : []).join(", ");

patternRequired
} =
/** @type {Schema & {patternRequired?: Array<string>;}} */
schema;
} = /** @type {Schema & {patternRequired?: Array<string>;}} */schema;
if (dependencies) {
Object.keys(dependencies).forEach(dependencyName => {
const dependency = dependencies[dependencyName];
if (Array.isArray(dependency)) {

@@ -734,7 +617,5 @@ hints.push(`should have ${dependency.length > 1 ? "properties" : "property"} ${dependency.map(dep => `'${dep}'`).join(", ")} when property '${dependencyName}' is present`);

}
if (propertyNames && Object.keys(propertyNames).length > 0) {
hints.push(`each property name should match format ${JSON.stringify(schema.propertyNames.format)}`);
}
if (patternRequired && patternRequired.length > 0) {

@@ -748,21 +629,18 @@ hints.push(`should have property matching pattern ${patternRequired.map(

}
return `object {${objectStructure ? ` ${objectStructure} ` : ""}}${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`;
}
if (likeNull(schema)) {
return `${logic ? "" : "non-"}null`;
}
if (Array.isArray(schema.type)) {
// not logic already applied in formatValidationError
return `${schema.type.join(" | ")}`;
} // Fallback for unknown keywords
}
// Fallback for unknown keywords
// not logic already applied in formatValidationError
/* istanbul ignore next */
return JSON.stringify(schema, null, 2);
}
/**

@@ -775,4 +653,2 @@ * @param {Schema=} schemaPart

*/
getSchemaPartText(schemaPart, additionalPath, needDot = false, logic = true) {

@@ -782,10 +658,6 @@ if (!schemaPart) {

}
if (Array.isArray(additionalPath)) {
for (let i = 0; i < additionalPath.length; i++) {
/** @type {Schema | undefined} */
const inner = schemaPart[
/** @type {keyof Schema} */
additionalPath[i]];
const inner = schemaPart[/** @type {keyof Schema} */additionalPath[i]];
if (inner) {

@@ -799,3 +671,2 @@ // eslint-disable-next-line no-param-reassign

}
while (schemaPart.$ref) {

@@ -805,15 +676,12 @@ // eslint-disable-next-line no-param-reassign

}
let schemaText = `${this.formatSchema(schemaPart, logic)}${needDot ? "." : ""}`;
if (schemaPart.description) {
schemaText += `\n-> ${schemaPart.description}`;
}
if (schemaPart.link) {
schemaText += `\n-> Read more at ${schemaPart.link}`;
}
return schemaText;
}
/**

@@ -823,4 +691,2 @@ * @param {Schema=} schemaPart

*/
getSchemaPartDescription(schemaPart) {

@@ -830,3 +696,2 @@ if (!schemaPart) {

}
while (schemaPart.$ref) {

@@ -836,15 +701,12 @@ // eslint-disable-next-line no-param-reassign

}
let schemaText = "";
if (schemaPart.description) {
schemaText += `\n-> ${schemaPart.description}`;
}
if (schemaPart.link) {
schemaText += `\n-> Read more at ${schemaPart.link}`;
}
return schemaText;
}
/**

@@ -854,4 +716,2 @@ * @param {SchemaUtilErrorObject} error

*/
formatValidationError(error) {

@@ -866,3 +726,2 @@ const {

*/
const defaultValue = [];

@@ -879,6 +738,7 @@ const prettyInstancePath = splittedInstancePath.reduce((acc, val) => {

}
return acc;
}, defaultValue).join("");
const instancePath = `${this.baseDataPath}${prettyInstancePath}`; // const { keyword, instancePath: errorInstancePath } = error;
const instancePath = `${this.baseDataPath}${prettyInstancePath}`;
// const { keyword, instancePath: errorInstancePath } = error;
// const instancePath = `${this.baseDataPath}${errorInstancePath.replace(/\//g, '.')}`;

@@ -892,26 +752,18 @@

params
} = error; // eslint-disable-next-line default-case
} = error;
switch (params.type) {
case "number":
return `${instancePath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`;
case "integer":
return `${instancePath} should be an ${this.getSchemaPartText(parentSchema, false, true)}`;
case "string":
return `${instancePath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`;
case "boolean":
return `${instancePath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`;
case "array":
return `${instancePath} should be an array:\n${this.getSchemaPartText(parentSchema)}`;
case "object":
return `${instancePath} should be an object:\n${this.getSchemaPartText(parentSchema)}`;
case "null":
return `${instancePath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`;
default:

@@ -921,3 +773,2 @@ return `${instancePath} should be:\n${this.getSchemaPartText(parentSchema)}`;

}
case "instanceof":

@@ -930,3 +781,2 @@ {

}
case "pattern":

@@ -943,3 +793,2 @@ {

}
case "format":

@@ -956,3 +805,2 @@ {

}
case "formatMinimum":

@@ -973,3 +821,2 @@ case "formatExclusiveMinimum":

}
case "minimum":

@@ -988,13 +835,8 @@ case "maximum":

} = params;
const [, ...hints] = getHints(
/** @type {Schema} */
parentSchema, true);
const [, ...hints] = getHints( /** @type {Schema} */parentSchema, true);
if (hints.length === 0) {
hints.push(`should be ${comparison} ${limit}`);
}
return `${instancePath} ${hints.join(" ")}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
}
case "multipleOf":

@@ -1011,3 +853,2 @@ {

}
case "patternRequired":

@@ -1024,3 +865,2 @@ {

}
case "minLength":

@@ -1035,11 +875,8 @@ {

} = params;
if (limit === 1) {
return `${instancePath} should be a non-empty string${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
}
const length = limit - 1;
return `${instancePath} should be longer than ${length} character${length > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
}
case "minItems":

@@ -1054,10 +891,7 @@ {

} = params;
if (limit === 1) {
return `${instancePath} should be a non-empty array${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
}
return `${instancePath} should not have fewer than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
}
case "minProperties":

@@ -1072,10 +906,7 @@ {

} = params;
if (limit === 1) {
return `${instancePath} should be a non-empty object${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
}
return `${instancePath} should not have fewer than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
}
case "maxLength":

@@ -1093,3 +924,2 @@ {

}
case "maxItems":

@@ -1106,3 +936,2 @@ {

}
case "maxProperties":

@@ -1119,3 +948,2 @@ {

}
case "uniqueItems":

@@ -1131,6 +959,4 @@ {

return `${instancePath} should not contain the item '${
/** @type {{ data: Array<any> }} **/
error.data[i]}' twice${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
/** @type {{ data: Array<any> }} **/error.data[i]}' twice${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
}
case "additionalItems":

@@ -1147,3 +973,2 @@ {

}
case "contains":

@@ -1156,3 +981,2 @@ {

}
case "required":

@@ -1165,10 +989,7 @@ {

const missingProperty = params.missingProperty.replace(/^\./, "");
const hasProperty = parentSchema && Boolean(
/** @type {Schema} */
parentSchema.properties &&
/** @type {Schema} */
const hasProperty = parentSchema && Boolean( /** @type {Schema} */
parentSchema.properties && /** @type {Schema} */
parentSchema.properties[missingProperty]);
return `${instancePath} misses the property '${missingProperty}'${getSchemaNonTypes(parentSchema)}.${hasProperty ? ` Should be:\n${this.getSchemaPartText(parentSchema, ["properties", missingProperty])}` : this.getSchemaPartDescription(parentSchema)}`;
}
case "additionalProperties":

@@ -1185,3 +1006,2 @@ {

}
case "dependencies":

@@ -1205,3 +1025,2 @@ {

}
case "propertyNames":

@@ -1219,3 +1038,2 @@ {

}
case "enum":

@@ -1226,14 +1044,9 @@ {

} = error;
if (parentSchema &&
/** @type {Schema} */
parentSchema.enum &&
/** @type {Schema} */
if (parentSchema && /** @type {Schema} */
parentSchema.enum && /** @type {Schema} */
parentSchema.enum.length === 1) {
return `${instancePath} should be ${this.getSchemaPartText(parentSchema, false, true)}`;
}
return `${instancePath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`;
}
case "const":

@@ -1246,14 +1059,9 @@ {

}
case "not":
{
const postfix = likeObject(
/** @type {Schema} */
error.parentSchema) ? `\n${this.getSchemaPartText(error.parentSchema)}` : "";
const postfix = likeObject( /** @type {Schema} */error.parentSchema) ? `\n${this.getSchemaPartText(error.parentSchema)}` : "";
const schemaOutput = this.getSchemaPartText(error.schema, false, false, false);
if (canApplyNot(error.schema)) {
return `${instancePath} should be any ${schemaOutput}${postfix}.`;
}
const {

@@ -1265,3 +1073,2 @@ schema,

}
case "oneOf":

@@ -1274,3 +1081,2 @@ case "anyOf":

} = error;
if (children && children.length > 0) {

@@ -1285,9 +1091,6 @@ if (error.schema.length === 1) {

}
let filteredChildren = filterChildren(children);
if (filteredChildren.length === 1) {
return this.formatValidationError(filteredChildren[0]);
}
filteredChildren = groupChildrenByFirstChild(filteredChildren);

@@ -1301,6 +1104,4 @@ return `${instancePath} should be one of these:\n${this.getSchemaPartText(parentSchema)}\nDetails:\n${filteredChildren.map(

}
return `${instancePath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`;
}
case "if":

@@ -1317,3 +1118,2 @@ {

}
case "absolutePath":

@@ -1327,5 +1127,3 @@ {

}
/* istanbul ignore next */
default:

@@ -1337,5 +1135,6 @@ {

} = error;
const ErrorInJSON = JSON.stringify(error, null, 2); // For `custom`, `false schema`, `$ref` keywords
const ErrorInJSON = JSON.stringify(error, null, 2);
// For `custom`, `false schema`, `$ref` keywords
// Fallback for unknown keywords
return `${instancePath} ${message} (${ErrorInJSON}).\n${this.getSchemaPartText(parentSchema, false)}`;

@@ -1345,2 +1144,3 @@ }

}
/**

@@ -1350,19 +1150,13 @@ * @param {Array<SchemaUtilErrorObject>} errors

*/
formatValidationErrors(errors) {
return errors.map(error => {
let formattedError = this.formatValidationError(error);
if (this.postFormatter) {
formattedError = this.postFormatter(formattedError, error);
}
return ` - ${indent(formattedError, " ")}`;
}).join("\n");
}
}
var _default = ValidationError;
exports.default = _default;
{
"name": "schema-utils",
"version": "4.0.0",
"version": "4.0.1",
"description": "webpack Validation Utils",

@@ -49,28 +49,28 @@ "license": "MIT",

"@types/json-schema": "^7.0.9",
"ajv": "^8.8.0",
"ajv-keywords": "^5.0.0",
"ajv-formats": "^2.1.1"
"ajv": "^8.9.0",
"ajv-formats": "^2.1.1",
"ajv-keywords": "^5.1.0"
},
"devDependencies": {
"@babel/cli": "^7.16.0",
"@babel/core": "^7.16.0",
"@babel/preset-env": "^7.16.0",
"@commitlint/cli": "^14.1.0",
"@commitlint/config-conventional": "^14.1.0",
"@babel/cli": "^7.17.0",
"@babel/core": "^7.17.0",
"@babel/preset-env": "^7.16.11",
"@commitlint/cli": "^16.1.0",
"@commitlint/config-conventional": "^16.0.0",
"@webpack-contrib/eslint-config-webpack": "^3.0.0",
"babel-jest": "^27.3.1",
"babel-jest": "^27.4.6",
"cross-env": "^7.0.3",
"del": "^6.0.0",
"del-cli": "^4.0.1",
"eslint": "^8.0.1",
"eslint": "^8.8.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-import": "^2.25.3",
"eslint-plugin-import": "^2.25.4",
"husky": "^7.0.4",
"jest": "^27.3.1",
"lint-staged": "^12.0.2",
"jest": "^27.4.7",
"lint-staged": "^12.3.3",
"npm-run-all": "^4.1.5",
"prettier": "^2.4.1",
"prettier": "^2.5.1",
"standard-version": "^9.3.2",
"typescript": "^4.3.5",
"webpack": "^5.64.1"
"typescript": "^4.5.5",
"webpack": "^5.68.0"
},

@@ -77,0 +77,0 @@ "keywords": [

@@ -14,3 +14,2 @@ <div align="center">

[![node][node]][node-url]
[![deps][deps]][deps-url]
[![tests][tests]][tests-url]

@@ -282,4 +281,2 @@ [![coverage][cover]][cover-url]

[node-url]: https://nodejs.org
[deps]: https://david-dm.org/webpack/schema-utils.svg
[deps-url]: https://david-dm.org/webpack/schema-utils
[tests]: https://github.com/webpack/schema-utils/workflows/schema-utils/badge.svg

@@ -286,0 +283,0 @@ [tests-url]: https://github.com/webpack/schema-utils/actions

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc