ValidationError.js 36 KB

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