errors.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. import { $constructor } from "./core.js";
  2. import * as util from "./util.js";
  3. const initializer = (inst, def) => {
  4. inst.name = "$ZodError";
  5. Object.defineProperty(inst, "_zod", {
  6. value: inst._zod,
  7. enumerable: false,
  8. });
  9. Object.defineProperty(inst, "issues", {
  10. value: def,
  11. enumerable: false,
  12. });
  13. inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);
  14. Object.defineProperty(inst, "toString", {
  15. value: () => inst.message,
  16. enumerable: false,
  17. });
  18. };
  19. export const $ZodError = $constructor("$ZodError", initializer);
  20. export const $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
  21. export function flattenError(error, mapper = (issue) => issue.message) {
  22. const fieldErrors = {};
  23. const formErrors = [];
  24. for (const sub of error.issues) {
  25. if (sub.path.length > 0) {
  26. fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
  27. fieldErrors[sub.path[0]].push(mapper(sub));
  28. }
  29. else {
  30. formErrors.push(mapper(sub));
  31. }
  32. }
  33. return { formErrors, fieldErrors };
  34. }
  35. export function formatError(error, mapper = (issue) => issue.message) {
  36. const fieldErrors = { _errors: [] };
  37. const processError = (error) => {
  38. for (const issue of error.issues) {
  39. if (issue.code === "invalid_union" && issue.errors.length) {
  40. issue.errors.map((issues) => processError({ issues }));
  41. }
  42. else if (issue.code === "invalid_key") {
  43. processError({ issues: issue.issues });
  44. }
  45. else if (issue.code === "invalid_element") {
  46. processError({ issues: issue.issues });
  47. }
  48. else if (issue.path.length === 0) {
  49. fieldErrors._errors.push(mapper(issue));
  50. }
  51. else {
  52. let curr = fieldErrors;
  53. let i = 0;
  54. while (i < issue.path.length) {
  55. const el = issue.path[i];
  56. const terminal = i === issue.path.length - 1;
  57. if (!terminal) {
  58. curr[el] = curr[el] || { _errors: [] };
  59. }
  60. else {
  61. curr[el] = curr[el] || { _errors: [] };
  62. curr[el]._errors.push(mapper(issue));
  63. }
  64. curr = curr[el];
  65. i++;
  66. }
  67. }
  68. }
  69. };
  70. processError(error);
  71. return fieldErrors;
  72. }
  73. export function treeifyError(error, mapper = (issue) => issue.message) {
  74. const result = { errors: [] };
  75. const processError = (error, path = []) => {
  76. var _a, _b;
  77. for (const issue of error.issues) {
  78. if (issue.code === "invalid_union" && issue.errors.length) {
  79. // regular union error
  80. issue.errors.map((issues) => processError({ issues }, issue.path));
  81. }
  82. else if (issue.code === "invalid_key") {
  83. processError({ issues: issue.issues }, issue.path);
  84. }
  85. else if (issue.code === "invalid_element") {
  86. processError({ issues: issue.issues }, issue.path);
  87. }
  88. else {
  89. const fullpath = [...path, ...issue.path];
  90. if (fullpath.length === 0) {
  91. result.errors.push(mapper(issue));
  92. continue;
  93. }
  94. let curr = result;
  95. let i = 0;
  96. while (i < fullpath.length) {
  97. const el = fullpath[i];
  98. const terminal = i === fullpath.length - 1;
  99. if (typeof el === "string") {
  100. curr.properties ?? (curr.properties = {});
  101. (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });
  102. curr = curr.properties[el];
  103. }
  104. else {
  105. curr.items ?? (curr.items = []);
  106. (_b = curr.items)[el] ?? (_b[el] = { errors: [] });
  107. curr = curr.items[el];
  108. }
  109. if (terminal) {
  110. curr.errors.push(mapper(issue));
  111. }
  112. i++;
  113. }
  114. }
  115. }
  116. };
  117. processError(error);
  118. return result;
  119. }
  120. /** Format a ZodError as a human-readable string in the following form.
  121. *
  122. * From
  123. *
  124. * ```ts
  125. * ZodError {
  126. * issues: [
  127. * {
  128. * expected: 'string',
  129. * code: 'invalid_type',
  130. * path: [ 'username' ],
  131. * message: 'Invalid input: expected string'
  132. * },
  133. * {
  134. * expected: 'number',
  135. * code: 'invalid_type',
  136. * path: [ 'favoriteNumbers', 1 ],
  137. * message: 'Invalid input: expected number'
  138. * }
  139. * ];
  140. * }
  141. * ```
  142. *
  143. * to
  144. *
  145. * ```
  146. * username
  147. * ✖ Expected number, received string at "username
  148. * favoriteNumbers[0]
  149. * ✖ Invalid input: expected number
  150. * ```
  151. */
  152. export function toDotPath(_path) {
  153. const segs = [];
  154. const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg));
  155. for (const seg of path) {
  156. if (typeof seg === "number")
  157. segs.push(`[${seg}]`);
  158. else if (typeof seg === "symbol")
  159. segs.push(`[${JSON.stringify(String(seg))}]`);
  160. else if (/[^\w$]/.test(seg))
  161. segs.push(`[${JSON.stringify(seg)}]`);
  162. else {
  163. if (segs.length)
  164. segs.push(".");
  165. segs.push(seg);
  166. }
  167. }
  168. return segs.join("");
  169. }
  170. export function prettifyError(error) {
  171. const lines = [];
  172. // sort by path length
  173. const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);
  174. // Process each issue
  175. for (const issue of issues) {
  176. lines.push(`✖ ${issue.message}`);
  177. if (issue.path?.length)
  178. lines.push(` → at ${toDotPath(issue.path)}`);
  179. }
  180. // Convert Map to formatted string
  181. return lines.join("\n");
  182. }