ValidationError.js 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _memorize = _interopRequireDefault(require("./util/memorize"));
  7. function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
  8. /** @typedef {import("json-schema").JSONSchema6} JSONSchema6 */
  9. /** @typedef {import("json-schema").JSONSchema7} JSONSchema7 */
  10. /** @typedef {import("./validate").Schema} Schema */
  11. /** @typedef {import("./validate").ValidationErrorConfiguration} ValidationErrorConfiguration */
  12. /** @typedef {import("./validate").PostFormatter} PostFormatter */
  13. /** @typedef {import("./validate").SchemaUtilErrorObject} SchemaUtilErrorObject */
  14. /** @enum {number} */
  15. const SPECIFICITY = {
  16. type: 1,
  17. not: 1,
  18. oneOf: 1,
  19. anyOf: 1,
  20. if: 1,
  21. enum: 1,
  22. const: 1,
  23. instanceof: 1,
  24. required: 2,
  25. pattern: 2,
  26. patternRequired: 2,
  27. format: 2,
  28. formatMinimum: 2,
  29. formatMaximum: 2,
  30. minimum: 2,
  31. exclusiveMinimum: 2,
  32. maximum: 2,
  33. exclusiveMaximum: 2,
  34. multipleOf: 2,
  35. uniqueItems: 2,
  36. contains: 2,
  37. minLength: 2,
  38. maxLength: 2,
  39. minItems: 2,
  40. maxItems: 2,
  41. minProperties: 2,
  42. maxProperties: 2,
  43. dependencies: 2,
  44. propertyNames: 2,
  45. additionalItems: 2,
  46. additionalProperties: 2,
  47. absolutePath: 2
  48. };
  49. /**
  50. * @param {string} value
  51. * @returns {value is number}
  52. */
  53. function isNumeric(value) {
  54. return /^-?\d+$/.test(value);
  55. }
  56. /**
  57. *
  58. * @param {Array<SchemaUtilErrorObject>} array
  59. * @param {(item: SchemaUtilErrorObject) => number} fn
  60. * @returns {Array<SchemaUtilErrorObject>}
  61. */
  62. function filterMax(array, fn) {
  63. const evaluatedMax = array.reduce((max, item) => Math.max(max, fn(item)), 0);
  64. return array.filter(item => fn(item) === evaluatedMax);
  65. }
  66. /**
  67. *
  68. * @param {Array<SchemaUtilErrorObject>} children
  69. * @returns {Array<SchemaUtilErrorObject>}
  70. */
  71. function filterChildren(children) {
  72. let newChildren = children;
  73. newChildren = filterMax(newChildren,
  74. /**
  75. *
  76. * @param {SchemaUtilErrorObject} error
  77. * @returns {number}
  78. */
  79. error => error.instancePath ? error.instancePath.length : 0);
  80. newChildren = filterMax(newChildren,
  81. /**
  82. * @param {SchemaUtilErrorObject} error
  83. * @returns {number}
  84. */
  85. error => SPECIFICITY[(/** @type {keyof typeof SPECIFICITY} */error.keyword)] || 2);
  86. return newChildren;
  87. }
  88. /**
  89. * Find all children errors
  90. * @param {Array<SchemaUtilErrorObject>} children
  91. * @param {Array<string>} schemaPaths
  92. * @return {number} returns index of first child
  93. */
  94. function findAllChildren(children, schemaPaths) {
  95. let i = children.length - 1;
  96. const predicate =
  97. /**
  98. * @param {string} schemaPath
  99. * @returns {boolean}
  100. */
  101. schemaPath => children[i].schemaPath.indexOf(schemaPath) !== 0;
  102. while (i > -1 && !schemaPaths.every(predicate)) {
  103. if (children[i].keyword === "anyOf" || children[i].keyword === "oneOf") {
  104. const refs = extractRefs(children[i]);
  105. const childrenStart = findAllChildren(children.slice(0, i), refs.concat(children[i].schemaPath));
  106. i = childrenStart - 1;
  107. } else {
  108. i -= 1;
  109. }
  110. }
  111. return i + 1;
  112. }
  113. /**
  114. * Extracts all refs from schema
  115. * @param {SchemaUtilErrorObject} error
  116. * @return {Array<string>}
  117. */
  118. function extractRefs(error) {
  119. const {
  120. schema
  121. } = error;
  122. if (!Array.isArray(schema)) {
  123. return [];
  124. }
  125. return schema.map(({
  126. $ref
  127. }) => $ref).filter(s => s);
  128. }
  129. /**
  130. * Groups children by their first level parent (assuming that error is root)
  131. * @param {Array<SchemaUtilErrorObject>} children
  132. * @return {Array<SchemaUtilErrorObject>}
  133. */
  134. function groupChildrenByFirstChild(children) {
  135. const result = [];
  136. let i = children.length - 1;
  137. while (i > 0) {
  138. const child = children[i];
  139. if (child.keyword === "anyOf" || child.keyword === "oneOf") {
  140. const refs = extractRefs(child);
  141. const childrenStart = findAllChildren(children.slice(0, i), refs.concat(child.schemaPath));
  142. if (childrenStart !== i) {
  143. result.push(Object.assign({}, child, {
  144. children: children.slice(childrenStart, i)
  145. }));
  146. i = childrenStart;
  147. } else {
  148. result.push(child);
  149. }
  150. } else {
  151. result.push(child);
  152. }
  153. i -= 1;
  154. }
  155. if (i === 0) {
  156. result.push(children[i]);
  157. }
  158. return result.reverse();
  159. }
  160. /**
  161. * @param {string} str
  162. * @param {string} prefix
  163. * @returns {string}
  164. */
  165. function indent(str, prefix) {
  166. return str.replace(/\n(?!$)/g, `\n${prefix}`);
  167. }
  168. /**
  169. * @param {Schema} schema
  170. * @returns {schema is (Schema & {not: Schema})}
  171. */
  172. function hasNotInSchema(schema) {
  173. return !!schema.not;
  174. }
  175. /**
  176. * @param {Schema} schema
  177. * @return {Schema}
  178. */
  179. function findFirstTypedSchema(schema) {
  180. if (hasNotInSchema(schema)) {
  181. return findFirstTypedSchema(schema.not);
  182. }
  183. return schema;
  184. }
  185. /**
  186. * @param {Schema} schema
  187. * @return {boolean}
  188. */
  189. function canApplyNot(schema) {
  190. const typedSchema = findFirstTypedSchema(schema);
  191. return likeNumber(typedSchema) || likeInteger(typedSchema) || likeString(typedSchema) || likeNull(typedSchema) || likeBoolean(typedSchema);
  192. }
  193. /**
  194. * @param {any} maybeObj
  195. * @returns {boolean}
  196. */
  197. function isObject(maybeObj) {
  198. return typeof maybeObj === "object" && !Array.isArray(maybeObj) && maybeObj !== null;
  199. }
  200. /**
  201. * @param {Schema} schema
  202. * @returns {boolean}
  203. */
  204. function likeNumber(schema) {
  205. return schema.type === "number" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined";
  206. }
  207. /**
  208. * @param {Schema} schema
  209. * @returns {boolean}
  210. */
  211. function likeInteger(schema) {
  212. return schema.type === "integer" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined";
  213. }
  214. /**
  215. * @param {Schema} schema
  216. * @returns {boolean}
  217. */
  218. function likeString(schema) {
  219. 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";
  220. }
  221. /**
  222. * @param {Schema} schema
  223. * @returns {boolean}
  224. */
  225. function likeBoolean(schema) {
  226. return schema.type === "boolean";
  227. }
  228. /**
  229. * @param {Schema} schema
  230. * @returns {boolean}
  231. */
  232. function likeArray(schema) {
  233. 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";
  234. }
  235. /**
  236. * @param {Schema & {patternRequired?: Array<string>}} schema
  237. * @returns {boolean}
  238. */
  239. function likeObject(schema) {
  240. 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";
  241. }
  242. /**
  243. * @param {Schema} schema
  244. * @returns {boolean}
  245. */
  246. function likeNull(schema) {
  247. return schema.type === "null";
  248. }
  249. /**
  250. * @param {string} type
  251. * @returns {string}
  252. */
  253. function getArticle(type) {
  254. if (/^[aeiou]/i.test(type)) {
  255. return "an";
  256. }
  257. return "a";
  258. }
  259. /**
  260. * @param {Schema=} schema
  261. * @returns {string}
  262. */
  263. function getSchemaNonTypes(schema) {
  264. if (!schema) {
  265. return "";
  266. }
  267. if (!schema.type) {
  268. if (likeNumber(schema) || likeInteger(schema)) {
  269. return " | should be any non-number";
  270. }
  271. if (likeString(schema)) {
  272. return " | should be any non-string";
  273. }
  274. if (likeArray(schema)) {
  275. return " | should be any non-array";
  276. }
  277. if (likeObject(schema)) {
  278. return " | should be any non-object";
  279. }
  280. }
  281. return "";
  282. }
  283. /**
  284. * @param {Array<string>} hints
  285. * @returns {string}
  286. */
  287. function formatHints(hints) {
  288. return hints.length > 0 ? `(${hints.join(", ")})` : "";
  289. }
  290. const getUtilHints = (0, _memorize.default)(() =>
  291. // eslint-disable-next-line global-require
  292. require("./util/hints"));
  293. /**
  294. * @param {Schema} schema
  295. * @param {boolean} logic
  296. * @returns {string[]}
  297. */
  298. function getHints(schema, logic) {
  299. if (likeNumber(schema) || likeInteger(schema)) {
  300. const util = getUtilHints();
  301. return util.numberHints(schema, logic);
  302. } else if (likeString(schema)) {
  303. const util = getUtilHints();
  304. return util.stringHints(schema, logic);
  305. }
  306. return [];
  307. }
  308. class ValidationError extends Error {
  309. /**
  310. * @param {Array<SchemaUtilErrorObject>} errors
  311. * @param {Schema} schema
  312. * @param {ValidationErrorConfiguration} configuration
  313. */
  314. constructor(errors, schema, configuration = {}) {
  315. super();
  316. /** @type {string} */
  317. this.name = "ValidationError";
  318. /** @type {Array<SchemaUtilErrorObject>} */
  319. this.errors = errors;
  320. /** @type {Schema} */
  321. this.schema = schema;
  322. let headerNameFromSchema;
  323. let baseDataPathFromSchema;
  324. if (schema.title && (!configuration.name || !configuration.baseDataPath)) {
  325. const splittedTitleFromSchema = schema.title.match(/^(.+) (.+)$/);
  326. if (splittedTitleFromSchema) {
  327. if (!configuration.name) {
  328. [, headerNameFromSchema] = splittedTitleFromSchema;
  329. }
  330. if (!configuration.baseDataPath) {
  331. [,, baseDataPathFromSchema] = splittedTitleFromSchema;
  332. }
  333. }
  334. }
  335. /** @type {string} */
  336. this.headerName = configuration.name || headerNameFromSchema || "Object";
  337. /** @type {string} */
  338. this.baseDataPath = configuration.baseDataPath || baseDataPathFromSchema || "configuration";
  339. /** @type {PostFormatter | null} */
  340. this.postFormatter = configuration.postFormatter || null;
  341. 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`;
  342. /** @type {string} */
  343. this.message = `${header}${this.formatValidationErrors(errors)}`;
  344. Error.captureStackTrace(this, this.constructor);
  345. }
  346. /**
  347. * @param {string} path
  348. * @returns {Schema}
  349. */
  350. getSchemaPart(path) {
  351. const newPath = path.split("/");
  352. let schemaPart = this.schema;
  353. for (let i = 1; i < newPath.length; i++) {
  354. const inner = schemaPart[(/** @type {keyof Schema} */newPath[i])];
  355. if (!inner) {
  356. break;
  357. }
  358. schemaPart = inner;
  359. }
  360. return schemaPart;
  361. }
  362. /**
  363. * @param {Schema} schema
  364. * @param {boolean} logic
  365. * @param {Array<Object>} prevSchemas
  366. * @returns {string}
  367. */
  368. formatSchema(schema, logic = true, prevSchemas = []) {
  369. let newLogic = logic;
  370. const formatInnerSchema =
  371. /**
  372. *
  373. * @param {Object} innerSchema
  374. * @param {boolean=} addSelf
  375. * @returns {string}
  376. */
  377. (innerSchema, addSelf) => {
  378. if (!addSelf) {
  379. return this.formatSchema(innerSchema, newLogic, prevSchemas);
  380. }
  381. if (prevSchemas.includes(innerSchema)) {
  382. return "(recursive)";
  383. }
  384. return this.formatSchema(innerSchema, newLogic, prevSchemas.concat(schema));
  385. };
  386. if (hasNotInSchema(schema) && !likeObject(schema)) {
  387. if (canApplyNot(schema.not)) {
  388. newLogic = !logic;
  389. return formatInnerSchema(schema.not);
  390. }
  391. const needApplyLogicHere = !schema.not.not;
  392. const prefix = logic ? "" : "non ";
  393. newLogic = !logic;
  394. return needApplyLogicHere ? prefix + formatInnerSchema(schema.not) : formatInnerSchema(schema.not);
  395. }
  396. if (/** @type {Schema & {instanceof: string | Array<string>}} */schema.instanceof) {
  397. const {
  398. instanceof: value
  399. } = /** @type {Schema & {instanceof: string | Array<string>}} */schema;
  400. const values = !Array.isArray(value) ? [value] : value;
  401. return values.map(
  402. /**
  403. * @param {string} item
  404. * @returns {string}
  405. */
  406. item => item === "Function" ? "function" : item).join(" | ");
  407. }
  408. if (schema.enum) {
  409. const enumValues = /** @type {Array<any>} */schema.enum.map(item => {
  410. if (item === null && schema.undefinedAsNull) {
  411. return `${JSON.stringify(item)} | undefined`;
  412. }
  413. return JSON.stringify(item);
  414. }).join(" | ");
  415. return `${enumValues}`;
  416. }
  417. if (typeof schema.const !== "undefined") {
  418. return JSON.stringify(schema.const);
  419. }
  420. if (schema.oneOf) {
  421. return /** @type {Array<Schema>} */schema.oneOf.map(item => formatInnerSchema(item, true)).join(" | ");
  422. }
  423. if (schema.anyOf) {
  424. return /** @type {Array<Schema>} */schema.anyOf.map(item => formatInnerSchema(item, true)).join(" | ");
  425. }
  426. if (schema.allOf) {
  427. return /** @type {Array<Schema>} */schema.allOf.map(item => formatInnerSchema(item, true)).join(" & ");
  428. }
  429. if (/** @type {JSONSchema7} */schema.if) {
  430. const {
  431. if: ifValue,
  432. then: thenValue,
  433. else: elseValue
  434. } = /** @type {JSONSchema7} */schema;
  435. return `${ifValue ? `if ${formatInnerSchema(ifValue)}` : ""}${thenValue ? ` then ${formatInnerSchema(thenValue)}` : ""}${elseValue ? ` else ${formatInnerSchema(elseValue)}` : ""}`;
  436. }
  437. if (schema.$ref) {
  438. return formatInnerSchema(this.getSchemaPart(schema.$ref), true);
  439. }
  440. if (likeNumber(schema) || likeInteger(schema)) {
  441. const [type, ...hints] = getHints(schema, logic);
  442. const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`;
  443. return logic ? str : hints.length > 0 ? `non-${type} | ${str}` : `non-${type}`;
  444. }
  445. if (likeString(schema)) {
  446. const [type, ...hints] = getHints(schema, logic);
  447. const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`;
  448. return logic ? str : str === "string" ? "non-string" : `non-string | ${str}`;
  449. }
  450. if (likeBoolean(schema)) {
  451. return `${logic ? "" : "non-"}boolean`;
  452. }
  453. if (likeArray(schema)) {
  454. // not logic already applied in formatValidationError
  455. newLogic = true;
  456. const hints = [];
  457. if (typeof schema.minItems === "number") {
  458. hints.push(`should not have fewer than ${schema.minItems} item${schema.minItems > 1 ? "s" : ""}`);
  459. }
  460. if (typeof schema.maxItems === "number") {
  461. hints.push(`should not have more than ${schema.maxItems} item${schema.maxItems > 1 ? "s" : ""}`);
  462. }
  463. if (schema.uniqueItems) {
  464. hints.push("should not have duplicate items");
  465. }
  466. const hasAdditionalItems = typeof schema.additionalItems === "undefined" || Boolean(schema.additionalItems);
  467. let items = "";
  468. if (schema.items) {
  469. if (Array.isArray(schema.items) && schema.items.length > 0) {
  470. items = `${/** @type {Array<Schema>} */schema.items.map(item => formatInnerSchema(item)).join(", ")}`;
  471. if (hasAdditionalItems) {
  472. if (schema.additionalItems && isObject(schema.additionalItems) && Object.keys(schema.additionalItems).length > 0) {
  473. hints.push(`additional items should be ${formatInnerSchema(schema.additionalItems)}`);
  474. }
  475. }
  476. } else if (schema.items && Object.keys(schema.items).length > 0) {
  477. // "additionalItems" is ignored
  478. items = `${formatInnerSchema(schema.items)}`;
  479. } else {
  480. // Fallback for empty `items` value
  481. items = "any";
  482. }
  483. } else {
  484. // "additionalItems" is ignored
  485. items = "any";
  486. }
  487. if (schema.contains && Object.keys(schema.contains).length > 0) {
  488. hints.push(`should contains at least one ${this.formatSchema(schema.contains)} item`);
  489. }
  490. return `[${items}${hasAdditionalItems ? ", ..." : ""}]${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`;
  491. }
  492. if (likeObject(schema)) {
  493. // not logic already applied in formatValidationError
  494. newLogic = true;
  495. const hints = [];
  496. if (typeof schema.minProperties === "number") {
  497. hints.push(`should not have fewer than ${schema.minProperties} ${schema.minProperties > 1 ? "properties" : "property"}`);
  498. }
  499. if (typeof schema.maxProperties === "number") {
  500. hints.push(`should not have more than ${schema.maxProperties} ${schema.minProperties && schema.minProperties > 1 ? "properties" : "property"}`);
  501. }
  502. if (schema.patternProperties && Object.keys(schema.patternProperties).length > 0) {
  503. const patternProperties = Object.keys(schema.patternProperties);
  504. hints.push(`additional property names should match pattern${patternProperties.length > 1 ? "s" : ""} ${patternProperties.map(pattern => JSON.stringify(pattern)).join(" | ")}`);
  505. }
  506. const properties = schema.properties ? Object.keys(schema.properties) : [];
  507. /** @type {Array<string>} */
  508. // @ts-ignore
  509. const required = schema.required ? schema.required : [];
  510. const allProperties = [...new Set(/** @type {Array<string>} */[].concat(required).concat(properties))];
  511. const objectStructure = allProperties.map(property => {
  512. const isRequired = required.includes(property);
  513. // Some properties need quotes, maybe we should add check
  514. // Maybe we should output type of property (`foo: string`), but it is looks very unreadable
  515. return `${property}${isRequired ? "" : "?"}`;
  516. }).concat(typeof schema.additionalProperties === "undefined" || Boolean(schema.additionalProperties) ? schema.additionalProperties && isObject(schema.additionalProperties) ? [`<key>: ${formatInnerSchema(schema.additionalProperties)}`] : ["…"] : []).join(", ");
  517. const {
  518. dependencies,
  519. propertyNames,
  520. patternRequired
  521. } = /** @type {Schema & {patternRequired?: Array<string>;}} */schema;
  522. if (dependencies) {
  523. Object.keys(dependencies).forEach(dependencyName => {
  524. const dependency = dependencies[dependencyName];
  525. if (Array.isArray(dependency)) {
  526. hints.push(`should have ${dependency.length > 1 ? "properties" : "property"} ${dependency.map(dep => `'${dep}'`).join(", ")} when property '${dependencyName}' is present`);
  527. } else {
  528. hints.push(`should be valid according to the schema ${formatInnerSchema(dependency)} when property '${dependencyName}' is present`);
  529. }
  530. });
  531. }
  532. if (propertyNames && Object.keys(propertyNames).length > 0) {
  533. hints.push(`each property name should match format ${JSON.stringify(schema.propertyNames.format)}`);
  534. }
  535. if (patternRequired && patternRequired.length > 0) {
  536. hints.push(`should have property matching pattern ${patternRequired.map(
  537. /**
  538. * @param {string} item
  539. * @returns {string}
  540. */
  541. item => JSON.stringify(item))}`);
  542. }
  543. return `object {${objectStructure ? ` ${objectStructure} ` : ""}}${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`;
  544. }
  545. if (likeNull(schema)) {
  546. return `${logic ? "" : "non-"}null`;
  547. }
  548. if (Array.isArray(schema.type)) {
  549. // not logic already applied in formatValidationError
  550. return `${schema.type.join(" | ")}`;
  551. }
  552. // Fallback for unknown keywords
  553. // not logic already applied in formatValidationError
  554. /* istanbul ignore next */
  555. return JSON.stringify(schema, null, 2);
  556. }
  557. /**
  558. * @param {Schema=} schemaPart
  559. * @param {(boolean | Array<string>)=} additionalPath
  560. * @param {boolean=} needDot
  561. * @param {boolean=} logic
  562. * @returns {string}
  563. */
  564. getSchemaPartText(schemaPart, additionalPath, needDot = false, logic = true) {
  565. if (!schemaPart) {
  566. return "";
  567. }
  568. if (Array.isArray(additionalPath)) {
  569. for (let i = 0; i < additionalPath.length; i++) {
  570. /** @type {Schema | undefined} */
  571. const inner = schemaPart[(/** @type {keyof Schema} */additionalPath[i])];
  572. if (inner) {
  573. // eslint-disable-next-line no-param-reassign
  574. schemaPart = inner;
  575. } else {
  576. break;
  577. }
  578. }
  579. }
  580. while (schemaPart.$ref) {
  581. // eslint-disable-next-line no-param-reassign
  582. schemaPart = this.getSchemaPart(schemaPart.$ref);
  583. }
  584. let schemaText = `${this.formatSchema(schemaPart, logic)}${needDot ? "." : ""}`;
  585. if (schemaPart.description) {
  586. schemaText += `\n-> ${schemaPart.description}`;
  587. }
  588. if (schemaPart.link) {
  589. schemaText += `\n-> Read more at ${schemaPart.link}`;
  590. }
  591. return schemaText;
  592. }
  593. /**
  594. * @param {Schema=} schemaPart
  595. * @returns {string}
  596. */
  597. getSchemaPartDescription(schemaPart) {
  598. if (!schemaPart) {
  599. return "";
  600. }
  601. while (schemaPart.$ref) {
  602. // eslint-disable-next-line no-param-reassign
  603. schemaPart = this.getSchemaPart(schemaPart.$ref);
  604. }
  605. let schemaText = "";
  606. if (schemaPart.description) {
  607. schemaText += `\n-> ${schemaPart.description}`;
  608. }
  609. if (schemaPart.link) {
  610. schemaText += `\n-> Read more at ${schemaPart.link}`;
  611. }
  612. return schemaText;
  613. }
  614. /**
  615. * @param {SchemaUtilErrorObject} error
  616. * @returns {string}
  617. */
  618. formatValidationError(error) {
  619. const {
  620. keyword,
  621. instancePath: errorInstancePath
  622. } = error;
  623. const splittedInstancePath = errorInstancePath.split("/");
  624. /**
  625. * @type {Array<string>}
  626. */
  627. const defaultValue = [];
  628. const prettyInstancePath = splittedInstancePath.reduce((acc, val) => {
  629. if (val.length > 0) {
  630. if (isNumeric(val)) {
  631. acc.push(`[${val}]`);
  632. } else if (/^\[/.test(val)) {
  633. acc.push(val);
  634. } else {
  635. acc.push(`.${val}`);
  636. }
  637. }
  638. return acc;
  639. }, defaultValue).join("");
  640. const instancePath = `${this.baseDataPath}${prettyInstancePath}`;
  641. // const { keyword, instancePath: errorInstancePath } = error;
  642. // const instancePath = `${this.baseDataPath}${errorInstancePath.replace(/\//g, '.')}`;
  643. switch (keyword) {
  644. case "type":
  645. {
  646. const {
  647. parentSchema,
  648. params
  649. } = error;
  650. switch (params.type) {
  651. case "number":
  652. return `${instancePath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`;
  653. case "integer":
  654. return `${instancePath} should be an ${this.getSchemaPartText(parentSchema, false, true)}`;
  655. case "string":
  656. return `${instancePath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`;
  657. case "boolean":
  658. return `${instancePath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`;
  659. case "array":
  660. return `${instancePath} should be an array:\n${this.getSchemaPartText(parentSchema)}`;
  661. case "object":
  662. return `${instancePath} should be an object:\n${this.getSchemaPartText(parentSchema)}`;
  663. case "null":
  664. return `${instancePath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`;
  665. default:
  666. return `${instancePath} should be:\n${this.getSchemaPartText(parentSchema)}`;
  667. }
  668. }
  669. case "instanceof":
  670. {
  671. const {
  672. parentSchema
  673. } = error;
  674. return `${instancePath} should be an instance of ${this.getSchemaPartText(parentSchema, false, true)}`;
  675. }
  676. case "pattern":
  677. {
  678. const {
  679. params,
  680. parentSchema
  681. } = error;
  682. const {
  683. pattern
  684. } = params;
  685. return `${instancePath} should match pattern ${JSON.stringify(pattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  686. }
  687. case "format":
  688. {
  689. const {
  690. params,
  691. parentSchema
  692. } = error;
  693. const {
  694. format
  695. } = params;
  696. return `${instancePath} should match format ${JSON.stringify(format)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  697. }
  698. case "formatMinimum":
  699. case "formatExclusiveMinimum":
  700. case "formatMaximum":
  701. case "formatExclusiveMaximum":
  702. {
  703. const {
  704. params,
  705. parentSchema
  706. } = error;
  707. const {
  708. comparison,
  709. limit
  710. } = params;
  711. return `${instancePath} should be ${comparison} ${JSON.stringify(limit)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  712. }
  713. case "minimum":
  714. case "maximum":
  715. case "exclusiveMinimum":
  716. case "exclusiveMaximum":
  717. {
  718. const {
  719. parentSchema,
  720. params
  721. } = error;
  722. const {
  723. comparison,
  724. limit
  725. } = params;
  726. const [, ...hints] = getHints(/** @type {Schema} */parentSchema, true);
  727. if (hints.length === 0) {
  728. hints.push(`should be ${comparison} ${limit}`);
  729. }
  730. return `${instancePath} ${hints.join(" ")}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  731. }
  732. case "multipleOf":
  733. {
  734. const {
  735. params,
  736. parentSchema
  737. } = error;
  738. const {
  739. multipleOf
  740. } = params;
  741. return `${instancePath} should be multiple of ${multipleOf}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  742. }
  743. case "patternRequired":
  744. {
  745. const {
  746. params,
  747. parentSchema
  748. } = error;
  749. const {
  750. missingPattern
  751. } = params;
  752. return `${instancePath} should have property matching pattern ${JSON.stringify(missingPattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  753. }
  754. case "minLength":
  755. {
  756. const {
  757. params,
  758. parentSchema
  759. } = error;
  760. const {
  761. limit
  762. } = params;
  763. if (limit === 1) {
  764. return `${instancePath} should be a non-empty string${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  765. }
  766. const length = limit - 1;
  767. return `${instancePath} should be longer than ${length} character${length > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  768. }
  769. case "minItems":
  770. {
  771. const {
  772. params,
  773. parentSchema
  774. } = error;
  775. const {
  776. limit
  777. } = params;
  778. if (limit === 1) {
  779. return `${instancePath} should be a non-empty array${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  780. }
  781. return `${instancePath} should not have fewer than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  782. }
  783. case "minProperties":
  784. {
  785. const {
  786. params,
  787. parentSchema
  788. } = error;
  789. const {
  790. limit
  791. } = params;
  792. if (limit === 1) {
  793. return `${instancePath} should be a non-empty object${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  794. }
  795. return `${instancePath} should not have fewer than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  796. }
  797. case "maxLength":
  798. {
  799. const {
  800. params,
  801. parentSchema
  802. } = error;
  803. const {
  804. limit
  805. } = params;
  806. const max = limit + 1;
  807. return `${instancePath} should be shorter than ${max} character${max > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  808. }
  809. case "maxItems":
  810. {
  811. const {
  812. params,
  813. parentSchema
  814. } = error;
  815. const {
  816. limit
  817. } = params;
  818. return `${instancePath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  819. }
  820. case "maxProperties":
  821. {
  822. const {
  823. params,
  824. parentSchema
  825. } = error;
  826. const {
  827. limit
  828. } = params;
  829. return `${instancePath} should not have more than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  830. }
  831. case "uniqueItems":
  832. {
  833. const {
  834. params,
  835. parentSchema
  836. } = error;
  837. const {
  838. i
  839. } = params;
  840. return `${instancePath} should not contain the item '${/** @type {{ data: Array<any> }} **/
  841. error.data[i]}' twice${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  842. }
  843. case "additionalItems":
  844. {
  845. const {
  846. params,
  847. parentSchema
  848. } = error;
  849. const {
  850. limit
  851. } = params;
  852. return `${instancePath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}. These items are valid:\n${this.getSchemaPartText(parentSchema)}`;
  853. }
  854. case "contains":
  855. {
  856. const {
  857. parentSchema
  858. } = error;
  859. return `${instancePath} should contains at least one ${this.getSchemaPartText(parentSchema, ["contains"])} item${getSchemaNonTypes(parentSchema)}.`;
  860. }
  861. case "required":
  862. {
  863. const {
  864. parentSchema,
  865. params
  866. } = error;
  867. const missingProperty = params.missingProperty.replace(/^\./, "");
  868. const hasProperty = parentSchema && Boolean(/** @type {Schema} */
  869. parentSchema.properties && /** @type {Schema} */
  870. parentSchema.properties[missingProperty]);
  871. return `${instancePath} misses the property '${missingProperty}'${getSchemaNonTypes(parentSchema)}.${hasProperty ? ` Should be:\n${this.getSchemaPartText(parentSchema, ["properties", missingProperty])}` : this.getSchemaPartDescription(parentSchema)}`;
  872. }
  873. case "additionalProperties":
  874. {
  875. const {
  876. params,
  877. parentSchema
  878. } = error;
  879. const {
  880. additionalProperty
  881. } = params;
  882. return `${instancePath} has an unknown property '${additionalProperty}'${getSchemaNonTypes(parentSchema)}. These properties are valid:\n${this.getSchemaPartText(parentSchema)}`;
  883. }
  884. case "dependencies":
  885. {
  886. const {
  887. params,
  888. parentSchema
  889. } = error;
  890. const {
  891. property,
  892. deps
  893. } = params;
  894. const dependencies = deps.split(",").map(
  895. /**
  896. * @param {string} dep
  897. * @returns {string}
  898. */
  899. dep => `'${dep.trim()}'`).join(", ");
  900. return `${instancePath} should have properties ${dependencies} when property '${property}' is present${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  901. }
  902. case "propertyNames":
  903. {
  904. const {
  905. params,
  906. parentSchema,
  907. schema
  908. } = error;
  909. const {
  910. propertyName
  911. } = params;
  912. return `${instancePath} property name '${propertyName}' is invalid${getSchemaNonTypes(parentSchema)}. Property names should be match format ${JSON.stringify(schema.format)}.${this.getSchemaPartDescription(parentSchema)}`;
  913. }
  914. case "enum":
  915. {
  916. const {
  917. parentSchema
  918. } = error;
  919. if (parentSchema && /** @type {Schema} */
  920. parentSchema.enum && /** @type {Schema} */
  921. parentSchema.enum.length === 1) {
  922. return `${instancePath} should be ${this.getSchemaPartText(parentSchema, false, true)}`;
  923. }
  924. return `${instancePath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`;
  925. }
  926. case "const":
  927. {
  928. const {
  929. parentSchema
  930. } = error;
  931. return `${instancePath} should be equal to constant ${this.getSchemaPartText(parentSchema, false, true)}`;
  932. }
  933. case "not":
  934. {
  935. const postfix = likeObject(/** @type {Schema} */error.parentSchema) ? `\n${this.getSchemaPartText(error.parentSchema)}` : "";
  936. const schemaOutput = this.getSchemaPartText(error.schema, false, false, false);
  937. if (canApplyNot(error.schema)) {
  938. return `${instancePath} should be any ${schemaOutput}${postfix}.`;
  939. }
  940. const {
  941. schema,
  942. parentSchema
  943. } = error;
  944. return `${instancePath} should not be ${this.getSchemaPartText(schema, false, true)}${parentSchema && likeObject(parentSchema) ? `\n${this.getSchemaPartText(parentSchema)}` : ""}`;
  945. }
  946. case "oneOf":
  947. case "anyOf":
  948. {
  949. const {
  950. parentSchema,
  951. children
  952. } = error;
  953. if (children && children.length > 0) {
  954. if (error.schema.length === 1) {
  955. const lastChild = children[children.length - 1];
  956. const remainingChildren = children.slice(0, children.length - 1);
  957. return this.formatValidationError(Object.assign({}, lastChild, {
  958. children: remainingChildren,
  959. parentSchema: Object.assign({}, parentSchema, lastChild.parentSchema)
  960. }));
  961. }
  962. let filteredChildren = filterChildren(children);
  963. if (filteredChildren.length === 1) {
  964. return this.formatValidationError(filteredChildren[0]);
  965. }
  966. filteredChildren = groupChildrenByFirstChild(filteredChildren);
  967. return `${instancePath} should be one of these:\n${this.getSchemaPartText(parentSchema)}\nDetails:\n${filteredChildren.map(
  968. /**
  969. * @param {SchemaUtilErrorObject} nestedError
  970. * @returns {string}
  971. */
  972. nestedError => ` * ${indent(this.formatValidationError(nestedError), " ")}`).join("\n")}`;
  973. }
  974. return `${instancePath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`;
  975. }
  976. case "if":
  977. {
  978. const {
  979. params,
  980. parentSchema
  981. } = error;
  982. const {
  983. failingKeyword
  984. } = params;
  985. return `${instancePath} should match "${failingKeyword}" schema:\n${this.getSchemaPartText(parentSchema, [failingKeyword])}`;
  986. }
  987. case "absolutePath":
  988. {
  989. const {
  990. message,
  991. parentSchema
  992. } = error;
  993. return `${instancePath}: ${message}${this.getSchemaPartDescription(parentSchema)}`;
  994. }
  995. /* istanbul ignore next */
  996. default:
  997. {
  998. const {
  999. message,
  1000. parentSchema
  1001. } = error;
  1002. const ErrorInJSON = JSON.stringify(error, null, 2);
  1003. // For `custom`, `false schema`, `$ref` keywords
  1004. // Fallback for unknown keywords
  1005. return `${instancePath} ${message} (${ErrorInJSON}).\n${this.getSchemaPartText(parentSchema, false)}`;
  1006. }
  1007. }
  1008. }
  1009. /**
  1010. * @param {Array<SchemaUtilErrorObject>} errors
  1011. * @returns {string}
  1012. */
  1013. formatValidationErrors(errors) {
  1014. return errors.map(error => {
  1015. let formattedError = this.formatValidationError(error);
  1016. if (this.postFormatter) {
  1017. formattedError = this.postFormatter(formattedError, error);
  1018. }
  1019. return ` - ${indent(formattedError, " ")}`;
  1020. }).join("\n");
  1021. }
  1022. }
  1023. var _default = exports.default = ValidationError;