ValidationError.js 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  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. return (
  408. /** @type {Array<any>} */
  409. schema.enum.map(item => JSON.stringify(item)).join(" | ")
  410. );
  411. }
  412. if (typeof schema.const !== "undefined") {
  413. return JSON.stringify(schema.const);
  414. }
  415. if (schema.oneOf) {
  416. return (
  417. /** @type {Array<Schema>} */
  418. schema.oneOf.map(item => formatInnerSchema(item, true)).join(" | ")
  419. );
  420. }
  421. if (schema.anyOf) {
  422. return (
  423. /** @type {Array<Schema>} */
  424. schema.anyOf.map(item => formatInnerSchema(item, true)).join(" | ")
  425. );
  426. }
  427. if (schema.allOf) {
  428. return (
  429. /** @type {Array<Schema>} */
  430. schema.allOf.map(item => formatInnerSchema(item, true)).join(" & ")
  431. );
  432. }
  433. if (
  434. /** @type {JSONSchema7} */
  435. schema.if) {
  436. const {
  437. if: ifValue,
  438. then: thenValue,
  439. else: elseValue
  440. } =
  441. /** @type {JSONSchema7} */
  442. schema;
  443. return `${ifValue ? `if ${formatInnerSchema(ifValue)}` : ""}${thenValue ? ` then ${formatInnerSchema(thenValue)}` : ""}${elseValue ? ` else ${formatInnerSchema(elseValue)}` : ""}`;
  444. }
  445. if (schema.$ref) {
  446. return formatInnerSchema(this.getSchemaPart(schema.$ref), true);
  447. }
  448. if (likeNumber(schema) || likeInteger(schema)) {
  449. const [type, ...hints] = getHints(schema, logic);
  450. const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`;
  451. return logic ? str : hints.length > 0 ? `non-${type} | ${str}` : `non-${type}`;
  452. }
  453. if (likeString(schema)) {
  454. const [type, ...hints] = getHints(schema, logic);
  455. const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`;
  456. return logic ? str : str === "string" ? "non-string" : `non-string | ${str}`;
  457. }
  458. if (likeBoolean(schema)) {
  459. return `${logic ? "" : "non-"}boolean`;
  460. }
  461. if (likeArray(schema)) {
  462. // not logic already applied in formatValidationError
  463. newLogic = true;
  464. const hints = [];
  465. if (typeof schema.minItems === "number") {
  466. hints.push(`should not have fewer than ${schema.minItems} item${schema.minItems > 1 ? "s" : ""}`);
  467. }
  468. if (typeof schema.maxItems === "number") {
  469. hints.push(`should not have more than ${schema.maxItems} item${schema.maxItems > 1 ? "s" : ""}`);
  470. }
  471. if (schema.uniqueItems) {
  472. hints.push("should not have duplicate items");
  473. }
  474. const hasAdditionalItems = typeof schema.additionalItems === "undefined" || Boolean(schema.additionalItems);
  475. let items = "";
  476. if (schema.items) {
  477. if (Array.isArray(schema.items) && schema.items.length > 0) {
  478. items = `${
  479. /** @type {Array<Schema>} */
  480. schema.items.map(item => formatInnerSchema(item)).join(", ")}`;
  481. if (hasAdditionalItems) {
  482. if (schema.additionalItems && isObject(schema.additionalItems) && Object.keys(schema.additionalItems).length > 0) {
  483. hints.push(`additional items should be ${formatInnerSchema(schema.additionalItems)}`);
  484. }
  485. }
  486. } else if (schema.items && Object.keys(schema.items).length > 0) {
  487. // "additionalItems" is ignored
  488. items = `${formatInnerSchema(schema.items)}`;
  489. } else {
  490. // Fallback for empty `items` value
  491. items = "any";
  492. }
  493. } else {
  494. // "additionalItems" is ignored
  495. items = "any";
  496. }
  497. if (schema.contains && Object.keys(schema.contains).length > 0) {
  498. hints.push(`should contains at least one ${this.formatSchema(schema.contains)} item`);
  499. }
  500. return `[${items}${hasAdditionalItems ? ", ..." : ""}]${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`;
  501. }
  502. if (likeObject(schema)) {
  503. // not logic already applied in formatValidationError
  504. newLogic = true;
  505. const hints = [];
  506. if (typeof schema.minProperties === "number") {
  507. hints.push(`should not have fewer than ${schema.minProperties} ${schema.minProperties > 1 ? "properties" : "property"}`);
  508. }
  509. if (typeof schema.maxProperties === "number") {
  510. hints.push(`should not have more than ${schema.maxProperties} ${schema.minProperties && schema.minProperties > 1 ? "properties" : "property"}`);
  511. }
  512. if (schema.patternProperties && Object.keys(schema.patternProperties).length > 0) {
  513. const patternProperties = Object.keys(schema.patternProperties);
  514. hints.push(`additional property names should match pattern${patternProperties.length > 1 ? "s" : ""} ${patternProperties.map(pattern => JSON.stringify(pattern)).join(" | ")}`);
  515. }
  516. const properties = schema.properties ? Object.keys(schema.properties) : [];
  517. const required = schema.required ? schema.required : [];
  518. const allProperties = [...new Set(
  519. /** @type {Array<string>} */
  520. [].concat(required).concat(properties))];
  521. const objectStructure = allProperties.map(property => {
  522. const isRequired = required.includes(property); // Some properties need quotes, maybe we should add check
  523. // Maybe we should output type of property (`foo: string`), but it is looks very unreadable
  524. return `${property}${isRequired ? "" : "?"}`;
  525. }).concat(typeof schema.additionalProperties === "undefined" || Boolean(schema.additionalProperties) ? schema.additionalProperties && isObject(schema.additionalProperties) ? [`<key>: ${formatInnerSchema(schema.additionalProperties)}`] : ["…"] : []).join(", ");
  526. const {
  527. dependencies,
  528. propertyNames,
  529. patternRequired
  530. } =
  531. /** @type {Schema & {patternRequired?: Array<string>;}} */
  532. schema;
  533. if (dependencies) {
  534. Object.keys(dependencies).forEach(dependencyName => {
  535. const dependency = dependencies[dependencyName];
  536. if (Array.isArray(dependency)) {
  537. hints.push(`should have ${dependency.length > 1 ? "properties" : "property"} ${dependency.map(dep => `'${dep}'`).join(", ")} when property '${dependencyName}' is present`);
  538. } else {
  539. hints.push(`should be valid according to the schema ${formatInnerSchema(dependency)} when property '${dependencyName}' is present`);
  540. }
  541. });
  542. }
  543. if (propertyNames && Object.keys(propertyNames).length > 0) {
  544. hints.push(`each property name should match format ${JSON.stringify(schema.propertyNames.format)}`);
  545. }
  546. if (patternRequired && patternRequired.length > 0) {
  547. hints.push(`should have property matching pattern ${patternRequired.map(
  548. /**
  549. * @param {string} item
  550. * @returns {string}
  551. */
  552. item => JSON.stringify(item))}`);
  553. }
  554. return `object {${objectStructure ? ` ${objectStructure} ` : ""}}${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`;
  555. }
  556. if (likeNull(schema)) {
  557. return `${logic ? "" : "non-"}null`;
  558. }
  559. if (Array.isArray(schema.type)) {
  560. // not logic already applied in formatValidationError
  561. return `${schema.type.join(" | ")}`;
  562. } // Fallback for unknown keywords
  563. // not logic already applied in formatValidationError
  564. /* istanbul ignore next */
  565. return JSON.stringify(schema, null, 2);
  566. }
  567. /**
  568. * @param {Schema=} schemaPart
  569. * @param {(boolean | Array<string>)=} additionalPath
  570. * @param {boolean=} needDot
  571. * @param {boolean=} logic
  572. * @returns {string}
  573. */
  574. getSchemaPartText(schemaPart, additionalPath, needDot = false, logic = true) {
  575. if (!schemaPart) {
  576. return "";
  577. }
  578. if (Array.isArray(additionalPath)) {
  579. for (let i = 0; i < additionalPath.length; i++) {
  580. /** @type {Schema | undefined} */
  581. const inner = schemaPart[
  582. /** @type {keyof Schema} */
  583. additionalPath[i]];
  584. if (inner) {
  585. // eslint-disable-next-line no-param-reassign
  586. schemaPart = inner;
  587. } else {
  588. break;
  589. }
  590. }
  591. }
  592. while (schemaPart.$ref) {
  593. // eslint-disable-next-line no-param-reassign
  594. schemaPart = this.getSchemaPart(schemaPart.$ref);
  595. }
  596. let schemaText = `${this.formatSchema(schemaPart, logic)}${needDot ? "." : ""}`;
  597. if (schemaPart.description) {
  598. schemaText += `\n-> ${schemaPart.description}`;
  599. }
  600. if (schemaPart.link) {
  601. schemaText += `\n-> Read more at ${schemaPart.link}`;
  602. }
  603. return schemaText;
  604. }
  605. /**
  606. * @param {Schema=} schemaPart
  607. * @returns {string}
  608. */
  609. getSchemaPartDescription(schemaPart) {
  610. if (!schemaPart) {
  611. return "";
  612. }
  613. while (schemaPart.$ref) {
  614. // eslint-disable-next-line no-param-reassign
  615. schemaPart = this.getSchemaPart(schemaPart.$ref);
  616. }
  617. let schemaText = "";
  618. if (schemaPart.description) {
  619. schemaText += `\n-> ${schemaPart.description}`;
  620. }
  621. if (schemaPart.link) {
  622. schemaText += `\n-> Read more at ${schemaPart.link}`;
  623. }
  624. return schemaText;
  625. }
  626. /**
  627. * @param {SchemaUtilErrorObject} error
  628. * @returns {string}
  629. */
  630. formatValidationError(error) {
  631. const {
  632. keyword,
  633. dataPath: errorDataPath
  634. } = error;
  635. const dataPath = `${this.baseDataPath}${errorDataPath}`;
  636. switch (keyword) {
  637. case "type":
  638. {
  639. const {
  640. parentSchema,
  641. params
  642. } = error; // eslint-disable-next-line default-case
  643. switch (
  644. /** @type {import("ajv").TypeParams} */
  645. params.type) {
  646. case "number":
  647. return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`;
  648. case "integer":
  649. return `${dataPath} should be an ${this.getSchemaPartText(parentSchema, false, true)}`;
  650. case "string":
  651. return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`;
  652. case "boolean":
  653. return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`;
  654. case "array":
  655. return `${dataPath} should be an array:\n${this.getSchemaPartText(parentSchema)}`;
  656. case "object":
  657. return `${dataPath} should be an object:\n${this.getSchemaPartText(parentSchema)}`;
  658. case "null":
  659. return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`;
  660. default:
  661. return `${dataPath} should be:\n${this.getSchemaPartText(parentSchema)}`;
  662. }
  663. }
  664. case "instanceof":
  665. {
  666. const {
  667. parentSchema
  668. } = error;
  669. return `${dataPath} should be an instance of ${this.getSchemaPartText(parentSchema, false, true)}`;
  670. }
  671. case "pattern":
  672. {
  673. const {
  674. params,
  675. parentSchema
  676. } = error;
  677. const {
  678. pattern
  679. } =
  680. /** @type {import("ajv").PatternParams} */
  681. params;
  682. return `${dataPath} should match pattern ${JSON.stringify(pattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  683. }
  684. case "format":
  685. {
  686. const {
  687. params,
  688. parentSchema
  689. } = error;
  690. const {
  691. format
  692. } =
  693. /** @type {import("ajv").FormatParams} */
  694. params;
  695. return `${dataPath} should match format ${JSON.stringify(format)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  696. }
  697. case "formatMinimum":
  698. case "formatMaximum":
  699. {
  700. const {
  701. params,
  702. parentSchema
  703. } = error;
  704. const {
  705. comparison,
  706. limit
  707. } =
  708. /** @type {import("ajv").ComparisonParams} */
  709. params;
  710. return `${dataPath} should be ${comparison} ${JSON.stringify(limit)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  711. }
  712. case "minimum":
  713. case "maximum":
  714. case "exclusiveMinimum":
  715. case "exclusiveMaximum":
  716. {
  717. const {
  718. parentSchema,
  719. params
  720. } = error;
  721. const {
  722. comparison,
  723. limit
  724. } =
  725. /** @type {import("ajv").ComparisonParams} */
  726. params;
  727. const [, ...hints] = getHints(
  728. /** @type {Schema} */
  729. parentSchema, true);
  730. if (hints.length === 0) {
  731. hints.push(`should be ${comparison} ${limit}`);
  732. }
  733. return `${dataPath} ${hints.join(" ")}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  734. }
  735. case "multipleOf":
  736. {
  737. const {
  738. params,
  739. parentSchema
  740. } = error;
  741. const {
  742. multipleOf
  743. } =
  744. /** @type {import("ajv").MultipleOfParams} */
  745. params;
  746. return `${dataPath} should be multiple of ${multipleOf}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  747. }
  748. case "patternRequired":
  749. {
  750. const {
  751. params,
  752. parentSchema
  753. } = error;
  754. const {
  755. missingPattern
  756. } =
  757. /** @type {import("ajv").PatternRequiredParams} */
  758. params;
  759. return `${dataPath} should have property matching pattern ${JSON.stringify(missingPattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  760. }
  761. case "minLength":
  762. {
  763. const {
  764. params,
  765. parentSchema
  766. } = error;
  767. const {
  768. limit
  769. } =
  770. /** @type {import("ajv").LimitParams} */
  771. params;
  772. if (limit === 1) {
  773. return `${dataPath} should be a non-empty string${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  774. }
  775. const length = limit - 1;
  776. return `${dataPath} should be longer than ${length} character${length > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  777. }
  778. case "minItems":
  779. {
  780. const {
  781. params,
  782. parentSchema
  783. } = error;
  784. const {
  785. limit
  786. } =
  787. /** @type {import("ajv").LimitParams} */
  788. params;
  789. if (limit === 1) {
  790. return `${dataPath} should be a non-empty array${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  791. }
  792. return `${dataPath} should not have fewer than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  793. }
  794. case "minProperties":
  795. {
  796. const {
  797. params,
  798. parentSchema
  799. } = error;
  800. const {
  801. limit
  802. } =
  803. /** @type {import("ajv").LimitParams} */
  804. params;
  805. if (limit === 1) {
  806. return `${dataPath} should be a non-empty object${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  807. }
  808. return `${dataPath} should not have fewer than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  809. }
  810. case "maxLength":
  811. {
  812. const {
  813. params,
  814. parentSchema
  815. } = error;
  816. const {
  817. limit
  818. } =
  819. /** @type {import("ajv").LimitParams} */
  820. params;
  821. const max = limit + 1;
  822. return `${dataPath} should be shorter than ${max} character${max > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  823. }
  824. case "maxItems":
  825. {
  826. const {
  827. params,
  828. parentSchema
  829. } = error;
  830. const {
  831. limit
  832. } =
  833. /** @type {import("ajv").LimitParams} */
  834. params;
  835. return `${dataPath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  836. }
  837. case "maxProperties":
  838. {
  839. const {
  840. params,
  841. parentSchema
  842. } = error;
  843. const {
  844. limit
  845. } =
  846. /** @type {import("ajv").LimitParams} */
  847. params;
  848. return `${dataPath} should not have more than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  849. }
  850. case "uniqueItems":
  851. {
  852. const {
  853. params,
  854. parentSchema
  855. } = error;
  856. const {
  857. i
  858. } =
  859. /** @type {import("ajv").UniqueItemsParams} */
  860. params;
  861. return `${dataPath} should not contain the item '${error.data[i]}' twice${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  862. }
  863. case "additionalItems":
  864. {
  865. const {
  866. params,
  867. parentSchema
  868. } = error;
  869. const {
  870. limit
  871. } =
  872. /** @type {import("ajv").LimitParams} */
  873. params;
  874. return `${dataPath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}. These items are valid:\n${this.getSchemaPartText(parentSchema)}`;
  875. }
  876. case "contains":
  877. {
  878. const {
  879. parentSchema
  880. } = error;
  881. return `${dataPath} should contains at least one ${this.getSchemaPartText(parentSchema, ["contains"])} item${getSchemaNonTypes(parentSchema)}.`;
  882. }
  883. case "required":
  884. {
  885. const {
  886. parentSchema,
  887. params
  888. } = error;
  889. const missingProperty =
  890. /** @type {import("ajv").DependenciesParams} */
  891. params.missingProperty.replace(/^\./, "");
  892. const hasProperty = parentSchema && Boolean(
  893. /** @type {Schema} */
  894. parentSchema.properties &&
  895. /** @type {Schema} */
  896. parentSchema.properties[missingProperty]);
  897. return `${dataPath} misses the property '${missingProperty}'${getSchemaNonTypes(parentSchema)}.${hasProperty ? ` Should be:\n${this.getSchemaPartText(parentSchema, ["properties", missingProperty])}` : this.getSchemaPartDescription(parentSchema)}`;
  898. }
  899. case "additionalProperties":
  900. {
  901. const {
  902. params,
  903. parentSchema
  904. } = error;
  905. const {
  906. additionalProperty
  907. } =
  908. /** @type {import("ajv").AdditionalPropertiesParams} */
  909. params;
  910. return `${dataPath} has an unknown property '${additionalProperty}'${getSchemaNonTypes(parentSchema)}. These properties are valid:\n${this.getSchemaPartText(parentSchema)}`;
  911. }
  912. case "dependencies":
  913. {
  914. const {
  915. params,
  916. parentSchema
  917. } = error;
  918. const {
  919. property,
  920. deps
  921. } =
  922. /** @type {import("ajv").DependenciesParams} */
  923. params;
  924. const dependencies = deps.split(",").map(
  925. /**
  926. * @param {string} dep
  927. * @returns {string}
  928. */
  929. dep => `'${dep.trim()}'`).join(", ");
  930. return `${dataPath} should have properties ${dependencies} when property '${property}' is present${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  931. }
  932. case "propertyNames":
  933. {
  934. const {
  935. params,
  936. parentSchema,
  937. schema
  938. } = error;
  939. const {
  940. propertyName
  941. } =
  942. /** @type {import("ajv").PropertyNamesParams} */
  943. params;
  944. return `${dataPath} property name '${propertyName}' is invalid${getSchemaNonTypes(parentSchema)}. Property names should be match format ${JSON.stringify(schema.format)}.${this.getSchemaPartDescription(parentSchema)}`;
  945. }
  946. case "enum":
  947. {
  948. const {
  949. parentSchema
  950. } = error;
  951. if (parentSchema &&
  952. /** @type {Schema} */
  953. parentSchema.enum &&
  954. /** @type {Schema} */
  955. parentSchema.enum.length === 1) {
  956. return `${dataPath} should be ${this.getSchemaPartText(parentSchema, false, true)}`;
  957. }
  958. return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`;
  959. }
  960. case "const":
  961. {
  962. const {
  963. parentSchema
  964. } = error;
  965. return `${dataPath} should be equal to constant ${this.getSchemaPartText(parentSchema, false, true)}`;
  966. }
  967. case "not":
  968. {
  969. const postfix = likeObject(
  970. /** @type {Schema} */
  971. error.parentSchema) ? `\n${this.getSchemaPartText(error.parentSchema)}` : "";
  972. const schemaOutput = this.getSchemaPartText(error.schema, false, false, false);
  973. if (canApplyNot(error.schema)) {
  974. return `${dataPath} should be any ${schemaOutput}${postfix}.`;
  975. }
  976. const {
  977. schema,
  978. parentSchema
  979. } = error;
  980. return `${dataPath} should not be ${this.getSchemaPartText(schema, false, true)}${parentSchema && likeObject(parentSchema) ? `\n${this.getSchemaPartText(parentSchema)}` : ""}`;
  981. }
  982. case "oneOf":
  983. case "anyOf":
  984. {
  985. const {
  986. parentSchema,
  987. children
  988. } = error;
  989. if (children && children.length > 0) {
  990. if (error.schema.length === 1) {
  991. const lastChild = children[children.length - 1];
  992. const remainingChildren = children.slice(0, children.length - 1);
  993. return this.formatValidationError(Object.assign({}, lastChild, {
  994. children: remainingChildren,
  995. parentSchema: Object.assign({}, parentSchema, lastChild.parentSchema)
  996. }));
  997. }
  998. let filteredChildren = filterChildren(children);
  999. if (filteredChildren.length === 1) {
  1000. return this.formatValidationError(filteredChildren[0]);
  1001. }
  1002. filteredChildren = groupChildrenByFirstChild(filteredChildren);
  1003. return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}\nDetails:\n${filteredChildren.map(
  1004. /**
  1005. * @param {SchemaUtilErrorObject} nestedError
  1006. * @returns {string}
  1007. */
  1008. nestedError => ` * ${indent(this.formatValidationError(nestedError), " ")}`).join("\n")}`;
  1009. }
  1010. return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`;
  1011. }
  1012. case "if":
  1013. {
  1014. const {
  1015. params,
  1016. parentSchema
  1017. } = error;
  1018. const {
  1019. failingKeyword
  1020. } =
  1021. /** @type {import("ajv").IfParams} */
  1022. params;
  1023. return `${dataPath} should match "${failingKeyword}" schema:\n${this.getSchemaPartText(parentSchema, [failingKeyword])}`;
  1024. }
  1025. case "absolutePath":
  1026. {
  1027. const {
  1028. message,
  1029. parentSchema
  1030. } = error;
  1031. return `${dataPath}: ${message}${this.getSchemaPartDescription(parentSchema)}`;
  1032. }
  1033. /* istanbul ignore next */
  1034. default:
  1035. {
  1036. const {
  1037. message,
  1038. parentSchema
  1039. } = error;
  1040. const ErrorInJSON = JSON.stringify(error, null, 2); // For `custom`, `false schema`, `$ref` keywords
  1041. // Fallback for unknown keywords
  1042. return `${dataPath} ${message} (${ErrorInJSON}).\n${this.getSchemaPartText(parentSchema, false)}`;
  1043. }
  1044. }
  1045. }
  1046. /**
  1047. * @param {Array<SchemaUtilErrorObject>} errors
  1048. * @returns {string}
  1049. */
  1050. formatValidationErrors(errors) {
  1051. return errors.map(error => {
  1052. let formattedError = this.formatValidationError(error);
  1053. if (this.postFormatter) {
  1054. formattedError = this.postFormatter(formattedError, error);
  1055. }
  1056. return ` - ${indent(formattedError, " ")}`;
  1057. }).join("\n");
  1058. }
  1059. }
  1060. var _default = ValidationError;
  1061. exports.default = _default;