msw-dev-tool 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/cjs/lib/handlerStore.js +35 -0
  2. package/dist/cjs/lib/handlerStore.js.map +1 -1
  3. package/dist/cjs/lib/type.js +12 -0
  4. package/dist/cjs/lib/type.js.map +1 -1
  5. package/dist/cjs/lib/util.js +10 -2
  6. package/dist/cjs/lib/util.js.map +1 -1
  7. package/dist/cjs/msw-dev-tool.css +1 -1
  8. package/dist/cjs/node_modules/@radix-ui/react-dialog/dist/index.js +8 -8
  9. package/dist/cjs/node_modules/@radix-ui/themes/dist/esm/components/dialog.js +40 -0
  10. package/dist/cjs/node_modules/@radix-ui/themes/dist/esm/components/dialog.js.map +1 -0
  11. package/dist/cjs/node_modules/@radix-ui/themes/dist/esm/components/dialog.props.js +10 -0
  12. package/dist/cjs/node_modules/@radix-ui/themes/dist/esm/components/dialog.props.js.map +1 -0
  13. package/dist/cjs/node_modules/@radix-ui/themes/dist/esm/components/text-area.js +31 -0
  14. package/dist/cjs/node_modules/@radix-ui/themes/dist/esm/components/text-area.js.map +1 -0
  15. package/dist/cjs/node_modules/@radix-ui/themes/dist/esm/components/text-area.props.js +9 -0
  16. package/dist/cjs/node_modules/@radix-ui/themes/dist/esm/components/text-area.props.js.map +1 -0
  17. package/dist/cjs/node_modules/@radix-ui/themes/dist/esm/components/text-field.js +2 -1
  18. package/dist/cjs/node_modules/@radix-ui/themes/dist/esm/components/text-field.js.map +1 -1
  19. package/dist/cjs/node_modules/@radix-ui/themes/dist/esm/helpers/require-react-element.js +27 -0
  20. package/dist/cjs/node_modules/@radix-ui/themes/dist/esm/helpers/require-react-element.js.map +1 -0
  21. package/dist/cjs/node_modules/radix-ui/dist/internal.js +11 -0
  22. package/dist/cjs/node_modules/radix-ui/dist/internal.js.map +1 -0
  23. package/dist/cjs/node_modules/zod/lib/index.js +4515 -0
  24. package/dist/cjs/node_modules/zod/lib/index.js.map +1 -0
  25. package/dist/cjs/ui/DevToolContent/Form/FormFieldBase.js +18 -0
  26. package/dist/cjs/ui/DevToolContent/Form/FormFieldBase.js.map +1 -0
  27. package/dist/cjs/ui/DevToolContent/Form/InputFormField.js +15 -0
  28. package/dist/cjs/ui/DevToolContent/Form/InputFormField.js.map +1 -0
  29. package/dist/cjs/ui/DevToolContent/Form/Select.js +32 -0
  30. package/dist/cjs/ui/DevToolContent/Form/Select.js.map +1 -0
  31. package/dist/cjs/ui/DevToolContent/Form/SelectFormField.js +14 -0
  32. package/dist/cjs/ui/DevToolContent/Form/SelectFormField.js.map +1 -0
  33. package/dist/cjs/ui/DevToolContent/Form/TextAreaFormField.js +15 -0
  34. package/dist/cjs/ui/DevToolContent/Form/TextAreaFormField.js.map +1 -0
  35. package/dist/cjs/ui/DevToolContent/HandlerTable/BehaviorSelect.js +8 -25
  36. package/dist/cjs/ui/DevToolContent/HandlerTable/BehaviorSelect.js.map +1 -1
  37. package/dist/cjs/ui/DevToolContent/ToolButtonGroup/HandlerForm.js +58 -0
  38. package/dist/cjs/ui/DevToolContent/ToolButtonGroup/HandlerForm.js.map +1 -0
  39. package/dist/cjs/ui/DevToolContent/ToolButtonGroup/index.js +64 -0
  40. package/dist/cjs/ui/DevToolContent/ToolButtonGroup/index.js.map +1 -0
  41. package/dist/cjs/ui/DevToolContent/ToolButtonGroup/schema.js +31 -0
  42. package/dist/cjs/ui/DevToolContent/ToolButtonGroup/schema.js.map +1 -0
  43. package/dist/cjs/ui/DevToolContent/ToolButtonGroup/util.js +24 -0
  44. package/dist/cjs/ui/DevToolContent/ToolButtonGroup/util.js.map +1 -0
  45. package/dist/cjs/ui/MSWDevTool.js +7 -14
  46. package/dist/cjs/ui/MSWDevTool.js.map +1 -1
  47. package/dist/esm/lib/handlerStore.js +35 -1
  48. package/dist/esm/lib/handlerStore.js.map +1 -1
  49. package/dist/esm/lib/type.js +12 -1
  50. package/dist/esm/lib/type.js.map +1 -1
  51. package/dist/esm/lib/util.js +10 -2
  52. package/dist/esm/lib/util.js.map +1 -1
  53. package/dist/esm/msw-dev-tool.css +1 -1
  54. package/dist/esm/node_modules/@radix-ui/themes/dist/esm/components/dialog.js +14 -0
  55. package/dist/esm/node_modules/@radix-ui/themes/dist/esm/components/dialog.js.map +1 -0
  56. package/dist/esm/node_modules/@radix-ui/themes/dist/esm/components/dialog.props.js +8 -0
  57. package/dist/esm/node_modules/@radix-ui/themes/dist/esm/components/dialog.props.js.map +1 -0
  58. package/dist/esm/node_modules/@radix-ui/themes/dist/esm/components/text-area.js +10 -0
  59. package/dist/esm/node_modules/@radix-ui/themes/dist/esm/components/text-area.js.map +1 -0
  60. package/dist/esm/node_modules/@radix-ui/themes/dist/esm/components/text-area.props.js +7 -0
  61. package/dist/esm/node_modules/@radix-ui/themes/dist/esm/components/text-area.props.js.map +1 -0
  62. package/dist/esm/node_modules/@radix-ui/themes/dist/esm/components/text-field.js +2 -1
  63. package/dist/esm/node_modules/@radix-ui/themes/dist/esm/components/text-field.js.map +1 -1
  64. package/dist/esm/node_modules/@radix-ui/themes/dist/esm/helpers/require-react-element.js +6 -0
  65. package/dist/esm/node_modules/@radix-ui/themes/dist/esm/helpers/require-react-element.js.map +1 -0
  66. package/dist/esm/node_modules/radix-ui/dist/internal.js +9 -0
  67. package/dist/esm/node_modules/radix-ui/dist/internal.js.map +1 -0
  68. package/dist/esm/node_modules/zod/lib/index.js +4406 -0
  69. package/dist/esm/node_modules/zod/lib/index.js.map +1 -0
  70. package/dist/esm/ui/DevToolContent/Form/FormFieldBase.js +16 -0
  71. package/dist/esm/ui/DevToolContent/Form/FormFieldBase.js.map +1 -0
  72. package/dist/esm/ui/DevToolContent/Form/InputFormField.js +13 -0
  73. package/dist/esm/ui/DevToolContent/Form/InputFormField.js.map +1 -0
  74. package/dist/esm/ui/DevToolContent/Form/Select.js +30 -0
  75. package/dist/esm/ui/DevToolContent/Form/Select.js.map +1 -0
  76. package/dist/esm/ui/DevToolContent/Form/SelectFormField.js +12 -0
  77. package/dist/esm/ui/DevToolContent/Form/SelectFormField.js.map +1 -0
  78. package/dist/esm/ui/DevToolContent/Form/TextAreaFormField.js +13 -0
  79. package/dist/esm/ui/DevToolContent/Form/TextAreaFormField.js.map +1 -0
  80. package/dist/esm/ui/DevToolContent/HandlerTable/BehaviorSelect.js +8 -25
  81. package/dist/esm/ui/DevToolContent/HandlerTable/BehaviorSelect.js.map +1 -1
  82. package/dist/esm/ui/DevToolContent/ToolButtonGroup/HandlerForm.js +56 -0
  83. package/dist/esm/ui/DevToolContent/ToolButtonGroup/HandlerForm.js.map +1 -0
  84. package/dist/esm/ui/DevToolContent/ToolButtonGroup/index.js +62 -0
  85. package/dist/esm/ui/DevToolContent/ToolButtonGroup/index.js.map +1 -0
  86. package/dist/esm/ui/DevToolContent/ToolButtonGroup/schema.js +29 -0
  87. package/dist/esm/ui/DevToolContent/ToolButtonGroup/schema.js.map +1 -0
  88. package/dist/esm/ui/DevToolContent/ToolButtonGroup/util.js +21 -0
  89. package/dist/esm/ui/DevToolContent/ToolButtonGroup/util.js.map +1 -0
  90. package/dist/esm/ui/MSWDevTool.js +2 -9
  91. package/dist/esm/ui/MSWDevTool.js.map +1 -1
  92. package/dist/types/index.d.ts +14 -1
  93. package/package.json +3 -2
  94. package/dist/cjs/ui/DevToolContent/ToolButtonGroup.js +0 -18
  95. package/dist/cjs/ui/DevToolContent/ToolButtonGroup.js.map +0 -1
  96. package/dist/esm/ui/DevToolContent/ToolButtonGroup.js +0 -16
  97. package/dist/esm/ui/DevToolContent/ToolButtonGroup.js.map +0 -1
@@ -0,0 +1,4406 @@
1
+ var util;
2
+ (function (util) {
3
+ util.assertEqual = (val) => val;
4
+ function assertIs(_arg) { }
5
+ util.assertIs = assertIs;
6
+ function assertNever(_x) {
7
+ throw new Error();
8
+ }
9
+ util.assertNever = assertNever;
10
+ util.arrayToEnum = (items) => {
11
+ const obj = {};
12
+ for (const item of items) {
13
+ obj[item] = item;
14
+ }
15
+ return obj;
16
+ };
17
+ util.getValidEnumValues = (obj) => {
18
+ const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
19
+ const filtered = {};
20
+ for (const k of validKeys) {
21
+ filtered[k] = obj[k];
22
+ }
23
+ return util.objectValues(filtered);
24
+ };
25
+ util.objectValues = (obj) => {
26
+ return util.objectKeys(obj).map(function (e) {
27
+ return obj[e];
28
+ });
29
+ };
30
+ util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
31
+ ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
32
+ : (object) => {
33
+ const keys = [];
34
+ for (const key in object) {
35
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
36
+ keys.push(key);
37
+ }
38
+ }
39
+ return keys;
40
+ };
41
+ util.find = (arr, checker) => {
42
+ for (const item of arr) {
43
+ if (checker(item))
44
+ return item;
45
+ }
46
+ return undefined;
47
+ };
48
+ util.isInteger = typeof Number.isInteger === "function"
49
+ ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
50
+ : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
51
+ function joinValues(array, separator = " | ") {
52
+ return array
53
+ .map((val) => (typeof val === "string" ? `'${val}'` : val))
54
+ .join(separator);
55
+ }
56
+ util.joinValues = joinValues;
57
+ util.jsonStringifyReplacer = (_, value) => {
58
+ if (typeof value === "bigint") {
59
+ return value.toString();
60
+ }
61
+ return value;
62
+ };
63
+ })(util || (util = {}));
64
+ var objectUtil;
65
+ (function (objectUtil) {
66
+ objectUtil.mergeShapes = (first, second) => {
67
+ return {
68
+ ...first,
69
+ ...second, // second overwrites first
70
+ };
71
+ };
72
+ })(objectUtil || (objectUtil = {}));
73
+ const ZodParsedType = util.arrayToEnum([
74
+ "string",
75
+ "nan",
76
+ "number",
77
+ "integer",
78
+ "float",
79
+ "boolean",
80
+ "date",
81
+ "bigint",
82
+ "symbol",
83
+ "function",
84
+ "undefined",
85
+ "null",
86
+ "array",
87
+ "object",
88
+ "unknown",
89
+ "promise",
90
+ "void",
91
+ "never",
92
+ "map",
93
+ "set",
94
+ ]);
95
+ const getParsedType = (data) => {
96
+ const t = typeof data;
97
+ switch (t) {
98
+ case "undefined":
99
+ return ZodParsedType.undefined;
100
+ case "string":
101
+ return ZodParsedType.string;
102
+ case "number":
103
+ return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
104
+ case "boolean":
105
+ return ZodParsedType.boolean;
106
+ case "function":
107
+ return ZodParsedType.function;
108
+ case "bigint":
109
+ return ZodParsedType.bigint;
110
+ case "symbol":
111
+ return ZodParsedType.symbol;
112
+ case "object":
113
+ if (Array.isArray(data)) {
114
+ return ZodParsedType.array;
115
+ }
116
+ if (data === null) {
117
+ return ZodParsedType.null;
118
+ }
119
+ if (data.then &&
120
+ typeof data.then === "function" &&
121
+ data.catch &&
122
+ typeof data.catch === "function") {
123
+ return ZodParsedType.promise;
124
+ }
125
+ if (typeof Map !== "undefined" && data instanceof Map) {
126
+ return ZodParsedType.map;
127
+ }
128
+ if (typeof Set !== "undefined" && data instanceof Set) {
129
+ return ZodParsedType.set;
130
+ }
131
+ if (typeof Date !== "undefined" && data instanceof Date) {
132
+ return ZodParsedType.date;
133
+ }
134
+ return ZodParsedType.object;
135
+ default:
136
+ return ZodParsedType.unknown;
137
+ }
138
+ };
139
+
140
+ const ZodIssueCode = util.arrayToEnum([
141
+ "invalid_type",
142
+ "invalid_literal",
143
+ "custom",
144
+ "invalid_union",
145
+ "invalid_union_discriminator",
146
+ "invalid_enum_value",
147
+ "unrecognized_keys",
148
+ "invalid_arguments",
149
+ "invalid_return_type",
150
+ "invalid_date",
151
+ "invalid_string",
152
+ "too_small",
153
+ "too_big",
154
+ "invalid_intersection_types",
155
+ "not_multiple_of",
156
+ "not_finite",
157
+ ]);
158
+ const quotelessJson = (obj) => {
159
+ const json = JSON.stringify(obj, null, 2);
160
+ return json.replace(/"([^"]+)":/g, "$1:");
161
+ };
162
+ class ZodError extends Error {
163
+ get errors() {
164
+ return this.issues;
165
+ }
166
+ constructor(issues) {
167
+ super();
168
+ this.issues = [];
169
+ this.addIssue = (sub) => {
170
+ this.issues = [...this.issues, sub];
171
+ };
172
+ this.addIssues = (subs = []) => {
173
+ this.issues = [...this.issues, ...subs];
174
+ };
175
+ const actualProto = new.target.prototype;
176
+ if (Object.setPrototypeOf) {
177
+ // eslint-disable-next-line ban/ban
178
+ Object.setPrototypeOf(this, actualProto);
179
+ }
180
+ else {
181
+ this.__proto__ = actualProto;
182
+ }
183
+ this.name = "ZodError";
184
+ this.issues = issues;
185
+ }
186
+ format(_mapper) {
187
+ const mapper = _mapper ||
188
+ function (issue) {
189
+ return issue.message;
190
+ };
191
+ const fieldErrors = { _errors: [] };
192
+ const processError = (error) => {
193
+ for (const issue of error.issues) {
194
+ if (issue.code === "invalid_union") {
195
+ issue.unionErrors.map(processError);
196
+ }
197
+ else if (issue.code === "invalid_return_type") {
198
+ processError(issue.returnTypeError);
199
+ }
200
+ else if (issue.code === "invalid_arguments") {
201
+ processError(issue.argumentsError);
202
+ }
203
+ else if (issue.path.length === 0) {
204
+ fieldErrors._errors.push(mapper(issue));
205
+ }
206
+ else {
207
+ let curr = fieldErrors;
208
+ let i = 0;
209
+ while (i < issue.path.length) {
210
+ const el = issue.path[i];
211
+ const terminal = i === issue.path.length - 1;
212
+ if (!terminal) {
213
+ curr[el] = curr[el] || { _errors: [] };
214
+ // if (typeof el === "string") {
215
+ // curr[el] = curr[el] || { _errors: [] };
216
+ // } else if (typeof el === "number") {
217
+ // const errorArray: any = [];
218
+ // errorArray._errors = [];
219
+ // curr[el] = curr[el] || errorArray;
220
+ // }
221
+ }
222
+ else {
223
+ curr[el] = curr[el] || { _errors: [] };
224
+ curr[el]._errors.push(mapper(issue));
225
+ }
226
+ curr = curr[el];
227
+ i++;
228
+ }
229
+ }
230
+ }
231
+ };
232
+ processError(this);
233
+ return fieldErrors;
234
+ }
235
+ static assert(value) {
236
+ if (!(value instanceof ZodError)) {
237
+ throw new Error(`Not a ZodError: ${value}`);
238
+ }
239
+ }
240
+ toString() {
241
+ return this.message;
242
+ }
243
+ get message() {
244
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
245
+ }
246
+ get isEmpty() {
247
+ return this.issues.length === 0;
248
+ }
249
+ flatten(mapper = (issue) => issue.message) {
250
+ const fieldErrors = {};
251
+ const formErrors = [];
252
+ for (const sub of this.issues) {
253
+ if (sub.path.length > 0) {
254
+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
255
+ fieldErrors[sub.path[0]].push(mapper(sub));
256
+ }
257
+ else {
258
+ formErrors.push(mapper(sub));
259
+ }
260
+ }
261
+ return { formErrors, fieldErrors };
262
+ }
263
+ get formErrors() {
264
+ return this.flatten();
265
+ }
266
+ }
267
+ ZodError.create = (issues) => {
268
+ const error = new ZodError(issues);
269
+ return error;
270
+ };
271
+
272
+ const errorMap = (issue, _ctx) => {
273
+ let message;
274
+ switch (issue.code) {
275
+ case ZodIssueCode.invalid_type:
276
+ if (issue.received === ZodParsedType.undefined) {
277
+ message = "Required";
278
+ }
279
+ else {
280
+ message = `Expected ${issue.expected}, received ${issue.received}`;
281
+ }
282
+ break;
283
+ case ZodIssueCode.invalid_literal:
284
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
285
+ break;
286
+ case ZodIssueCode.unrecognized_keys:
287
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
288
+ break;
289
+ case ZodIssueCode.invalid_union:
290
+ message = `Invalid input`;
291
+ break;
292
+ case ZodIssueCode.invalid_union_discriminator:
293
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
294
+ break;
295
+ case ZodIssueCode.invalid_enum_value:
296
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
297
+ break;
298
+ case ZodIssueCode.invalid_arguments:
299
+ message = `Invalid function arguments`;
300
+ break;
301
+ case ZodIssueCode.invalid_return_type:
302
+ message = `Invalid function return type`;
303
+ break;
304
+ case ZodIssueCode.invalid_date:
305
+ message = `Invalid date`;
306
+ break;
307
+ case ZodIssueCode.invalid_string:
308
+ if (typeof issue.validation === "object") {
309
+ if ("includes" in issue.validation) {
310
+ message = `Invalid input: must include "${issue.validation.includes}"`;
311
+ if (typeof issue.validation.position === "number") {
312
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
313
+ }
314
+ }
315
+ else if ("startsWith" in issue.validation) {
316
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
317
+ }
318
+ else if ("endsWith" in issue.validation) {
319
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
320
+ }
321
+ else {
322
+ util.assertNever(issue.validation);
323
+ }
324
+ }
325
+ else if (issue.validation !== "regex") {
326
+ message = `Invalid ${issue.validation}`;
327
+ }
328
+ else {
329
+ message = "Invalid";
330
+ }
331
+ break;
332
+ case ZodIssueCode.too_small:
333
+ if (issue.type === "array")
334
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
335
+ else if (issue.type === "string")
336
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
337
+ else if (issue.type === "number")
338
+ message = `Number must be ${issue.exact
339
+ ? `exactly equal to `
340
+ : issue.inclusive
341
+ ? `greater than or equal to `
342
+ : `greater than `}${issue.minimum}`;
343
+ else if (issue.type === "date")
344
+ message = `Date must be ${issue.exact
345
+ ? `exactly equal to `
346
+ : issue.inclusive
347
+ ? `greater than or equal to `
348
+ : `greater than `}${new Date(Number(issue.minimum))}`;
349
+ else
350
+ message = "Invalid input";
351
+ break;
352
+ case ZodIssueCode.too_big:
353
+ if (issue.type === "array")
354
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
355
+ else if (issue.type === "string")
356
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
357
+ else if (issue.type === "number")
358
+ message = `Number must be ${issue.exact
359
+ ? `exactly`
360
+ : issue.inclusive
361
+ ? `less than or equal to`
362
+ : `less than`} ${issue.maximum}`;
363
+ else if (issue.type === "bigint")
364
+ message = `BigInt must be ${issue.exact
365
+ ? `exactly`
366
+ : issue.inclusive
367
+ ? `less than or equal to`
368
+ : `less than`} ${issue.maximum}`;
369
+ else if (issue.type === "date")
370
+ message = `Date must be ${issue.exact
371
+ ? `exactly`
372
+ : issue.inclusive
373
+ ? `smaller than or equal to`
374
+ : `smaller than`} ${new Date(Number(issue.maximum))}`;
375
+ else
376
+ message = "Invalid input";
377
+ break;
378
+ case ZodIssueCode.custom:
379
+ message = `Invalid input`;
380
+ break;
381
+ case ZodIssueCode.invalid_intersection_types:
382
+ message = `Intersection results could not be merged`;
383
+ break;
384
+ case ZodIssueCode.not_multiple_of:
385
+ message = `Number must be a multiple of ${issue.multipleOf}`;
386
+ break;
387
+ case ZodIssueCode.not_finite:
388
+ message = "Number must be finite";
389
+ break;
390
+ default:
391
+ message = _ctx.defaultError;
392
+ util.assertNever(issue);
393
+ }
394
+ return { message };
395
+ };
396
+
397
+ let overrideErrorMap = errorMap;
398
+ function setErrorMap(map) {
399
+ overrideErrorMap = map;
400
+ }
401
+ function getErrorMap() {
402
+ return overrideErrorMap;
403
+ }
404
+
405
+ const makeIssue = (params) => {
406
+ const { data, path, errorMaps, issueData } = params;
407
+ const fullPath = [...path, ...(issueData.path || [])];
408
+ const fullIssue = {
409
+ ...issueData,
410
+ path: fullPath,
411
+ };
412
+ if (issueData.message !== undefined) {
413
+ return {
414
+ ...issueData,
415
+ path: fullPath,
416
+ message: issueData.message,
417
+ };
418
+ }
419
+ let errorMessage = "";
420
+ const maps = errorMaps
421
+ .filter((m) => !!m)
422
+ .slice()
423
+ .reverse();
424
+ for (const map of maps) {
425
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
426
+ }
427
+ return {
428
+ ...issueData,
429
+ path: fullPath,
430
+ message: errorMessage,
431
+ };
432
+ };
433
+ const EMPTY_PATH = [];
434
+ function addIssueToContext(ctx, issueData) {
435
+ const overrideMap = getErrorMap();
436
+ const issue = makeIssue({
437
+ issueData: issueData,
438
+ data: ctx.data,
439
+ path: ctx.path,
440
+ errorMaps: [
441
+ ctx.common.contextualErrorMap, // contextual error map is first priority
442
+ ctx.schemaErrorMap, // then schema-bound map if available
443
+ overrideMap, // then global override map
444
+ overrideMap === errorMap ? undefined : errorMap, // then global default map
445
+ ].filter((x) => !!x),
446
+ });
447
+ ctx.common.issues.push(issue);
448
+ }
449
+ class ParseStatus {
450
+ constructor() {
451
+ this.value = "valid";
452
+ }
453
+ dirty() {
454
+ if (this.value === "valid")
455
+ this.value = "dirty";
456
+ }
457
+ abort() {
458
+ if (this.value !== "aborted")
459
+ this.value = "aborted";
460
+ }
461
+ static mergeArray(status, results) {
462
+ const arrayValue = [];
463
+ for (const s of results) {
464
+ if (s.status === "aborted")
465
+ return INVALID;
466
+ if (s.status === "dirty")
467
+ status.dirty();
468
+ arrayValue.push(s.value);
469
+ }
470
+ return { status: status.value, value: arrayValue };
471
+ }
472
+ static async mergeObjectAsync(status, pairs) {
473
+ const syncPairs = [];
474
+ for (const pair of pairs) {
475
+ const key = await pair.key;
476
+ const value = await pair.value;
477
+ syncPairs.push({
478
+ key,
479
+ value,
480
+ });
481
+ }
482
+ return ParseStatus.mergeObjectSync(status, syncPairs);
483
+ }
484
+ static mergeObjectSync(status, pairs) {
485
+ const finalObject = {};
486
+ for (const pair of pairs) {
487
+ const { key, value } = pair;
488
+ if (key.status === "aborted")
489
+ return INVALID;
490
+ if (value.status === "aborted")
491
+ return INVALID;
492
+ if (key.status === "dirty")
493
+ status.dirty();
494
+ if (value.status === "dirty")
495
+ status.dirty();
496
+ if (key.value !== "__proto__" &&
497
+ (typeof value.value !== "undefined" || pair.alwaysSet)) {
498
+ finalObject[key.value] = value.value;
499
+ }
500
+ }
501
+ return { status: status.value, value: finalObject };
502
+ }
503
+ }
504
+ const INVALID = Object.freeze({
505
+ status: "aborted",
506
+ });
507
+ const DIRTY = (value) => ({ status: "dirty", value });
508
+ const OK = (value) => ({ status: "valid", value });
509
+ const isAborted = (x) => x.status === "aborted";
510
+ const isDirty = (x) => x.status === "dirty";
511
+ const isValid = (x) => x.status === "valid";
512
+ const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
513
+
514
+ /******************************************************************************
515
+ Copyright (c) Microsoft Corporation.
516
+
517
+ Permission to use, copy, modify, and/or distribute this software for any
518
+ purpose with or without fee is hereby granted.
519
+
520
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
521
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
522
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
523
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
524
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
525
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
526
+ PERFORMANCE OF THIS SOFTWARE.
527
+ ***************************************************************************** */
528
+
529
+ function __classPrivateFieldGet(receiver, state, kind, f) {
530
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
531
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
532
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
533
+ }
534
+
535
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
536
+ if (kind === "m") throw new TypeError("Private method is not writable");
537
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
538
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
539
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
540
+ }
541
+
542
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
543
+ var e = new Error(message);
544
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
545
+ };
546
+
547
+ var errorUtil;
548
+ (function (errorUtil) {
549
+ errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
550
+ errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
551
+ })(errorUtil || (errorUtil = {}));
552
+
553
+ var _ZodEnum_cache, _ZodNativeEnum_cache;
554
+ class ParseInputLazyPath {
555
+ constructor(parent, value, path, key) {
556
+ this._cachedPath = [];
557
+ this.parent = parent;
558
+ this.data = value;
559
+ this._path = path;
560
+ this._key = key;
561
+ }
562
+ get path() {
563
+ if (!this._cachedPath.length) {
564
+ if (this._key instanceof Array) {
565
+ this._cachedPath.push(...this._path, ...this._key);
566
+ }
567
+ else {
568
+ this._cachedPath.push(...this._path, this._key);
569
+ }
570
+ }
571
+ return this._cachedPath;
572
+ }
573
+ }
574
+ const handleResult = (ctx, result) => {
575
+ if (isValid(result)) {
576
+ return { success: true, data: result.value };
577
+ }
578
+ else {
579
+ if (!ctx.common.issues.length) {
580
+ throw new Error("Validation failed but no issues detected.");
581
+ }
582
+ return {
583
+ success: false,
584
+ get error() {
585
+ if (this._error)
586
+ return this._error;
587
+ const error = new ZodError(ctx.common.issues);
588
+ this._error = error;
589
+ return this._error;
590
+ },
591
+ };
592
+ }
593
+ };
594
+ function processCreateParams(params) {
595
+ if (!params)
596
+ return {};
597
+ const { errorMap, invalid_type_error, required_error, description } = params;
598
+ if (errorMap && (invalid_type_error || required_error)) {
599
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
600
+ }
601
+ if (errorMap)
602
+ return { errorMap: errorMap, description };
603
+ const customMap = (iss, ctx) => {
604
+ var _a, _b;
605
+ const { message } = params;
606
+ if (iss.code === "invalid_enum_value") {
607
+ return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
608
+ }
609
+ if (typeof ctx.data === "undefined") {
610
+ return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };
611
+ }
612
+ if (iss.code !== "invalid_type")
613
+ return { message: ctx.defaultError };
614
+ return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
615
+ };
616
+ return { errorMap: customMap, description };
617
+ }
618
+ class ZodType {
619
+ get description() {
620
+ return this._def.description;
621
+ }
622
+ _getType(input) {
623
+ return getParsedType(input.data);
624
+ }
625
+ _getOrReturnCtx(input, ctx) {
626
+ return (ctx || {
627
+ common: input.parent.common,
628
+ data: input.data,
629
+ parsedType: getParsedType(input.data),
630
+ schemaErrorMap: this._def.errorMap,
631
+ path: input.path,
632
+ parent: input.parent,
633
+ });
634
+ }
635
+ _processInputParams(input) {
636
+ return {
637
+ status: new ParseStatus(),
638
+ ctx: {
639
+ common: input.parent.common,
640
+ data: input.data,
641
+ parsedType: getParsedType(input.data),
642
+ schemaErrorMap: this._def.errorMap,
643
+ path: input.path,
644
+ parent: input.parent,
645
+ },
646
+ };
647
+ }
648
+ _parseSync(input) {
649
+ const result = this._parse(input);
650
+ if (isAsync(result)) {
651
+ throw new Error("Synchronous parse encountered promise.");
652
+ }
653
+ return result;
654
+ }
655
+ _parseAsync(input) {
656
+ const result = this._parse(input);
657
+ return Promise.resolve(result);
658
+ }
659
+ parse(data, params) {
660
+ const result = this.safeParse(data, params);
661
+ if (result.success)
662
+ return result.data;
663
+ throw result.error;
664
+ }
665
+ safeParse(data, params) {
666
+ var _a;
667
+ const ctx = {
668
+ common: {
669
+ issues: [],
670
+ async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
671
+ contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
672
+ },
673
+ path: (params === null || params === void 0 ? void 0 : params.path) || [],
674
+ schemaErrorMap: this._def.errorMap,
675
+ parent: null,
676
+ data,
677
+ parsedType: getParsedType(data),
678
+ };
679
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
680
+ return handleResult(ctx, result);
681
+ }
682
+ "~validate"(data) {
683
+ var _a, _b;
684
+ const ctx = {
685
+ common: {
686
+ issues: [],
687
+ async: !!this["~standard"].async,
688
+ },
689
+ path: [],
690
+ schemaErrorMap: this._def.errorMap,
691
+ parent: null,
692
+ data,
693
+ parsedType: getParsedType(data),
694
+ };
695
+ if (!this["~standard"].async) {
696
+ try {
697
+ const result = this._parseSync({ data, path: [], parent: ctx });
698
+ return isValid(result)
699
+ ? {
700
+ value: result.value,
701
+ }
702
+ : {
703
+ issues: ctx.common.issues,
704
+ };
705
+ }
706
+ catch (err) {
707
+ if ((_b = (_a = err === null || err === void 0 ? void 0 : err.message) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes("encountered")) {
708
+ this["~standard"].async = true;
709
+ }
710
+ ctx.common = {
711
+ issues: [],
712
+ async: true,
713
+ };
714
+ }
715
+ }
716
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)
717
+ ? {
718
+ value: result.value,
719
+ }
720
+ : {
721
+ issues: ctx.common.issues,
722
+ });
723
+ }
724
+ async parseAsync(data, params) {
725
+ const result = await this.safeParseAsync(data, params);
726
+ if (result.success)
727
+ return result.data;
728
+ throw result.error;
729
+ }
730
+ async safeParseAsync(data, params) {
731
+ const ctx = {
732
+ common: {
733
+ issues: [],
734
+ contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
735
+ async: true,
736
+ },
737
+ path: (params === null || params === void 0 ? void 0 : params.path) || [],
738
+ schemaErrorMap: this._def.errorMap,
739
+ parent: null,
740
+ data,
741
+ parsedType: getParsedType(data),
742
+ };
743
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
744
+ const result = await (isAsync(maybeAsyncResult)
745
+ ? maybeAsyncResult
746
+ : Promise.resolve(maybeAsyncResult));
747
+ return handleResult(ctx, result);
748
+ }
749
+ refine(check, message) {
750
+ const getIssueProperties = (val) => {
751
+ if (typeof message === "string" || typeof message === "undefined") {
752
+ return { message };
753
+ }
754
+ else if (typeof message === "function") {
755
+ return message(val);
756
+ }
757
+ else {
758
+ return message;
759
+ }
760
+ };
761
+ return this._refinement((val, ctx) => {
762
+ const result = check(val);
763
+ const setError = () => ctx.addIssue({
764
+ code: ZodIssueCode.custom,
765
+ ...getIssueProperties(val),
766
+ });
767
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
768
+ return result.then((data) => {
769
+ if (!data) {
770
+ setError();
771
+ return false;
772
+ }
773
+ else {
774
+ return true;
775
+ }
776
+ });
777
+ }
778
+ if (!result) {
779
+ setError();
780
+ return false;
781
+ }
782
+ else {
783
+ return true;
784
+ }
785
+ });
786
+ }
787
+ refinement(check, refinementData) {
788
+ return this._refinement((val, ctx) => {
789
+ if (!check(val)) {
790
+ ctx.addIssue(typeof refinementData === "function"
791
+ ? refinementData(val, ctx)
792
+ : refinementData);
793
+ return false;
794
+ }
795
+ else {
796
+ return true;
797
+ }
798
+ });
799
+ }
800
+ _refinement(refinement) {
801
+ return new ZodEffects({
802
+ schema: this,
803
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
804
+ effect: { type: "refinement", refinement },
805
+ });
806
+ }
807
+ superRefine(refinement) {
808
+ return this._refinement(refinement);
809
+ }
810
+ constructor(def) {
811
+ /** Alias of safeParseAsync */
812
+ this.spa = this.safeParseAsync;
813
+ this._def = def;
814
+ this.parse = this.parse.bind(this);
815
+ this.safeParse = this.safeParse.bind(this);
816
+ this.parseAsync = this.parseAsync.bind(this);
817
+ this.safeParseAsync = this.safeParseAsync.bind(this);
818
+ this.spa = this.spa.bind(this);
819
+ this.refine = this.refine.bind(this);
820
+ this.refinement = this.refinement.bind(this);
821
+ this.superRefine = this.superRefine.bind(this);
822
+ this.optional = this.optional.bind(this);
823
+ this.nullable = this.nullable.bind(this);
824
+ this.nullish = this.nullish.bind(this);
825
+ this.array = this.array.bind(this);
826
+ this.promise = this.promise.bind(this);
827
+ this.or = this.or.bind(this);
828
+ this.and = this.and.bind(this);
829
+ this.transform = this.transform.bind(this);
830
+ this.brand = this.brand.bind(this);
831
+ this.default = this.default.bind(this);
832
+ this.catch = this.catch.bind(this);
833
+ this.describe = this.describe.bind(this);
834
+ this.pipe = this.pipe.bind(this);
835
+ this.readonly = this.readonly.bind(this);
836
+ this.isNullable = this.isNullable.bind(this);
837
+ this.isOptional = this.isOptional.bind(this);
838
+ this["~standard"] = {
839
+ version: 1,
840
+ vendor: "zod",
841
+ validate: (data) => this["~validate"](data),
842
+ };
843
+ }
844
+ optional() {
845
+ return ZodOptional.create(this, this._def);
846
+ }
847
+ nullable() {
848
+ return ZodNullable.create(this, this._def);
849
+ }
850
+ nullish() {
851
+ return this.nullable().optional();
852
+ }
853
+ array() {
854
+ return ZodArray.create(this);
855
+ }
856
+ promise() {
857
+ return ZodPromise.create(this, this._def);
858
+ }
859
+ or(option) {
860
+ return ZodUnion.create([this, option], this._def);
861
+ }
862
+ and(incoming) {
863
+ return ZodIntersection.create(this, incoming, this._def);
864
+ }
865
+ transform(transform) {
866
+ return new ZodEffects({
867
+ ...processCreateParams(this._def),
868
+ schema: this,
869
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
870
+ effect: { type: "transform", transform },
871
+ });
872
+ }
873
+ default(def) {
874
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
875
+ return new ZodDefault({
876
+ ...processCreateParams(this._def),
877
+ innerType: this,
878
+ defaultValue: defaultValueFunc,
879
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
880
+ });
881
+ }
882
+ brand() {
883
+ return new ZodBranded({
884
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
885
+ type: this,
886
+ ...processCreateParams(this._def),
887
+ });
888
+ }
889
+ catch(def) {
890
+ const catchValueFunc = typeof def === "function" ? def : () => def;
891
+ return new ZodCatch({
892
+ ...processCreateParams(this._def),
893
+ innerType: this,
894
+ catchValue: catchValueFunc,
895
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
896
+ });
897
+ }
898
+ describe(description) {
899
+ const This = this.constructor;
900
+ return new This({
901
+ ...this._def,
902
+ description,
903
+ });
904
+ }
905
+ pipe(target) {
906
+ return ZodPipeline.create(this, target);
907
+ }
908
+ readonly() {
909
+ return ZodReadonly.create(this);
910
+ }
911
+ isOptional() {
912
+ return this.safeParse(undefined).success;
913
+ }
914
+ isNullable() {
915
+ return this.safeParse(null).success;
916
+ }
917
+ }
918
+ const cuidRegex = /^c[^\s-]{8,}$/i;
919
+ const cuid2Regex = /^[0-9a-z]+$/;
920
+ const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
921
+ // const uuidRegex =
922
+ // /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
923
+ const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
924
+ const nanoidRegex = /^[a-z0-9_-]{21}$/i;
925
+ const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
926
+ const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
927
+ // from https://stackoverflow.com/a/46181/1550155
928
+ // old version: too slow, didn't support unicode
929
+ // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
930
+ //old email regex
931
+ // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
932
+ // eslint-disable-next-line
933
+ // const emailRegex =
934
+ // /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
935
+ // const emailRegex =
936
+ // /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
937
+ // const emailRegex =
938
+ // /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
939
+ const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
940
+ // const emailRegex =
941
+ // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
942
+ // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
943
+ const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
944
+ let emojiRegex;
945
+ // faster, simpler, safer
946
+ const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
947
+ const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
948
+ // const ipv6Regex =
949
+ // /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
950
+ const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
951
+ const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
952
+ // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
953
+ const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
954
+ // https://base64.guru/standards/base64url
955
+ const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
956
+ // simple
957
+ // const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`;
958
+ // no leap year validation
959
+ // const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`;
960
+ // with leap year validation
961
+ const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
962
+ const dateRegex = new RegExp(`^${dateRegexSource}$`);
963
+ function timeRegexSource(args) {
964
+ // let regex = `\\d{2}:\\d{2}:\\d{2}`;
965
+ let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
966
+ if (args.precision) {
967
+ regex = `${regex}\\.\\d{${args.precision}}`;
968
+ }
969
+ else if (args.precision == null) {
970
+ regex = `${regex}(\\.\\d+)?`;
971
+ }
972
+ return regex;
973
+ }
974
+ function timeRegex(args) {
975
+ return new RegExp(`^${timeRegexSource(args)}$`);
976
+ }
977
+ // Adapted from https://stackoverflow.com/a/3143231
978
+ function datetimeRegex(args) {
979
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
980
+ const opts = [];
981
+ opts.push(args.local ? `Z?` : `Z`);
982
+ if (args.offset)
983
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
984
+ regex = `${regex}(${opts.join("|")})`;
985
+ return new RegExp(`^${regex}$`);
986
+ }
987
+ function isValidIP(ip, version) {
988
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
989
+ return true;
990
+ }
991
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
992
+ return true;
993
+ }
994
+ return false;
995
+ }
996
+ function isValidJWT(jwt, alg) {
997
+ if (!jwtRegex.test(jwt))
998
+ return false;
999
+ try {
1000
+ const [header] = jwt.split(".");
1001
+ // Convert base64url to base64
1002
+ const base64 = header
1003
+ .replace(/-/g, "+")
1004
+ .replace(/_/g, "/")
1005
+ .padEnd(header.length + ((4 - (header.length % 4)) % 4), "=");
1006
+ const decoded = JSON.parse(atob(base64));
1007
+ if (typeof decoded !== "object" || decoded === null)
1008
+ return false;
1009
+ if (!decoded.typ || !decoded.alg)
1010
+ return false;
1011
+ if (alg && decoded.alg !== alg)
1012
+ return false;
1013
+ return true;
1014
+ }
1015
+ catch (_a) {
1016
+ return false;
1017
+ }
1018
+ }
1019
+ function isValidCidr(ip, version) {
1020
+ if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
1021
+ return true;
1022
+ }
1023
+ if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
1024
+ return true;
1025
+ }
1026
+ return false;
1027
+ }
1028
+ class ZodString extends ZodType {
1029
+ _parse(input) {
1030
+ if (this._def.coerce) {
1031
+ input.data = String(input.data);
1032
+ }
1033
+ const parsedType = this._getType(input);
1034
+ if (parsedType !== ZodParsedType.string) {
1035
+ const ctx = this._getOrReturnCtx(input);
1036
+ addIssueToContext(ctx, {
1037
+ code: ZodIssueCode.invalid_type,
1038
+ expected: ZodParsedType.string,
1039
+ received: ctx.parsedType,
1040
+ });
1041
+ return INVALID;
1042
+ }
1043
+ const status = new ParseStatus();
1044
+ let ctx = undefined;
1045
+ for (const check of this._def.checks) {
1046
+ if (check.kind === "min") {
1047
+ if (input.data.length < check.value) {
1048
+ ctx = this._getOrReturnCtx(input, ctx);
1049
+ addIssueToContext(ctx, {
1050
+ code: ZodIssueCode.too_small,
1051
+ minimum: check.value,
1052
+ type: "string",
1053
+ inclusive: true,
1054
+ exact: false,
1055
+ message: check.message,
1056
+ });
1057
+ status.dirty();
1058
+ }
1059
+ }
1060
+ else if (check.kind === "max") {
1061
+ if (input.data.length > check.value) {
1062
+ ctx = this._getOrReturnCtx(input, ctx);
1063
+ addIssueToContext(ctx, {
1064
+ code: ZodIssueCode.too_big,
1065
+ maximum: check.value,
1066
+ type: "string",
1067
+ inclusive: true,
1068
+ exact: false,
1069
+ message: check.message,
1070
+ });
1071
+ status.dirty();
1072
+ }
1073
+ }
1074
+ else if (check.kind === "length") {
1075
+ const tooBig = input.data.length > check.value;
1076
+ const tooSmall = input.data.length < check.value;
1077
+ if (tooBig || tooSmall) {
1078
+ ctx = this._getOrReturnCtx(input, ctx);
1079
+ if (tooBig) {
1080
+ addIssueToContext(ctx, {
1081
+ code: ZodIssueCode.too_big,
1082
+ maximum: check.value,
1083
+ type: "string",
1084
+ inclusive: true,
1085
+ exact: true,
1086
+ message: check.message,
1087
+ });
1088
+ }
1089
+ else if (tooSmall) {
1090
+ addIssueToContext(ctx, {
1091
+ code: ZodIssueCode.too_small,
1092
+ minimum: check.value,
1093
+ type: "string",
1094
+ inclusive: true,
1095
+ exact: true,
1096
+ message: check.message,
1097
+ });
1098
+ }
1099
+ status.dirty();
1100
+ }
1101
+ }
1102
+ else if (check.kind === "email") {
1103
+ if (!emailRegex.test(input.data)) {
1104
+ ctx = this._getOrReturnCtx(input, ctx);
1105
+ addIssueToContext(ctx, {
1106
+ validation: "email",
1107
+ code: ZodIssueCode.invalid_string,
1108
+ message: check.message,
1109
+ });
1110
+ status.dirty();
1111
+ }
1112
+ }
1113
+ else if (check.kind === "emoji") {
1114
+ if (!emojiRegex) {
1115
+ emojiRegex = new RegExp(_emojiRegex, "u");
1116
+ }
1117
+ if (!emojiRegex.test(input.data)) {
1118
+ ctx = this._getOrReturnCtx(input, ctx);
1119
+ addIssueToContext(ctx, {
1120
+ validation: "emoji",
1121
+ code: ZodIssueCode.invalid_string,
1122
+ message: check.message,
1123
+ });
1124
+ status.dirty();
1125
+ }
1126
+ }
1127
+ else if (check.kind === "uuid") {
1128
+ if (!uuidRegex.test(input.data)) {
1129
+ ctx = this._getOrReturnCtx(input, ctx);
1130
+ addIssueToContext(ctx, {
1131
+ validation: "uuid",
1132
+ code: ZodIssueCode.invalid_string,
1133
+ message: check.message,
1134
+ });
1135
+ status.dirty();
1136
+ }
1137
+ }
1138
+ else if (check.kind === "nanoid") {
1139
+ if (!nanoidRegex.test(input.data)) {
1140
+ ctx = this._getOrReturnCtx(input, ctx);
1141
+ addIssueToContext(ctx, {
1142
+ validation: "nanoid",
1143
+ code: ZodIssueCode.invalid_string,
1144
+ message: check.message,
1145
+ });
1146
+ status.dirty();
1147
+ }
1148
+ }
1149
+ else if (check.kind === "cuid") {
1150
+ if (!cuidRegex.test(input.data)) {
1151
+ ctx = this._getOrReturnCtx(input, ctx);
1152
+ addIssueToContext(ctx, {
1153
+ validation: "cuid",
1154
+ code: ZodIssueCode.invalid_string,
1155
+ message: check.message,
1156
+ });
1157
+ status.dirty();
1158
+ }
1159
+ }
1160
+ else if (check.kind === "cuid2") {
1161
+ if (!cuid2Regex.test(input.data)) {
1162
+ ctx = this._getOrReturnCtx(input, ctx);
1163
+ addIssueToContext(ctx, {
1164
+ validation: "cuid2",
1165
+ code: ZodIssueCode.invalid_string,
1166
+ message: check.message,
1167
+ });
1168
+ status.dirty();
1169
+ }
1170
+ }
1171
+ else if (check.kind === "ulid") {
1172
+ if (!ulidRegex.test(input.data)) {
1173
+ ctx = this._getOrReturnCtx(input, ctx);
1174
+ addIssueToContext(ctx, {
1175
+ validation: "ulid",
1176
+ code: ZodIssueCode.invalid_string,
1177
+ message: check.message,
1178
+ });
1179
+ status.dirty();
1180
+ }
1181
+ }
1182
+ else if (check.kind === "url") {
1183
+ try {
1184
+ new URL(input.data);
1185
+ }
1186
+ catch (_a) {
1187
+ ctx = this._getOrReturnCtx(input, ctx);
1188
+ addIssueToContext(ctx, {
1189
+ validation: "url",
1190
+ code: ZodIssueCode.invalid_string,
1191
+ message: check.message,
1192
+ });
1193
+ status.dirty();
1194
+ }
1195
+ }
1196
+ else if (check.kind === "regex") {
1197
+ check.regex.lastIndex = 0;
1198
+ const testResult = check.regex.test(input.data);
1199
+ if (!testResult) {
1200
+ ctx = this._getOrReturnCtx(input, ctx);
1201
+ addIssueToContext(ctx, {
1202
+ validation: "regex",
1203
+ code: ZodIssueCode.invalid_string,
1204
+ message: check.message,
1205
+ });
1206
+ status.dirty();
1207
+ }
1208
+ }
1209
+ else if (check.kind === "trim") {
1210
+ input.data = input.data.trim();
1211
+ }
1212
+ else if (check.kind === "includes") {
1213
+ if (!input.data.includes(check.value, check.position)) {
1214
+ ctx = this._getOrReturnCtx(input, ctx);
1215
+ addIssueToContext(ctx, {
1216
+ code: ZodIssueCode.invalid_string,
1217
+ validation: { includes: check.value, position: check.position },
1218
+ message: check.message,
1219
+ });
1220
+ status.dirty();
1221
+ }
1222
+ }
1223
+ else if (check.kind === "toLowerCase") {
1224
+ input.data = input.data.toLowerCase();
1225
+ }
1226
+ else if (check.kind === "toUpperCase") {
1227
+ input.data = input.data.toUpperCase();
1228
+ }
1229
+ else if (check.kind === "startsWith") {
1230
+ if (!input.data.startsWith(check.value)) {
1231
+ ctx = this._getOrReturnCtx(input, ctx);
1232
+ addIssueToContext(ctx, {
1233
+ code: ZodIssueCode.invalid_string,
1234
+ validation: { startsWith: check.value },
1235
+ message: check.message,
1236
+ });
1237
+ status.dirty();
1238
+ }
1239
+ }
1240
+ else if (check.kind === "endsWith") {
1241
+ if (!input.data.endsWith(check.value)) {
1242
+ ctx = this._getOrReturnCtx(input, ctx);
1243
+ addIssueToContext(ctx, {
1244
+ code: ZodIssueCode.invalid_string,
1245
+ validation: { endsWith: check.value },
1246
+ message: check.message,
1247
+ });
1248
+ status.dirty();
1249
+ }
1250
+ }
1251
+ else if (check.kind === "datetime") {
1252
+ const regex = datetimeRegex(check);
1253
+ if (!regex.test(input.data)) {
1254
+ ctx = this._getOrReturnCtx(input, ctx);
1255
+ addIssueToContext(ctx, {
1256
+ code: ZodIssueCode.invalid_string,
1257
+ validation: "datetime",
1258
+ message: check.message,
1259
+ });
1260
+ status.dirty();
1261
+ }
1262
+ }
1263
+ else if (check.kind === "date") {
1264
+ const regex = dateRegex;
1265
+ if (!regex.test(input.data)) {
1266
+ ctx = this._getOrReturnCtx(input, ctx);
1267
+ addIssueToContext(ctx, {
1268
+ code: ZodIssueCode.invalid_string,
1269
+ validation: "date",
1270
+ message: check.message,
1271
+ });
1272
+ status.dirty();
1273
+ }
1274
+ }
1275
+ else if (check.kind === "time") {
1276
+ const regex = timeRegex(check);
1277
+ if (!regex.test(input.data)) {
1278
+ ctx = this._getOrReturnCtx(input, ctx);
1279
+ addIssueToContext(ctx, {
1280
+ code: ZodIssueCode.invalid_string,
1281
+ validation: "time",
1282
+ message: check.message,
1283
+ });
1284
+ status.dirty();
1285
+ }
1286
+ }
1287
+ else if (check.kind === "duration") {
1288
+ if (!durationRegex.test(input.data)) {
1289
+ ctx = this._getOrReturnCtx(input, ctx);
1290
+ addIssueToContext(ctx, {
1291
+ validation: "duration",
1292
+ code: ZodIssueCode.invalid_string,
1293
+ message: check.message,
1294
+ });
1295
+ status.dirty();
1296
+ }
1297
+ }
1298
+ else if (check.kind === "ip") {
1299
+ if (!isValidIP(input.data, check.version)) {
1300
+ ctx = this._getOrReturnCtx(input, ctx);
1301
+ addIssueToContext(ctx, {
1302
+ validation: "ip",
1303
+ code: ZodIssueCode.invalid_string,
1304
+ message: check.message,
1305
+ });
1306
+ status.dirty();
1307
+ }
1308
+ }
1309
+ else if (check.kind === "jwt") {
1310
+ if (!isValidJWT(input.data, check.alg)) {
1311
+ ctx = this._getOrReturnCtx(input, ctx);
1312
+ addIssueToContext(ctx, {
1313
+ validation: "jwt",
1314
+ code: ZodIssueCode.invalid_string,
1315
+ message: check.message,
1316
+ });
1317
+ status.dirty();
1318
+ }
1319
+ }
1320
+ else if (check.kind === "cidr") {
1321
+ if (!isValidCidr(input.data, check.version)) {
1322
+ ctx = this._getOrReturnCtx(input, ctx);
1323
+ addIssueToContext(ctx, {
1324
+ validation: "cidr",
1325
+ code: ZodIssueCode.invalid_string,
1326
+ message: check.message,
1327
+ });
1328
+ status.dirty();
1329
+ }
1330
+ }
1331
+ else if (check.kind === "base64") {
1332
+ if (!base64Regex.test(input.data)) {
1333
+ ctx = this._getOrReturnCtx(input, ctx);
1334
+ addIssueToContext(ctx, {
1335
+ validation: "base64",
1336
+ code: ZodIssueCode.invalid_string,
1337
+ message: check.message,
1338
+ });
1339
+ status.dirty();
1340
+ }
1341
+ }
1342
+ else if (check.kind === "base64url") {
1343
+ if (!base64urlRegex.test(input.data)) {
1344
+ ctx = this._getOrReturnCtx(input, ctx);
1345
+ addIssueToContext(ctx, {
1346
+ validation: "base64url",
1347
+ code: ZodIssueCode.invalid_string,
1348
+ message: check.message,
1349
+ });
1350
+ status.dirty();
1351
+ }
1352
+ }
1353
+ else {
1354
+ util.assertNever(check);
1355
+ }
1356
+ }
1357
+ return { status: status.value, value: input.data };
1358
+ }
1359
+ _regex(regex, validation, message) {
1360
+ return this.refinement((data) => regex.test(data), {
1361
+ validation,
1362
+ code: ZodIssueCode.invalid_string,
1363
+ ...errorUtil.errToObj(message),
1364
+ });
1365
+ }
1366
+ _addCheck(check) {
1367
+ return new ZodString({
1368
+ ...this._def,
1369
+ checks: [...this._def.checks, check],
1370
+ });
1371
+ }
1372
+ email(message) {
1373
+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
1374
+ }
1375
+ url(message) {
1376
+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
1377
+ }
1378
+ emoji(message) {
1379
+ return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
1380
+ }
1381
+ uuid(message) {
1382
+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1383
+ }
1384
+ nanoid(message) {
1385
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1386
+ }
1387
+ cuid(message) {
1388
+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1389
+ }
1390
+ cuid2(message) {
1391
+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
1392
+ }
1393
+ ulid(message) {
1394
+ return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1395
+ }
1396
+ base64(message) {
1397
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1398
+ }
1399
+ base64url(message) {
1400
+ // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
1401
+ return this._addCheck({
1402
+ kind: "base64url",
1403
+ ...errorUtil.errToObj(message),
1404
+ });
1405
+ }
1406
+ jwt(options) {
1407
+ return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
1408
+ }
1409
+ ip(options) {
1410
+ return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1411
+ }
1412
+ cidr(options) {
1413
+ return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
1414
+ }
1415
+ datetime(options) {
1416
+ var _a, _b;
1417
+ if (typeof options === "string") {
1418
+ return this._addCheck({
1419
+ kind: "datetime",
1420
+ precision: null,
1421
+ offset: false,
1422
+ local: false,
1423
+ message: options,
1424
+ });
1425
+ }
1426
+ return this._addCheck({
1427
+ kind: "datetime",
1428
+ precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
1429
+ offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
1430
+ local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,
1431
+ ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
1432
+ });
1433
+ }
1434
+ date(message) {
1435
+ return this._addCheck({ kind: "date", message });
1436
+ }
1437
+ time(options) {
1438
+ if (typeof options === "string") {
1439
+ return this._addCheck({
1440
+ kind: "time",
1441
+ precision: null,
1442
+ message: options,
1443
+ });
1444
+ }
1445
+ return this._addCheck({
1446
+ kind: "time",
1447
+ precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
1448
+ ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
1449
+ });
1450
+ }
1451
+ duration(message) {
1452
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
1453
+ }
1454
+ regex(regex, message) {
1455
+ return this._addCheck({
1456
+ kind: "regex",
1457
+ regex: regex,
1458
+ ...errorUtil.errToObj(message),
1459
+ });
1460
+ }
1461
+ includes(value, options) {
1462
+ return this._addCheck({
1463
+ kind: "includes",
1464
+ value: value,
1465
+ position: options === null || options === void 0 ? void 0 : options.position,
1466
+ ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
1467
+ });
1468
+ }
1469
+ startsWith(value, message) {
1470
+ return this._addCheck({
1471
+ kind: "startsWith",
1472
+ value: value,
1473
+ ...errorUtil.errToObj(message),
1474
+ });
1475
+ }
1476
+ endsWith(value, message) {
1477
+ return this._addCheck({
1478
+ kind: "endsWith",
1479
+ value: value,
1480
+ ...errorUtil.errToObj(message),
1481
+ });
1482
+ }
1483
+ min(minLength, message) {
1484
+ return this._addCheck({
1485
+ kind: "min",
1486
+ value: minLength,
1487
+ ...errorUtil.errToObj(message),
1488
+ });
1489
+ }
1490
+ max(maxLength, message) {
1491
+ return this._addCheck({
1492
+ kind: "max",
1493
+ value: maxLength,
1494
+ ...errorUtil.errToObj(message),
1495
+ });
1496
+ }
1497
+ length(len, message) {
1498
+ return this._addCheck({
1499
+ kind: "length",
1500
+ value: len,
1501
+ ...errorUtil.errToObj(message),
1502
+ });
1503
+ }
1504
+ /**
1505
+ * Equivalent to `.min(1)`
1506
+ */
1507
+ nonempty(message) {
1508
+ return this.min(1, errorUtil.errToObj(message));
1509
+ }
1510
+ trim() {
1511
+ return new ZodString({
1512
+ ...this._def,
1513
+ checks: [...this._def.checks, { kind: "trim" }],
1514
+ });
1515
+ }
1516
+ toLowerCase() {
1517
+ return new ZodString({
1518
+ ...this._def,
1519
+ checks: [...this._def.checks, { kind: "toLowerCase" }],
1520
+ });
1521
+ }
1522
+ toUpperCase() {
1523
+ return new ZodString({
1524
+ ...this._def,
1525
+ checks: [...this._def.checks, { kind: "toUpperCase" }],
1526
+ });
1527
+ }
1528
+ get isDatetime() {
1529
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
1530
+ }
1531
+ get isDate() {
1532
+ return !!this._def.checks.find((ch) => ch.kind === "date");
1533
+ }
1534
+ get isTime() {
1535
+ return !!this._def.checks.find((ch) => ch.kind === "time");
1536
+ }
1537
+ get isDuration() {
1538
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
1539
+ }
1540
+ get isEmail() {
1541
+ return !!this._def.checks.find((ch) => ch.kind === "email");
1542
+ }
1543
+ get isURL() {
1544
+ return !!this._def.checks.find((ch) => ch.kind === "url");
1545
+ }
1546
+ get isEmoji() {
1547
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
1548
+ }
1549
+ get isUUID() {
1550
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
1551
+ }
1552
+ get isNANOID() {
1553
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1554
+ }
1555
+ get isCUID() {
1556
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
1557
+ }
1558
+ get isCUID2() {
1559
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1560
+ }
1561
+ get isULID() {
1562
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
1563
+ }
1564
+ get isIP() {
1565
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
1566
+ }
1567
+ get isCIDR() {
1568
+ return !!this._def.checks.find((ch) => ch.kind === "cidr");
1569
+ }
1570
+ get isBase64() {
1571
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
1572
+ }
1573
+ get isBase64url() {
1574
+ // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
1575
+ return !!this._def.checks.find((ch) => ch.kind === "base64url");
1576
+ }
1577
+ get minLength() {
1578
+ let min = null;
1579
+ for (const ch of this._def.checks) {
1580
+ if (ch.kind === "min") {
1581
+ if (min === null || ch.value > min)
1582
+ min = ch.value;
1583
+ }
1584
+ }
1585
+ return min;
1586
+ }
1587
+ get maxLength() {
1588
+ let max = null;
1589
+ for (const ch of this._def.checks) {
1590
+ if (ch.kind === "max") {
1591
+ if (max === null || ch.value < max)
1592
+ max = ch.value;
1593
+ }
1594
+ }
1595
+ return max;
1596
+ }
1597
+ }
1598
+ ZodString.create = (params) => {
1599
+ var _a;
1600
+ return new ZodString({
1601
+ checks: [],
1602
+ typeName: ZodFirstPartyTypeKind.ZodString,
1603
+ coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
1604
+ ...processCreateParams(params),
1605
+ });
1606
+ };
1607
+ // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
1608
+ function floatSafeRemainder(val, step) {
1609
+ const valDecCount = (val.toString().split(".")[1] || "").length;
1610
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
1611
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1612
+ const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
1613
+ const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
1614
+ return (valInt % stepInt) / Math.pow(10, decCount);
1615
+ }
1616
+ class ZodNumber extends ZodType {
1617
+ constructor() {
1618
+ super(...arguments);
1619
+ this.min = this.gte;
1620
+ this.max = this.lte;
1621
+ this.step = this.multipleOf;
1622
+ }
1623
+ _parse(input) {
1624
+ if (this._def.coerce) {
1625
+ input.data = Number(input.data);
1626
+ }
1627
+ const parsedType = this._getType(input);
1628
+ if (parsedType !== ZodParsedType.number) {
1629
+ const ctx = this._getOrReturnCtx(input);
1630
+ addIssueToContext(ctx, {
1631
+ code: ZodIssueCode.invalid_type,
1632
+ expected: ZodParsedType.number,
1633
+ received: ctx.parsedType,
1634
+ });
1635
+ return INVALID;
1636
+ }
1637
+ let ctx = undefined;
1638
+ const status = new ParseStatus();
1639
+ for (const check of this._def.checks) {
1640
+ if (check.kind === "int") {
1641
+ if (!util.isInteger(input.data)) {
1642
+ ctx = this._getOrReturnCtx(input, ctx);
1643
+ addIssueToContext(ctx, {
1644
+ code: ZodIssueCode.invalid_type,
1645
+ expected: "integer",
1646
+ received: "float",
1647
+ message: check.message,
1648
+ });
1649
+ status.dirty();
1650
+ }
1651
+ }
1652
+ else if (check.kind === "min") {
1653
+ const tooSmall = check.inclusive
1654
+ ? input.data < check.value
1655
+ : input.data <= check.value;
1656
+ if (tooSmall) {
1657
+ ctx = this._getOrReturnCtx(input, ctx);
1658
+ addIssueToContext(ctx, {
1659
+ code: ZodIssueCode.too_small,
1660
+ minimum: check.value,
1661
+ type: "number",
1662
+ inclusive: check.inclusive,
1663
+ exact: false,
1664
+ message: check.message,
1665
+ });
1666
+ status.dirty();
1667
+ }
1668
+ }
1669
+ else if (check.kind === "max") {
1670
+ const tooBig = check.inclusive
1671
+ ? input.data > check.value
1672
+ : input.data >= check.value;
1673
+ if (tooBig) {
1674
+ ctx = this._getOrReturnCtx(input, ctx);
1675
+ addIssueToContext(ctx, {
1676
+ code: ZodIssueCode.too_big,
1677
+ maximum: check.value,
1678
+ type: "number",
1679
+ inclusive: check.inclusive,
1680
+ exact: false,
1681
+ message: check.message,
1682
+ });
1683
+ status.dirty();
1684
+ }
1685
+ }
1686
+ else if (check.kind === "multipleOf") {
1687
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
1688
+ ctx = this._getOrReturnCtx(input, ctx);
1689
+ addIssueToContext(ctx, {
1690
+ code: ZodIssueCode.not_multiple_of,
1691
+ multipleOf: check.value,
1692
+ message: check.message,
1693
+ });
1694
+ status.dirty();
1695
+ }
1696
+ }
1697
+ else if (check.kind === "finite") {
1698
+ if (!Number.isFinite(input.data)) {
1699
+ ctx = this._getOrReturnCtx(input, ctx);
1700
+ addIssueToContext(ctx, {
1701
+ code: ZodIssueCode.not_finite,
1702
+ message: check.message,
1703
+ });
1704
+ status.dirty();
1705
+ }
1706
+ }
1707
+ else {
1708
+ util.assertNever(check);
1709
+ }
1710
+ }
1711
+ return { status: status.value, value: input.data };
1712
+ }
1713
+ gte(value, message) {
1714
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1715
+ }
1716
+ gt(value, message) {
1717
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1718
+ }
1719
+ lte(value, message) {
1720
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1721
+ }
1722
+ lt(value, message) {
1723
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1724
+ }
1725
+ setLimit(kind, value, inclusive, message) {
1726
+ return new ZodNumber({
1727
+ ...this._def,
1728
+ checks: [
1729
+ ...this._def.checks,
1730
+ {
1731
+ kind,
1732
+ value,
1733
+ inclusive,
1734
+ message: errorUtil.toString(message),
1735
+ },
1736
+ ],
1737
+ });
1738
+ }
1739
+ _addCheck(check) {
1740
+ return new ZodNumber({
1741
+ ...this._def,
1742
+ checks: [...this._def.checks, check],
1743
+ });
1744
+ }
1745
+ int(message) {
1746
+ return this._addCheck({
1747
+ kind: "int",
1748
+ message: errorUtil.toString(message),
1749
+ });
1750
+ }
1751
+ positive(message) {
1752
+ return this._addCheck({
1753
+ kind: "min",
1754
+ value: 0,
1755
+ inclusive: false,
1756
+ message: errorUtil.toString(message),
1757
+ });
1758
+ }
1759
+ negative(message) {
1760
+ return this._addCheck({
1761
+ kind: "max",
1762
+ value: 0,
1763
+ inclusive: false,
1764
+ message: errorUtil.toString(message),
1765
+ });
1766
+ }
1767
+ nonpositive(message) {
1768
+ return this._addCheck({
1769
+ kind: "max",
1770
+ value: 0,
1771
+ inclusive: true,
1772
+ message: errorUtil.toString(message),
1773
+ });
1774
+ }
1775
+ nonnegative(message) {
1776
+ return this._addCheck({
1777
+ kind: "min",
1778
+ value: 0,
1779
+ inclusive: true,
1780
+ message: errorUtil.toString(message),
1781
+ });
1782
+ }
1783
+ multipleOf(value, message) {
1784
+ return this._addCheck({
1785
+ kind: "multipleOf",
1786
+ value: value,
1787
+ message: errorUtil.toString(message),
1788
+ });
1789
+ }
1790
+ finite(message) {
1791
+ return this._addCheck({
1792
+ kind: "finite",
1793
+ message: errorUtil.toString(message),
1794
+ });
1795
+ }
1796
+ safe(message) {
1797
+ return this._addCheck({
1798
+ kind: "min",
1799
+ inclusive: true,
1800
+ value: Number.MIN_SAFE_INTEGER,
1801
+ message: errorUtil.toString(message),
1802
+ })._addCheck({
1803
+ kind: "max",
1804
+ inclusive: true,
1805
+ value: Number.MAX_SAFE_INTEGER,
1806
+ message: errorUtil.toString(message),
1807
+ });
1808
+ }
1809
+ get minValue() {
1810
+ let min = null;
1811
+ for (const ch of this._def.checks) {
1812
+ if (ch.kind === "min") {
1813
+ if (min === null || ch.value > min)
1814
+ min = ch.value;
1815
+ }
1816
+ }
1817
+ return min;
1818
+ }
1819
+ get maxValue() {
1820
+ let max = null;
1821
+ for (const ch of this._def.checks) {
1822
+ if (ch.kind === "max") {
1823
+ if (max === null || ch.value < max)
1824
+ max = ch.value;
1825
+ }
1826
+ }
1827
+ return max;
1828
+ }
1829
+ get isInt() {
1830
+ return !!this._def.checks.find((ch) => ch.kind === "int" ||
1831
+ (ch.kind === "multipleOf" && util.isInteger(ch.value)));
1832
+ }
1833
+ get isFinite() {
1834
+ let max = null, min = null;
1835
+ for (const ch of this._def.checks) {
1836
+ if (ch.kind === "finite" ||
1837
+ ch.kind === "int" ||
1838
+ ch.kind === "multipleOf") {
1839
+ return true;
1840
+ }
1841
+ else if (ch.kind === "min") {
1842
+ if (min === null || ch.value > min)
1843
+ min = ch.value;
1844
+ }
1845
+ else if (ch.kind === "max") {
1846
+ if (max === null || ch.value < max)
1847
+ max = ch.value;
1848
+ }
1849
+ }
1850
+ return Number.isFinite(min) && Number.isFinite(max);
1851
+ }
1852
+ }
1853
+ ZodNumber.create = (params) => {
1854
+ return new ZodNumber({
1855
+ checks: [],
1856
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
1857
+ coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
1858
+ ...processCreateParams(params),
1859
+ });
1860
+ };
1861
+ class ZodBigInt extends ZodType {
1862
+ constructor() {
1863
+ super(...arguments);
1864
+ this.min = this.gte;
1865
+ this.max = this.lte;
1866
+ }
1867
+ _parse(input) {
1868
+ if (this._def.coerce) {
1869
+ try {
1870
+ input.data = BigInt(input.data);
1871
+ }
1872
+ catch (_a) {
1873
+ return this._getInvalidInput(input);
1874
+ }
1875
+ }
1876
+ const parsedType = this._getType(input);
1877
+ if (parsedType !== ZodParsedType.bigint) {
1878
+ return this._getInvalidInput(input);
1879
+ }
1880
+ let ctx = undefined;
1881
+ const status = new ParseStatus();
1882
+ for (const check of this._def.checks) {
1883
+ if (check.kind === "min") {
1884
+ const tooSmall = check.inclusive
1885
+ ? input.data < check.value
1886
+ : input.data <= check.value;
1887
+ if (tooSmall) {
1888
+ ctx = this._getOrReturnCtx(input, ctx);
1889
+ addIssueToContext(ctx, {
1890
+ code: ZodIssueCode.too_small,
1891
+ type: "bigint",
1892
+ minimum: check.value,
1893
+ inclusive: check.inclusive,
1894
+ message: check.message,
1895
+ });
1896
+ status.dirty();
1897
+ }
1898
+ }
1899
+ else if (check.kind === "max") {
1900
+ const tooBig = check.inclusive
1901
+ ? input.data > check.value
1902
+ : input.data >= check.value;
1903
+ if (tooBig) {
1904
+ ctx = this._getOrReturnCtx(input, ctx);
1905
+ addIssueToContext(ctx, {
1906
+ code: ZodIssueCode.too_big,
1907
+ type: "bigint",
1908
+ maximum: check.value,
1909
+ inclusive: check.inclusive,
1910
+ message: check.message,
1911
+ });
1912
+ status.dirty();
1913
+ }
1914
+ }
1915
+ else if (check.kind === "multipleOf") {
1916
+ if (input.data % check.value !== BigInt(0)) {
1917
+ ctx = this._getOrReturnCtx(input, ctx);
1918
+ addIssueToContext(ctx, {
1919
+ code: ZodIssueCode.not_multiple_of,
1920
+ multipleOf: check.value,
1921
+ message: check.message,
1922
+ });
1923
+ status.dirty();
1924
+ }
1925
+ }
1926
+ else {
1927
+ util.assertNever(check);
1928
+ }
1929
+ }
1930
+ return { status: status.value, value: input.data };
1931
+ }
1932
+ _getInvalidInput(input) {
1933
+ const ctx = this._getOrReturnCtx(input);
1934
+ addIssueToContext(ctx, {
1935
+ code: ZodIssueCode.invalid_type,
1936
+ expected: ZodParsedType.bigint,
1937
+ received: ctx.parsedType,
1938
+ });
1939
+ return INVALID;
1940
+ }
1941
+ gte(value, message) {
1942
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1943
+ }
1944
+ gt(value, message) {
1945
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1946
+ }
1947
+ lte(value, message) {
1948
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1949
+ }
1950
+ lt(value, message) {
1951
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1952
+ }
1953
+ setLimit(kind, value, inclusive, message) {
1954
+ return new ZodBigInt({
1955
+ ...this._def,
1956
+ checks: [
1957
+ ...this._def.checks,
1958
+ {
1959
+ kind,
1960
+ value,
1961
+ inclusive,
1962
+ message: errorUtil.toString(message),
1963
+ },
1964
+ ],
1965
+ });
1966
+ }
1967
+ _addCheck(check) {
1968
+ return new ZodBigInt({
1969
+ ...this._def,
1970
+ checks: [...this._def.checks, check],
1971
+ });
1972
+ }
1973
+ positive(message) {
1974
+ return this._addCheck({
1975
+ kind: "min",
1976
+ value: BigInt(0),
1977
+ inclusive: false,
1978
+ message: errorUtil.toString(message),
1979
+ });
1980
+ }
1981
+ negative(message) {
1982
+ return this._addCheck({
1983
+ kind: "max",
1984
+ value: BigInt(0),
1985
+ inclusive: false,
1986
+ message: errorUtil.toString(message),
1987
+ });
1988
+ }
1989
+ nonpositive(message) {
1990
+ return this._addCheck({
1991
+ kind: "max",
1992
+ value: BigInt(0),
1993
+ inclusive: true,
1994
+ message: errorUtil.toString(message),
1995
+ });
1996
+ }
1997
+ nonnegative(message) {
1998
+ return this._addCheck({
1999
+ kind: "min",
2000
+ value: BigInt(0),
2001
+ inclusive: true,
2002
+ message: errorUtil.toString(message),
2003
+ });
2004
+ }
2005
+ multipleOf(value, message) {
2006
+ return this._addCheck({
2007
+ kind: "multipleOf",
2008
+ value,
2009
+ message: errorUtil.toString(message),
2010
+ });
2011
+ }
2012
+ get minValue() {
2013
+ let min = null;
2014
+ for (const ch of this._def.checks) {
2015
+ if (ch.kind === "min") {
2016
+ if (min === null || ch.value > min)
2017
+ min = ch.value;
2018
+ }
2019
+ }
2020
+ return min;
2021
+ }
2022
+ get maxValue() {
2023
+ let max = null;
2024
+ for (const ch of this._def.checks) {
2025
+ if (ch.kind === "max") {
2026
+ if (max === null || ch.value < max)
2027
+ max = ch.value;
2028
+ }
2029
+ }
2030
+ return max;
2031
+ }
2032
+ }
2033
+ ZodBigInt.create = (params) => {
2034
+ var _a;
2035
+ return new ZodBigInt({
2036
+ checks: [],
2037
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
2038
+ coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
2039
+ ...processCreateParams(params),
2040
+ });
2041
+ };
2042
+ class ZodBoolean extends ZodType {
2043
+ _parse(input) {
2044
+ if (this._def.coerce) {
2045
+ input.data = Boolean(input.data);
2046
+ }
2047
+ const parsedType = this._getType(input);
2048
+ if (parsedType !== ZodParsedType.boolean) {
2049
+ const ctx = this._getOrReturnCtx(input);
2050
+ addIssueToContext(ctx, {
2051
+ code: ZodIssueCode.invalid_type,
2052
+ expected: ZodParsedType.boolean,
2053
+ received: ctx.parsedType,
2054
+ });
2055
+ return INVALID;
2056
+ }
2057
+ return OK(input.data);
2058
+ }
2059
+ }
2060
+ ZodBoolean.create = (params) => {
2061
+ return new ZodBoolean({
2062
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
2063
+ coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
2064
+ ...processCreateParams(params),
2065
+ });
2066
+ };
2067
+ class ZodDate extends ZodType {
2068
+ _parse(input) {
2069
+ if (this._def.coerce) {
2070
+ input.data = new Date(input.data);
2071
+ }
2072
+ const parsedType = this._getType(input);
2073
+ if (parsedType !== ZodParsedType.date) {
2074
+ const ctx = this._getOrReturnCtx(input);
2075
+ addIssueToContext(ctx, {
2076
+ code: ZodIssueCode.invalid_type,
2077
+ expected: ZodParsedType.date,
2078
+ received: ctx.parsedType,
2079
+ });
2080
+ return INVALID;
2081
+ }
2082
+ if (isNaN(input.data.getTime())) {
2083
+ const ctx = this._getOrReturnCtx(input);
2084
+ addIssueToContext(ctx, {
2085
+ code: ZodIssueCode.invalid_date,
2086
+ });
2087
+ return INVALID;
2088
+ }
2089
+ const status = new ParseStatus();
2090
+ let ctx = undefined;
2091
+ for (const check of this._def.checks) {
2092
+ if (check.kind === "min") {
2093
+ if (input.data.getTime() < check.value) {
2094
+ ctx = this._getOrReturnCtx(input, ctx);
2095
+ addIssueToContext(ctx, {
2096
+ code: ZodIssueCode.too_small,
2097
+ message: check.message,
2098
+ inclusive: true,
2099
+ exact: false,
2100
+ minimum: check.value,
2101
+ type: "date",
2102
+ });
2103
+ status.dirty();
2104
+ }
2105
+ }
2106
+ else if (check.kind === "max") {
2107
+ if (input.data.getTime() > check.value) {
2108
+ ctx = this._getOrReturnCtx(input, ctx);
2109
+ addIssueToContext(ctx, {
2110
+ code: ZodIssueCode.too_big,
2111
+ message: check.message,
2112
+ inclusive: true,
2113
+ exact: false,
2114
+ maximum: check.value,
2115
+ type: "date",
2116
+ });
2117
+ status.dirty();
2118
+ }
2119
+ }
2120
+ else {
2121
+ util.assertNever(check);
2122
+ }
2123
+ }
2124
+ return {
2125
+ status: status.value,
2126
+ value: new Date(input.data.getTime()),
2127
+ };
2128
+ }
2129
+ _addCheck(check) {
2130
+ return new ZodDate({
2131
+ ...this._def,
2132
+ checks: [...this._def.checks, check],
2133
+ });
2134
+ }
2135
+ min(minDate, message) {
2136
+ return this._addCheck({
2137
+ kind: "min",
2138
+ value: minDate.getTime(),
2139
+ message: errorUtil.toString(message),
2140
+ });
2141
+ }
2142
+ max(maxDate, message) {
2143
+ return this._addCheck({
2144
+ kind: "max",
2145
+ value: maxDate.getTime(),
2146
+ message: errorUtil.toString(message),
2147
+ });
2148
+ }
2149
+ get minDate() {
2150
+ let min = null;
2151
+ for (const ch of this._def.checks) {
2152
+ if (ch.kind === "min") {
2153
+ if (min === null || ch.value > min)
2154
+ min = ch.value;
2155
+ }
2156
+ }
2157
+ return min != null ? new Date(min) : null;
2158
+ }
2159
+ get maxDate() {
2160
+ let max = null;
2161
+ for (const ch of this._def.checks) {
2162
+ if (ch.kind === "max") {
2163
+ if (max === null || ch.value < max)
2164
+ max = ch.value;
2165
+ }
2166
+ }
2167
+ return max != null ? new Date(max) : null;
2168
+ }
2169
+ }
2170
+ ZodDate.create = (params) => {
2171
+ return new ZodDate({
2172
+ checks: [],
2173
+ coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
2174
+ typeName: ZodFirstPartyTypeKind.ZodDate,
2175
+ ...processCreateParams(params),
2176
+ });
2177
+ };
2178
+ class ZodSymbol extends ZodType {
2179
+ _parse(input) {
2180
+ const parsedType = this._getType(input);
2181
+ if (parsedType !== ZodParsedType.symbol) {
2182
+ const ctx = this._getOrReturnCtx(input);
2183
+ addIssueToContext(ctx, {
2184
+ code: ZodIssueCode.invalid_type,
2185
+ expected: ZodParsedType.symbol,
2186
+ received: ctx.parsedType,
2187
+ });
2188
+ return INVALID;
2189
+ }
2190
+ return OK(input.data);
2191
+ }
2192
+ }
2193
+ ZodSymbol.create = (params) => {
2194
+ return new ZodSymbol({
2195
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
2196
+ ...processCreateParams(params),
2197
+ });
2198
+ };
2199
+ class ZodUndefined extends ZodType {
2200
+ _parse(input) {
2201
+ const parsedType = this._getType(input);
2202
+ if (parsedType !== ZodParsedType.undefined) {
2203
+ const ctx = this._getOrReturnCtx(input);
2204
+ addIssueToContext(ctx, {
2205
+ code: ZodIssueCode.invalid_type,
2206
+ expected: ZodParsedType.undefined,
2207
+ received: ctx.parsedType,
2208
+ });
2209
+ return INVALID;
2210
+ }
2211
+ return OK(input.data);
2212
+ }
2213
+ }
2214
+ ZodUndefined.create = (params) => {
2215
+ return new ZodUndefined({
2216
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
2217
+ ...processCreateParams(params),
2218
+ });
2219
+ };
2220
+ class ZodNull extends ZodType {
2221
+ _parse(input) {
2222
+ const parsedType = this._getType(input);
2223
+ if (parsedType !== ZodParsedType.null) {
2224
+ const ctx = this._getOrReturnCtx(input);
2225
+ addIssueToContext(ctx, {
2226
+ code: ZodIssueCode.invalid_type,
2227
+ expected: ZodParsedType.null,
2228
+ received: ctx.parsedType,
2229
+ });
2230
+ return INVALID;
2231
+ }
2232
+ return OK(input.data);
2233
+ }
2234
+ }
2235
+ ZodNull.create = (params) => {
2236
+ return new ZodNull({
2237
+ typeName: ZodFirstPartyTypeKind.ZodNull,
2238
+ ...processCreateParams(params),
2239
+ });
2240
+ };
2241
+ class ZodAny extends ZodType {
2242
+ constructor() {
2243
+ super(...arguments);
2244
+ // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
2245
+ this._any = true;
2246
+ }
2247
+ _parse(input) {
2248
+ return OK(input.data);
2249
+ }
2250
+ }
2251
+ ZodAny.create = (params) => {
2252
+ return new ZodAny({
2253
+ typeName: ZodFirstPartyTypeKind.ZodAny,
2254
+ ...processCreateParams(params),
2255
+ });
2256
+ };
2257
+ class ZodUnknown extends ZodType {
2258
+ constructor() {
2259
+ super(...arguments);
2260
+ // required
2261
+ this._unknown = true;
2262
+ }
2263
+ _parse(input) {
2264
+ return OK(input.data);
2265
+ }
2266
+ }
2267
+ ZodUnknown.create = (params) => {
2268
+ return new ZodUnknown({
2269
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
2270
+ ...processCreateParams(params),
2271
+ });
2272
+ };
2273
+ class ZodNever extends ZodType {
2274
+ _parse(input) {
2275
+ const ctx = this._getOrReturnCtx(input);
2276
+ addIssueToContext(ctx, {
2277
+ code: ZodIssueCode.invalid_type,
2278
+ expected: ZodParsedType.never,
2279
+ received: ctx.parsedType,
2280
+ });
2281
+ return INVALID;
2282
+ }
2283
+ }
2284
+ ZodNever.create = (params) => {
2285
+ return new ZodNever({
2286
+ typeName: ZodFirstPartyTypeKind.ZodNever,
2287
+ ...processCreateParams(params),
2288
+ });
2289
+ };
2290
+ class ZodVoid extends ZodType {
2291
+ _parse(input) {
2292
+ const parsedType = this._getType(input);
2293
+ if (parsedType !== ZodParsedType.undefined) {
2294
+ const ctx = this._getOrReturnCtx(input);
2295
+ addIssueToContext(ctx, {
2296
+ code: ZodIssueCode.invalid_type,
2297
+ expected: ZodParsedType.void,
2298
+ received: ctx.parsedType,
2299
+ });
2300
+ return INVALID;
2301
+ }
2302
+ return OK(input.data);
2303
+ }
2304
+ }
2305
+ ZodVoid.create = (params) => {
2306
+ return new ZodVoid({
2307
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
2308
+ ...processCreateParams(params),
2309
+ });
2310
+ };
2311
+ class ZodArray extends ZodType {
2312
+ _parse(input) {
2313
+ const { ctx, status } = this._processInputParams(input);
2314
+ const def = this._def;
2315
+ if (ctx.parsedType !== ZodParsedType.array) {
2316
+ addIssueToContext(ctx, {
2317
+ code: ZodIssueCode.invalid_type,
2318
+ expected: ZodParsedType.array,
2319
+ received: ctx.parsedType,
2320
+ });
2321
+ return INVALID;
2322
+ }
2323
+ if (def.exactLength !== null) {
2324
+ const tooBig = ctx.data.length > def.exactLength.value;
2325
+ const tooSmall = ctx.data.length < def.exactLength.value;
2326
+ if (tooBig || tooSmall) {
2327
+ addIssueToContext(ctx, {
2328
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2329
+ minimum: (tooSmall ? def.exactLength.value : undefined),
2330
+ maximum: (tooBig ? def.exactLength.value : undefined),
2331
+ type: "array",
2332
+ inclusive: true,
2333
+ exact: true,
2334
+ message: def.exactLength.message,
2335
+ });
2336
+ status.dirty();
2337
+ }
2338
+ }
2339
+ if (def.minLength !== null) {
2340
+ if (ctx.data.length < def.minLength.value) {
2341
+ addIssueToContext(ctx, {
2342
+ code: ZodIssueCode.too_small,
2343
+ minimum: def.minLength.value,
2344
+ type: "array",
2345
+ inclusive: true,
2346
+ exact: false,
2347
+ message: def.minLength.message,
2348
+ });
2349
+ status.dirty();
2350
+ }
2351
+ }
2352
+ if (def.maxLength !== null) {
2353
+ if (ctx.data.length > def.maxLength.value) {
2354
+ addIssueToContext(ctx, {
2355
+ code: ZodIssueCode.too_big,
2356
+ maximum: def.maxLength.value,
2357
+ type: "array",
2358
+ inclusive: true,
2359
+ exact: false,
2360
+ message: def.maxLength.message,
2361
+ });
2362
+ status.dirty();
2363
+ }
2364
+ }
2365
+ if (ctx.common.async) {
2366
+ return Promise.all([...ctx.data].map((item, i) => {
2367
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2368
+ })).then((result) => {
2369
+ return ParseStatus.mergeArray(status, result);
2370
+ });
2371
+ }
2372
+ const result = [...ctx.data].map((item, i) => {
2373
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2374
+ });
2375
+ return ParseStatus.mergeArray(status, result);
2376
+ }
2377
+ get element() {
2378
+ return this._def.type;
2379
+ }
2380
+ min(minLength, message) {
2381
+ return new ZodArray({
2382
+ ...this._def,
2383
+ minLength: { value: minLength, message: errorUtil.toString(message) },
2384
+ });
2385
+ }
2386
+ max(maxLength, message) {
2387
+ return new ZodArray({
2388
+ ...this._def,
2389
+ maxLength: { value: maxLength, message: errorUtil.toString(message) },
2390
+ });
2391
+ }
2392
+ length(len, message) {
2393
+ return new ZodArray({
2394
+ ...this._def,
2395
+ exactLength: { value: len, message: errorUtil.toString(message) },
2396
+ });
2397
+ }
2398
+ nonempty(message) {
2399
+ return this.min(1, message);
2400
+ }
2401
+ }
2402
+ ZodArray.create = (schema, params) => {
2403
+ return new ZodArray({
2404
+ type: schema,
2405
+ minLength: null,
2406
+ maxLength: null,
2407
+ exactLength: null,
2408
+ typeName: ZodFirstPartyTypeKind.ZodArray,
2409
+ ...processCreateParams(params),
2410
+ });
2411
+ };
2412
+ function deepPartialify(schema) {
2413
+ if (schema instanceof ZodObject) {
2414
+ const newShape = {};
2415
+ for (const key in schema.shape) {
2416
+ const fieldSchema = schema.shape[key];
2417
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2418
+ }
2419
+ return new ZodObject({
2420
+ ...schema._def,
2421
+ shape: () => newShape,
2422
+ });
2423
+ }
2424
+ else if (schema instanceof ZodArray) {
2425
+ return new ZodArray({
2426
+ ...schema._def,
2427
+ type: deepPartialify(schema.element),
2428
+ });
2429
+ }
2430
+ else if (schema instanceof ZodOptional) {
2431
+ return ZodOptional.create(deepPartialify(schema.unwrap()));
2432
+ }
2433
+ else if (schema instanceof ZodNullable) {
2434
+ return ZodNullable.create(deepPartialify(schema.unwrap()));
2435
+ }
2436
+ else if (schema instanceof ZodTuple) {
2437
+ return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2438
+ }
2439
+ else {
2440
+ return schema;
2441
+ }
2442
+ }
2443
+ class ZodObject extends ZodType {
2444
+ constructor() {
2445
+ super(...arguments);
2446
+ this._cached = null;
2447
+ /**
2448
+ * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
2449
+ * If you want to pass through unknown properties, use `.passthrough()` instead.
2450
+ */
2451
+ this.nonstrict = this.passthrough;
2452
+ // extend<
2453
+ // Augmentation extends ZodRawShape,
2454
+ // NewOutput extends util.flatten<{
2455
+ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
2456
+ // ? Augmentation[k]["_output"]
2457
+ // : k extends keyof Output
2458
+ // ? Output[k]
2459
+ // : never;
2460
+ // }>,
2461
+ // NewInput extends util.flatten<{
2462
+ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
2463
+ // ? Augmentation[k]["_input"]
2464
+ // : k extends keyof Input
2465
+ // ? Input[k]
2466
+ // : never;
2467
+ // }>
2468
+ // >(
2469
+ // augmentation: Augmentation
2470
+ // ): ZodObject<
2471
+ // extendShape<T, Augmentation>,
2472
+ // UnknownKeys,
2473
+ // Catchall,
2474
+ // NewOutput,
2475
+ // NewInput
2476
+ // > {
2477
+ // return new ZodObject({
2478
+ // ...this._def,
2479
+ // shape: () => ({
2480
+ // ...this._def.shape(),
2481
+ // ...augmentation,
2482
+ // }),
2483
+ // }) as any;
2484
+ // }
2485
+ /**
2486
+ * @deprecated Use `.extend` instead
2487
+ * */
2488
+ this.augment = this.extend;
2489
+ }
2490
+ _getCached() {
2491
+ if (this._cached !== null)
2492
+ return this._cached;
2493
+ const shape = this._def.shape();
2494
+ const keys = util.objectKeys(shape);
2495
+ return (this._cached = { shape, keys });
2496
+ }
2497
+ _parse(input) {
2498
+ const parsedType = this._getType(input);
2499
+ if (parsedType !== ZodParsedType.object) {
2500
+ const ctx = this._getOrReturnCtx(input);
2501
+ addIssueToContext(ctx, {
2502
+ code: ZodIssueCode.invalid_type,
2503
+ expected: ZodParsedType.object,
2504
+ received: ctx.parsedType,
2505
+ });
2506
+ return INVALID;
2507
+ }
2508
+ const { status, ctx } = this._processInputParams(input);
2509
+ const { shape, keys: shapeKeys } = this._getCached();
2510
+ const extraKeys = [];
2511
+ if (!(this._def.catchall instanceof ZodNever &&
2512
+ this._def.unknownKeys === "strip")) {
2513
+ for (const key in ctx.data) {
2514
+ if (!shapeKeys.includes(key)) {
2515
+ extraKeys.push(key);
2516
+ }
2517
+ }
2518
+ }
2519
+ const pairs = [];
2520
+ for (const key of shapeKeys) {
2521
+ const keyValidator = shape[key];
2522
+ const value = ctx.data[key];
2523
+ pairs.push({
2524
+ key: { status: "valid", value: key },
2525
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2526
+ alwaysSet: key in ctx.data,
2527
+ });
2528
+ }
2529
+ if (this._def.catchall instanceof ZodNever) {
2530
+ const unknownKeys = this._def.unknownKeys;
2531
+ if (unknownKeys === "passthrough") {
2532
+ for (const key of extraKeys) {
2533
+ pairs.push({
2534
+ key: { status: "valid", value: key },
2535
+ value: { status: "valid", value: ctx.data[key] },
2536
+ });
2537
+ }
2538
+ }
2539
+ else if (unknownKeys === "strict") {
2540
+ if (extraKeys.length > 0) {
2541
+ addIssueToContext(ctx, {
2542
+ code: ZodIssueCode.unrecognized_keys,
2543
+ keys: extraKeys,
2544
+ });
2545
+ status.dirty();
2546
+ }
2547
+ }
2548
+ else if (unknownKeys === "strip") ;
2549
+ else {
2550
+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2551
+ }
2552
+ }
2553
+ else {
2554
+ // run catchall validation
2555
+ const catchall = this._def.catchall;
2556
+ for (const key of extraKeys) {
2557
+ const value = ctx.data[key];
2558
+ pairs.push({
2559
+ key: { status: "valid", value: key },
2560
+ value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
2561
+ ),
2562
+ alwaysSet: key in ctx.data,
2563
+ });
2564
+ }
2565
+ }
2566
+ if (ctx.common.async) {
2567
+ return Promise.resolve()
2568
+ .then(async () => {
2569
+ const syncPairs = [];
2570
+ for (const pair of pairs) {
2571
+ const key = await pair.key;
2572
+ const value = await pair.value;
2573
+ syncPairs.push({
2574
+ key,
2575
+ value,
2576
+ alwaysSet: pair.alwaysSet,
2577
+ });
2578
+ }
2579
+ return syncPairs;
2580
+ })
2581
+ .then((syncPairs) => {
2582
+ return ParseStatus.mergeObjectSync(status, syncPairs);
2583
+ });
2584
+ }
2585
+ else {
2586
+ return ParseStatus.mergeObjectSync(status, pairs);
2587
+ }
2588
+ }
2589
+ get shape() {
2590
+ return this._def.shape();
2591
+ }
2592
+ strict(message) {
2593
+ errorUtil.errToObj;
2594
+ return new ZodObject({
2595
+ ...this._def,
2596
+ unknownKeys: "strict",
2597
+ ...(message !== undefined
2598
+ ? {
2599
+ errorMap: (issue, ctx) => {
2600
+ var _a, _b, _c, _d;
2601
+ const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
2602
+ if (issue.code === "unrecognized_keys")
2603
+ return {
2604
+ message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,
2605
+ };
2606
+ return {
2607
+ message: defaultError,
2608
+ };
2609
+ },
2610
+ }
2611
+ : {}),
2612
+ });
2613
+ }
2614
+ strip() {
2615
+ return new ZodObject({
2616
+ ...this._def,
2617
+ unknownKeys: "strip",
2618
+ });
2619
+ }
2620
+ passthrough() {
2621
+ return new ZodObject({
2622
+ ...this._def,
2623
+ unknownKeys: "passthrough",
2624
+ });
2625
+ }
2626
+ // const AugmentFactory =
2627
+ // <Def extends ZodObjectDef>(def: Def) =>
2628
+ // <Augmentation extends ZodRawShape>(
2629
+ // augmentation: Augmentation
2630
+ // ): ZodObject<
2631
+ // extendShape<ReturnType<Def["shape"]>, Augmentation>,
2632
+ // Def["unknownKeys"],
2633
+ // Def["catchall"]
2634
+ // > => {
2635
+ // return new ZodObject({
2636
+ // ...def,
2637
+ // shape: () => ({
2638
+ // ...def.shape(),
2639
+ // ...augmentation,
2640
+ // }),
2641
+ // }) as any;
2642
+ // };
2643
+ extend(augmentation) {
2644
+ return new ZodObject({
2645
+ ...this._def,
2646
+ shape: () => ({
2647
+ ...this._def.shape(),
2648
+ ...augmentation,
2649
+ }),
2650
+ });
2651
+ }
2652
+ /**
2653
+ * Prior to zod@1.0.12 there was a bug in the
2654
+ * inferred type of merged objects. Please
2655
+ * upgrade if you are experiencing issues.
2656
+ */
2657
+ merge(merging) {
2658
+ const merged = new ZodObject({
2659
+ unknownKeys: merging._def.unknownKeys,
2660
+ catchall: merging._def.catchall,
2661
+ shape: () => ({
2662
+ ...this._def.shape(),
2663
+ ...merging._def.shape(),
2664
+ }),
2665
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2666
+ });
2667
+ return merged;
2668
+ }
2669
+ // merge<
2670
+ // Incoming extends AnyZodObject,
2671
+ // Augmentation extends Incoming["shape"],
2672
+ // NewOutput extends {
2673
+ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
2674
+ // ? Augmentation[k]["_output"]
2675
+ // : k extends keyof Output
2676
+ // ? Output[k]
2677
+ // : never;
2678
+ // },
2679
+ // NewInput extends {
2680
+ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
2681
+ // ? Augmentation[k]["_input"]
2682
+ // : k extends keyof Input
2683
+ // ? Input[k]
2684
+ // : never;
2685
+ // }
2686
+ // >(
2687
+ // merging: Incoming
2688
+ // ): ZodObject<
2689
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2690
+ // Incoming["_def"]["unknownKeys"],
2691
+ // Incoming["_def"]["catchall"],
2692
+ // NewOutput,
2693
+ // NewInput
2694
+ // > {
2695
+ // const merged: any = new ZodObject({
2696
+ // unknownKeys: merging._def.unknownKeys,
2697
+ // catchall: merging._def.catchall,
2698
+ // shape: () =>
2699
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2700
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
2701
+ // }) as any;
2702
+ // return merged;
2703
+ // }
2704
+ setKey(key, schema) {
2705
+ return this.augment({ [key]: schema });
2706
+ }
2707
+ // merge<Incoming extends AnyZodObject>(
2708
+ // merging: Incoming
2709
+ // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
2710
+ // ZodObject<
2711
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2712
+ // Incoming["_def"]["unknownKeys"],
2713
+ // Incoming["_def"]["catchall"]
2714
+ // > {
2715
+ // // const mergedShape = objectUtil.mergeShapes(
2716
+ // // this._def.shape(),
2717
+ // // merging._def.shape()
2718
+ // // );
2719
+ // const merged: any = new ZodObject({
2720
+ // unknownKeys: merging._def.unknownKeys,
2721
+ // catchall: merging._def.catchall,
2722
+ // shape: () =>
2723
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2724
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
2725
+ // }) as any;
2726
+ // return merged;
2727
+ // }
2728
+ catchall(index) {
2729
+ return new ZodObject({
2730
+ ...this._def,
2731
+ catchall: index,
2732
+ });
2733
+ }
2734
+ pick(mask) {
2735
+ const shape = {};
2736
+ util.objectKeys(mask).forEach((key) => {
2737
+ if (mask[key] && this.shape[key]) {
2738
+ shape[key] = this.shape[key];
2739
+ }
2740
+ });
2741
+ return new ZodObject({
2742
+ ...this._def,
2743
+ shape: () => shape,
2744
+ });
2745
+ }
2746
+ omit(mask) {
2747
+ const shape = {};
2748
+ util.objectKeys(this.shape).forEach((key) => {
2749
+ if (!mask[key]) {
2750
+ shape[key] = this.shape[key];
2751
+ }
2752
+ });
2753
+ return new ZodObject({
2754
+ ...this._def,
2755
+ shape: () => shape,
2756
+ });
2757
+ }
2758
+ /**
2759
+ * @deprecated
2760
+ */
2761
+ deepPartial() {
2762
+ return deepPartialify(this);
2763
+ }
2764
+ partial(mask) {
2765
+ const newShape = {};
2766
+ util.objectKeys(this.shape).forEach((key) => {
2767
+ const fieldSchema = this.shape[key];
2768
+ if (mask && !mask[key]) {
2769
+ newShape[key] = fieldSchema;
2770
+ }
2771
+ else {
2772
+ newShape[key] = fieldSchema.optional();
2773
+ }
2774
+ });
2775
+ return new ZodObject({
2776
+ ...this._def,
2777
+ shape: () => newShape,
2778
+ });
2779
+ }
2780
+ required(mask) {
2781
+ const newShape = {};
2782
+ util.objectKeys(this.shape).forEach((key) => {
2783
+ if (mask && !mask[key]) {
2784
+ newShape[key] = this.shape[key];
2785
+ }
2786
+ else {
2787
+ const fieldSchema = this.shape[key];
2788
+ let newField = fieldSchema;
2789
+ while (newField instanceof ZodOptional) {
2790
+ newField = newField._def.innerType;
2791
+ }
2792
+ newShape[key] = newField;
2793
+ }
2794
+ });
2795
+ return new ZodObject({
2796
+ ...this._def,
2797
+ shape: () => newShape,
2798
+ });
2799
+ }
2800
+ keyof() {
2801
+ return createZodEnum(util.objectKeys(this.shape));
2802
+ }
2803
+ }
2804
+ ZodObject.create = (shape, params) => {
2805
+ return new ZodObject({
2806
+ shape: () => shape,
2807
+ unknownKeys: "strip",
2808
+ catchall: ZodNever.create(),
2809
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2810
+ ...processCreateParams(params),
2811
+ });
2812
+ };
2813
+ ZodObject.strictCreate = (shape, params) => {
2814
+ return new ZodObject({
2815
+ shape: () => shape,
2816
+ unknownKeys: "strict",
2817
+ catchall: ZodNever.create(),
2818
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2819
+ ...processCreateParams(params),
2820
+ });
2821
+ };
2822
+ ZodObject.lazycreate = (shape, params) => {
2823
+ return new ZodObject({
2824
+ shape,
2825
+ unknownKeys: "strip",
2826
+ catchall: ZodNever.create(),
2827
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2828
+ ...processCreateParams(params),
2829
+ });
2830
+ };
2831
+ class ZodUnion extends ZodType {
2832
+ _parse(input) {
2833
+ const { ctx } = this._processInputParams(input);
2834
+ const options = this._def.options;
2835
+ function handleResults(results) {
2836
+ // return first issue-free validation if it exists
2837
+ for (const result of results) {
2838
+ if (result.result.status === "valid") {
2839
+ return result.result;
2840
+ }
2841
+ }
2842
+ for (const result of results) {
2843
+ if (result.result.status === "dirty") {
2844
+ // add issues from dirty option
2845
+ ctx.common.issues.push(...result.ctx.common.issues);
2846
+ return result.result;
2847
+ }
2848
+ }
2849
+ // return invalid
2850
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
2851
+ addIssueToContext(ctx, {
2852
+ code: ZodIssueCode.invalid_union,
2853
+ unionErrors,
2854
+ });
2855
+ return INVALID;
2856
+ }
2857
+ if (ctx.common.async) {
2858
+ return Promise.all(options.map(async (option) => {
2859
+ const childCtx = {
2860
+ ...ctx,
2861
+ common: {
2862
+ ...ctx.common,
2863
+ issues: [],
2864
+ },
2865
+ parent: null,
2866
+ };
2867
+ return {
2868
+ result: await option._parseAsync({
2869
+ data: ctx.data,
2870
+ path: ctx.path,
2871
+ parent: childCtx,
2872
+ }),
2873
+ ctx: childCtx,
2874
+ };
2875
+ })).then(handleResults);
2876
+ }
2877
+ else {
2878
+ let dirty = undefined;
2879
+ const issues = [];
2880
+ for (const option of options) {
2881
+ const childCtx = {
2882
+ ...ctx,
2883
+ common: {
2884
+ ...ctx.common,
2885
+ issues: [],
2886
+ },
2887
+ parent: null,
2888
+ };
2889
+ const result = option._parseSync({
2890
+ data: ctx.data,
2891
+ path: ctx.path,
2892
+ parent: childCtx,
2893
+ });
2894
+ if (result.status === "valid") {
2895
+ return result;
2896
+ }
2897
+ else if (result.status === "dirty" && !dirty) {
2898
+ dirty = { result, ctx: childCtx };
2899
+ }
2900
+ if (childCtx.common.issues.length) {
2901
+ issues.push(childCtx.common.issues);
2902
+ }
2903
+ }
2904
+ if (dirty) {
2905
+ ctx.common.issues.push(...dirty.ctx.common.issues);
2906
+ return dirty.result;
2907
+ }
2908
+ const unionErrors = issues.map((issues) => new ZodError(issues));
2909
+ addIssueToContext(ctx, {
2910
+ code: ZodIssueCode.invalid_union,
2911
+ unionErrors,
2912
+ });
2913
+ return INVALID;
2914
+ }
2915
+ }
2916
+ get options() {
2917
+ return this._def.options;
2918
+ }
2919
+ }
2920
+ ZodUnion.create = (types, params) => {
2921
+ return new ZodUnion({
2922
+ options: types,
2923
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
2924
+ ...processCreateParams(params),
2925
+ });
2926
+ };
2927
+ /////////////////////////////////////////////////////
2928
+ /////////////////////////////////////////////////////
2929
+ ////////// //////////
2930
+ ////////// ZodDiscriminatedUnion //////////
2931
+ ////////// //////////
2932
+ /////////////////////////////////////////////////////
2933
+ /////////////////////////////////////////////////////
2934
+ const getDiscriminator = (type) => {
2935
+ if (type instanceof ZodLazy) {
2936
+ return getDiscriminator(type.schema);
2937
+ }
2938
+ else if (type instanceof ZodEffects) {
2939
+ return getDiscriminator(type.innerType());
2940
+ }
2941
+ else if (type instanceof ZodLiteral) {
2942
+ return [type.value];
2943
+ }
2944
+ else if (type instanceof ZodEnum) {
2945
+ return type.options;
2946
+ }
2947
+ else if (type instanceof ZodNativeEnum) {
2948
+ // eslint-disable-next-line ban/ban
2949
+ return util.objectValues(type.enum);
2950
+ }
2951
+ else if (type instanceof ZodDefault) {
2952
+ return getDiscriminator(type._def.innerType);
2953
+ }
2954
+ else if (type instanceof ZodUndefined) {
2955
+ return [undefined];
2956
+ }
2957
+ else if (type instanceof ZodNull) {
2958
+ return [null];
2959
+ }
2960
+ else if (type instanceof ZodOptional) {
2961
+ return [undefined, ...getDiscriminator(type.unwrap())];
2962
+ }
2963
+ else if (type instanceof ZodNullable) {
2964
+ return [null, ...getDiscriminator(type.unwrap())];
2965
+ }
2966
+ else if (type instanceof ZodBranded) {
2967
+ return getDiscriminator(type.unwrap());
2968
+ }
2969
+ else if (type instanceof ZodReadonly) {
2970
+ return getDiscriminator(type.unwrap());
2971
+ }
2972
+ else if (type instanceof ZodCatch) {
2973
+ return getDiscriminator(type._def.innerType);
2974
+ }
2975
+ else {
2976
+ return [];
2977
+ }
2978
+ };
2979
+ class ZodDiscriminatedUnion extends ZodType {
2980
+ _parse(input) {
2981
+ const { ctx } = this._processInputParams(input);
2982
+ if (ctx.parsedType !== ZodParsedType.object) {
2983
+ addIssueToContext(ctx, {
2984
+ code: ZodIssueCode.invalid_type,
2985
+ expected: ZodParsedType.object,
2986
+ received: ctx.parsedType,
2987
+ });
2988
+ return INVALID;
2989
+ }
2990
+ const discriminator = this.discriminator;
2991
+ const discriminatorValue = ctx.data[discriminator];
2992
+ const option = this.optionsMap.get(discriminatorValue);
2993
+ if (!option) {
2994
+ addIssueToContext(ctx, {
2995
+ code: ZodIssueCode.invalid_union_discriminator,
2996
+ options: Array.from(this.optionsMap.keys()),
2997
+ path: [discriminator],
2998
+ });
2999
+ return INVALID;
3000
+ }
3001
+ if (ctx.common.async) {
3002
+ return option._parseAsync({
3003
+ data: ctx.data,
3004
+ path: ctx.path,
3005
+ parent: ctx,
3006
+ });
3007
+ }
3008
+ else {
3009
+ return option._parseSync({
3010
+ data: ctx.data,
3011
+ path: ctx.path,
3012
+ parent: ctx,
3013
+ });
3014
+ }
3015
+ }
3016
+ get discriminator() {
3017
+ return this._def.discriminator;
3018
+ }
3019
+ get options() {
3020
+ return this._def.options;
3021
+ }
3022
+ get optionsMap() {
3023
+ return this._def.optionsMap;
3024
+ }
3025
+ /**
3026
+ * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
3027
+ * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
3028
+ * have a different value for each object in the union.
3029
+ * @param discriminator the name of the discriminator property
3030
+ * @param types an array of object schemas
3031
+ * @param params
3032
+ */
3033
+ static create(discriminator, options, params) {
3034
+ // Get all the valid discriminator values
3035
+ const optionsMap = new Map();
3036
+ // try {
3037
+ for (const type of options) {
3038
+ const discriminatorValues = getDiscriminator(type.shape[discriminator]);
3039
+ if (!discriminatorValues.length) {
3040
+ throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
3041
+ }
3042
+ for (const value of discriminatorValues) {
3043
+ if (optionsMap.has(value)) {
3044
+ throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
3045
+ }
3046
+ optionsMap.set(value, type);
3047
+ }
3048
+ }
3049
+ return new ZodDiscriminatedUnion({
3050
+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
3051
+ discriminator,
3052
+ options,
3053
+ optionsMap,
3054
+ ...processCreateParams(params),
3055
+ });
3056
+ }
3057
+ }
3058
+ function mergeValues(a, b) {
3059
+ const aType = getParsedType(a);
3060
+ const bType = getParsedType(b);
3061
+ if (a === b) {
3062
+ return { valid: true, data: a };
3063
+ }
3064
+ else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
3065
+ const bKeys = util.objectKeys(b);
3066
+ const sharedKeys = util
3067
+ .objectKeys(a)
3068
+ .filter((key) => bKeys.indexOf(key) !== -1);
3069
+ const newObj = { ...a, ...b };
3070
+ for (const key of sharedKeys) {
3071
+ const sharedValue = mergeValues(a[key], b[key]);
3072
+ if (!sharedValue.valid) {
3073
+ return { valid: false };
3074
+ }
3075
+ newObj[key] = sharedValue.data;
3076
+ }
3077
+ return { valid: true, data: newObj };
3078
+ }
3079
+ else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
3080
+ if (a.length !== b.length) {
3081
+ return { valid: false };
3082
+ }
3083
+ const newArray = [];
3084
+ for (let index = 0; index < a.length; index++) {
3085
+ const itemA = a[index];
3086
+ const itemB = b[index];
3087
+ const sharedValue = mergeValues(itemA, itemB);
3088
+ if (!sharedValue.valid) {
3089
+ return { valid: false };
3090
+ }
3091
+ newArray.push(sharedValue.data);
3092
+ }
3093
+ return { valid: true, data: newArray };
3094
+ }
3095
+ else if (aType === ZodParsedType.date &&
3096
+ bType === ZodParsedType.date &&
3097
+ +a === +b) {
3098
+ return { valid: true, data: a };
3099
+ }
3100
+ else {
3101
+ return { valid: false };
3102
+ }
3103
+ }
3104
+ class ZodIntersection extends ZodType {
3105
+ _parse(input) {
3106
+ const { status, ctx } = this._processInputParams(input);
3107
+ const handleParsed = (parsedLeft, parsedRight) => {
3108
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {
3109
+ return INVALID;
3110
+ }
3111
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
3112
+ if (!merged.valid) {
3113
+ addIssueToContext(ctx, {
3114
+ code: ZodIssueCode.invalid_intersection_types,
3115
+ });
3116
+ return INVALID;
3117
+ }
3118
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {
3119
+ status.dirty();
3120
+ }
3121
+ return { status: status.value, value: merged.data };
3122
+ };
3123
+ if (ctx.common.async) {
3124
+ return Promise.all([
3125
+ this._def.left._parseAsync({
3126
+ data: ctx.data,
3127
+ path: ctx.path,
3128
+ parent: ctx,
3129
+ }),
3130
+ this._def.right._parseAsync({
3131
+ data: ctx.data,
3132
+ path: ctx.path,
3133
+ parent: ctx,
3134
+ }),
3135
+ ]).then(([left, right]) => handleParsed(left, right));
3136
+ }
3137
+ else {
3138
+ return handleParsed(this._def.left._parseSync({
3139
+ data: ctx.data,
3140
+ path: ctx.path,
3141
+ parent: ctx,
3142
+ }), this._def.right._parseSync({
3143
+ data: ctx.data,
3144
+ path: ctx.path,
3145
+ parent: ctx,
3146
+ }));
3147
+ }
3148
+ }
3149
+ }
3150
+ ZodIntersection.create = (left, right, params) => {
3151
+ return new ZodIntersection({
3152
+ left: left,
3153
+ right: right,
3154
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
3155
+ ...processCreateParams(params),
3156
+ });
3157
+ };
3158
+ class ZodTuple extends ZodType {
3159
+ _parse(input) {
3160
+ const { status, ctx } = this._processInputParams(input);
3161
+ if (ctx.parsedType !== ZodParsedType.array) {
3162
+ addIssueToContext(ctx, {
3163
+ code: ZodIssueCode.invalid_type,
3164
+ expected: ZodParsedType.array,
3165
+ received: ctx.parsedType,
3166
+ });
3167
+ return INVALID;
3168
+ }
3169
+ if (ctx.data.length < this._def.items.length) {
3170
+ addIssueToContext(ctx, {
3171
+ code: ZodIssueCode.too_small,
3172
+ minimum: this._def.items.length,
3173
+ inclusive: true,
3174
+ exact: false,
3175
+ type: "array",
3176
+ });
3177
+ return INVALID;
3178
+ }
3179
+ const rest = this._def.rest;
3180
+ if (!rest && ctx.data.length > this._def.items.length) {
3181
+ addIssueToContext(ctx, {
3182
+ code: ZodIssueCode.too_big,
3183
+ maximum: this._def.items.length,
3184
+ inclusive: true,
3185
+ exact: false,
3186
+ type: "array",
3187
+ });
3188
+ status.dirty();
3189
+ }
3190
+ const items = [...ctx.data]
3191
+ .map((item, itemIndex) => {
3192
+ const schema = this._def.items[itemIndex] || this._def.rest;
3193
+ if (!schema)
3194
+ return null;
3195
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
3196
+ })
3197
+ .filter((x) => !!x); // filter nulls
3198
+ if (ctx.common.async) {
3199
+ return Promise.all(items).then((results) => {
3200
+ return ParseStatus.mergeArray(status, results);
3201
+ });
3202
+ }
3203
+ else {
3204
+ return ParseStatus.mergeArray(status, items);
3205
+ }
3206
+ }
3207
+ get items() {
3208
+ return this._def.items;
3209
+ }
3210
+ rest(rest) {
3211
+ return new ZodTuple({
3212
+ ...this._def,
3213
+ rest,
3214
+ });
3215
+ }
3216
+ }
3217
+ ZodTuple.create = (schemas, params) => {
3218
+ if (!Array.isArray(schemas)) {
3219
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
3220
+ }
3221
+ return new ZodTuple({
3222
+ items: schemas,
3223
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
3224
+ rest: null,
3225
+ ...processCreateParams(params),
3226
+ });
3227
+ };
3228
+ class ZodRecord extends ZodType {
3229
+ get keySchema() {
3230
+ return this._def.keyType;
3231
+ }
3232
+ get valueSchema() {
3233
+ return this._def.valueType;
3234
+ }
3235
+ _parse(input) {
3236
+ const { status, ctx } = this._processInputParams(input);
3237
+ if (ctx.parsedType !== ZodParsedType.object) {
3238
+ addIssueToContext(ctx, {
3239
+ code: ZodIssueCode.invalid_type,
3240
+ expected: ZodParsedType.object,
3241
+ received: ctx.parsedType,
3242
+ });
3243
+ return INVALID;
3244
+ }
3245
+ const pairs = [];
3246
+ const keyType = this._def.keyType;
3247
+ const valueType = this._def.valueType;
3248
+ for (const key in ctx.data) {
3249
+ pairs.push({
3250
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3251
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3252
+ alwaysSet: key in ctx.data,
3253
+ });
3254
+ }
3255
+ if (ctx.common.async) {
3256
+ return ParseStatus.mergeObjectAsync(status, pairs);
3257
+ }
3258
+ else {
3259
+ return ParseStatus.mergeObjectSync(status, pairs);
3260
+ }
3261
+ }
3262
+ get element() {
3263
+ return this._def.valueType;
3264
+ }
3265
+ static create(first, second, third) {
3266
+ if (second instanceof ZodType) {
3267
+ return new ZodRecord({
3268
+ keyType: first,
3269
+ valueType: second,
3270
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3271
+ ...processCreateParams(third),
3272
+ });
3273
+ }
3274
+ return new ZodRecord({
3275
+ keyType: ZodString.create(),
3276
+ valueType: first,
3277
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3278
+ ...processCreateParams(second),
3279
+ });
3280
+ }
3281
+ }
3282
+ class ZodMap extends ZodType {
3283
+ get keySchema() {
3284
+ return this._def.keyType;
3285
+ }
3286
+ get valueSchema() {
3287
+ return this._def.valueType;
3288
+ }
3289
+ _parse(input) {
3290
+ const { status, ctx } = this._processInputParams(input);
3291
+ if (ctx.parsedType !== ZodParsedType.map) {
3292
+ addIssueToContext(ctx, {
3293
+ code: ZodIssueCode.invalid_type,
3294
+ expected: ZodParsedType.map,
3295
+ received: ctx.parsedType,
3296
+ });
3297
+ return INVALID;
3298
+ }
3299
+ const keyType = this._def.keyType;
3300
+ const valueType = this._def.valueType;
3301
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
3302
+ return {
3303
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
3304
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])),
3305
+ };
3306
+ });
3307
+ if (ctx.common.async) {
3308
+ const finalMap = new Map();
3309
+ return Promise.resolve().then(async () => {
3310
+ for (const pair of pairs) {
3311
+ const key = await pair.key;
3312
+ const value = await pair.value;
3313
+ if (key.status === "aborted" || value.status === "aborted") {
3314
+ return INVALID;
3315
+ }
3316
+ if (key.status === "dirty" || value.status === "dirty") {
3317
+ status.dirty();
3318
+ }
3319
+ finalMap.set(key.value, value.value);
3320
+ }
3321
+ return { status: status.value, value: finalMap };
3322
+ });
3323
+ }
3324
+ else {
3325
+ const finalMap = new Map();
3326
+ for (const pair of pairs) {
3327
+ const key = pair.key;
3328
+ const value = pair.value;
3329
+ if (key.status === "aborted" || value.status === "aborted") {
3330
+ return INVALID;
3331
+ }
3332
+ if (key.status === "dirty" || value.status === "dirty") {
3333
+ status.dirty();
3334
+ }
3335
+ finalMap.set(key.value, value.value);
3336
+ }
3337
+ return { status: status.value, value: finalMap };
3338
+ }
3339
+ }
3340
+ }
3341
+ ZodMap.create = (keyType, valueType, params) => {
3342
+ return new ZodMap({
3343
+ valueType,
3344
+ keyType,
3345
+ typeName: ZodFirstPartyTypeKind.ZodMap,
3346
+ ...processCreateParams(params),
3347
+ });
3348
+ };
3349
+ class ZodSet extends ZodType {
3350
+ _parse(input) {
3351
+ const { status, ctx } = this._processInputParams(input);
3352
+ if (ctx.parsedType !== ZodParsedType.set) {
3353
+ addIssueToContext(ctx, {
3354
+ code: ZodIssueCode.invalid_type,
3355
+ expected: ZodParsedType.set,
3356
+ received: ctx.parsedType,
3357
+ });
3358
+ return INVALID;
3359
+ }
3360
+ const def = this._def;
3361
+ if (def.minSize !== null) {
3362
+ if (ctx.data.size < def.minSize.value) {
3363
+ addIssueToContext(ctx, {
3364
+ code: ZodIssueCode.too_small,
3365
+ minimum: def.minSize.value,
3366
+ type: "set",
3367
+ inclusive: true,
3368
+ exact: false,
3369
+ message: def.minSize.message,
3370
+ });
3371
+ status.dirty();
3372
+ }
3373
+ }
3374
+ if (def.maxSize !== null) {
3375
+ if (ctx.data.size > def.maxSize.value) {
3376
+ addIssueToContext(ctx, {
3377
+ code: ZodIssueCode.too_big,
3378
+ maximum: def.maxSize.value,
3379
+ type: "set",
3380
+ inclusive: true,
3381
+ exact: false,
3382
+ message: def.maxSize.message,
3383
+ });
3384
+ status.dirty();
3385
+ }
3386
+ }
3387
+ const valueType = this._def.valueType;
3388
+ function finalizeSet(elements) {
3389
+ const parsedSet = new Set();
3390
+ for (const element of elements) {
3391
+ if (element.status === "aborted")
3392
+ return INVALID;
3393
+ if (element.status === "dirty")
3394
+ status.dirty();
3395
+ parsedSet.add(element.value);
3396
+ }
3397
+ return { status: status.value, value: parsedSet };
3398
+ }
3399
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3400
+ if (ctx.common.async) {
3401
+ return Promise.all(elements).then((elements) => finalizeSet(elements));
3402
+ }
3403
+ else {
3404
+ return finalizeSet(elements);
3405
+ }
3406
+ }
3407
+ min(minSize, message) {
3408
+ return new ZodSet({
3409
+ ...this._def,
3410
+ minSize: { value: minSize, message: errorUtil.toString(message) },
3411
+ });
3412
+ }
3413
+ max(maxSize, message) {
3414
+ return new ZodSet({
3415
+ ...this._def,
3416
+ maxSize: { value: maxSize, message: errorUtil.toString(message) },
3417
+ });
3418
+ }
3419
+ size(size, message) {
3420
+ return this.min(size, message).max(size, message);
3421
+ }
3422
+ nonempty(message) {
3423
+ return this.min(1, message);
3424
+ }
3425
+ }
3426
+ ZodSet.create = (valueType, params) => {
3427
+ return new ZodSet({
3428
+ valueType,
3429
+ minSize: null,
3430
+ maxSize: null,
3431
+ typeName: ZodFirstPartyTypeKind.ZodSet,
3432
+ ...processCreateParams(params),
3433
+ });
3434
+ };
3435
+ class ZodFunction extends ZodType {
3436
+ constructor() {
3437
+ super(...arguments);
3438
+ this.validate = this.implement;
3439
+ }
3440
+ _parse(input) {
3441
+ const { ctx } = this._processInputParams(input);
3442
+ if (ctx.parsedType !== ZodParsedType.function) {
3443
+ addIssueToContext(ctx, {
3444
+ code: ZodIssueCode.invalid_type,
3445
+ expected: ZodParsedType.function,
3446
+ received: ctx.parsedType,
3447
+ });
3448
+ return INVALID;
3449
+ }
3450
+ function makeArgsIssue(args, error) {
3451
+ return makeIssue({
3452
+ data: args,
3453
+ path: ctx.path,
3454
+ errorMaps: [
3455
+ ctx.common.contextualErrorMap,
3456
+ ctx.schemaErrorMap,
3457
+ getErrorMap(),
3458
+ errorMap,
3459
+ ].filter((x) => !!x),
3460
+ issueData: {
3461
+ code: ZodIssueCode.invalid_arguments,
3462
+ argumentsError: error,
3463
+ },
3464
+ });
3465
+ }
3466
+ function makeReturnsIssue(returns, error) {
3467
+ return makeIssue({
3468
+ data: returns,
3469
+ path: ctx.path,
3470
+ errorMaps: [
3471
+ ctx.common.contextualErrorMap,
3472
+ ctx.schemaErrorMap,
3473
+ getErrorMap(),
3474
+ errorMap,
3475
+ ].filter((x) => !!x),
3476
+ issueData: {
3477
+ code: ZodIssueCode.invalid_return_type,
3478
+ returnTypeError: error,
3479
+ },
3480
+ });
3481
+ }
3482
+ const params = { errorMap: ctx.common.contextualErrorMap };
3483
+ const fn = ctx.data;
3484
+ if (this._def.returns instanceof ZodPromise) {
3485
+ // Would love a way to avoid disabling this rule, but we need
3486
+ // an alias (using an arrow function was what caused 2651).
3487
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
3488
+ const me = this;
3489
+ return OK(async function (...args) {
3490
+ const error = new ZodError([]);
3491
+ const parsedArgs = await me._def.args
3492
+ .parseAsync(args, params)
3493
+ .catch((e) => {
3494
+ error.addIssue(makeArgsIssue(args, e));
3495
+ throw error;
3496
+ });
3497
+ const result = await Reflect.apply(fn, this, parsedArgs);
3498
+ const parsedReturns = await me._def.returns._def.type
3499
+ .parseAsync(result, params)
3500
+ .catch((e) => {
3501
+ error.addIssue(makeReturnsIssue(result, e));
3502
+ throw error;
3503
+ });
3504
+ return parsedReturns;
3505
+ });
3506
+ }
3507
+ else {
3508
+ // Would love a way to avoid disabling this rule, but we need
3509
+ // an alias (using an arrow function was what caused 2651).
3510
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
3511
+ const me = this;
3512
+ return OK(function (...args) {
3513
+ const parsedArgs = me._def.args.safeParse(args, params);
3514
+ if (!parsedArgs.success) {
3515
+ throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3516
+ }
3517
+ const result = Reflect.apply(fn, this, parsedArgs.data);
3518
+ const parsedReturns = me._def.returns.safeParse(result, params);
3519
+ if (!parsedReturns.success) {
3520
+ throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3521
+ }
3522
+ return parsedReturns.data;
3523
+ });
3524
+ }
3525
+ }
3526
+ parameters() {
3527
+ return this._def.args;
3528
+ }
3529
+ returnType() {
3530
+ return this._def.returns;
3531
+ }
3532
+ args(...items) {
3533
+ return new ZodFunction({
3534
+ ...this._def,
3535
+ args: ZodTuple.create(items).rest(ZodUnknown.create()),
3536
+ });
3537
+ }
3538
+ returns(returnType) {
3539
+ return new ZodFunction({
3540
+ ...this._def,
3541
+ returns: returnType,
3542
+ });
3543
+ }
3544
+ implement(func) {
3545
+ const validatedFunc = this.parse(func);
3546
+ return validatedFunc;
3547
+ }
3548
+ strictImplement(func) {
3549
+ const validatedFunc = this.parse(func);
3550
+ return validatedFunc;
3551
+ }
3552
+ static create(args, returns, params) {
3553
+ return new ZodFunction({
3554
+ args: (args
3555
+ ? args
3556
+ : ZodTuple.create([]).rest(ZodUnknown.create())),
3557
+ returns: returns || ZodUnknown.create(),
3558
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
3559
+ ...processCreateParams(params),
3560
+ });
3561
+ }
3562
+ }
3563
+ class ZodLazy extends ZodType {
3564
+ get schema() {
3565
+ return this._def.getter();
3566
+ }
3567
+ _parse(input) {
3568
+ const { ctx } = this._processInputParams(input);
3569
+ const lazySchema = this._def.getter();
3570
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
3571
+ }
3572
+ }
3573
+ ZodLazy.create = (getter, params) => {
3574
+ return new ZodLazy({
3575
+ getter: getter,
3576
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
3577
+ ...processCreateParams(params),
3578
+ });
3579
+ };
3580
+ class ZodLiteral extends ZodType {
3581
+ _parse(input) {
3582
+ if (input.data !== this._def.value) {
3583
+ const ctx = this._getOrReturnCtx(input);
3584
+ addIssueToContext(ctx, {
3585
+ received: ctx.data,
3586
+ code: ZodIssueCode.invalid_literal,
3587
+ expected: this._def.value,
3588
+ });
3589
+ return INVALID;
3590
+ }
3591
+ return { status: "valid", value: input.data };
3592
+ }
3593
+ get value() {
3594
+ return this._def.value;
3595
+ }
3596
+ }
3597
+ ZodLiteral.create = (value, params) => {
3598
+ return new ZodLiteral({
3599
+ value: value,
3600
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
3601
+ ...processCreateParams(params),
3602
+ });
3603
+ };
3604
+ function createZodEnum(values, params) {
3605
+ return new ZodEnum({
3606
+ values,
3607
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
3608
+ ...processCreateParams(params),
3609
+ });
3610
+ }
3611
+ class ZodEnum extends ZodType {
3612
+ constructor() {
3613
+ super(...arguments);
3614
+ _ZodEnum_cache.set(this, void 0);
3615
+ }
3616
+ _parse(input) {
3617
+ if (typeof input.data !== "string") {
3618
+ const ctx = this._getOrReturnCtx(input);
3619
+ const expectedValues = this._def.values;
3620
+ addIssueToContext(ctx, {
3621
+ expected: util.joinValues(expectedValues),
3622
+ received: ctx.parsedType,
3623
+ code: ZodIssueCode.invalid_type,
3624
+ });
3625
+ return INVALID;
3626
+ }
3627
+ if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
3628
+ __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
3629
+ }
3630
+ if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
3631
+ const ctx = this._getOrReturnCtx(input);
3632
+ const expectedValues = this._def.values;
3633
+ addIssueToContext(ctx, {
3634
+ received: ctx.data,
3635
+ code: ZodIssueCode.invalid_enum_value,
3636
+ options: expectedValues,
3637
+ });
3638
+ return INVALID;
3639
+ }
3640
+ return OK(input.data);
3641
+ }
3642
+ get options() {
3643
+ return this._def.values;
3644
+ }
3645
+ get enum() {
3646
+ const enumValues = {};
3647
+ for (const val of this._def.values) {
3648
+ enumValues[val] = val;
3649
+ }
3650
+ return enumValues;
3651
+ }
3652
+ get Values() {
3653
+ const enumValues = {};
3654
+ for (const val of this._def.values) {
3655
+ enumValues[val] = val;
3656
+ }
3657
+ return enumValues;
3658
+ }
3659
+ get Enum() {
3660
+ const enumValues = {};
3661
+ for (const val of this._def.values) {
3662
+ enumValues[val] = val;
3663
+ }
3664
+ return enumValues;
3665
+ }
3666
+ extract(values, newDef = this._def) {
3667
+ return ZodEnum.create(values, {
3668
+ ...this._def,
3669
+ ...newDef,
3670
+ });
3671
+ }
3672
+ exclude(values, newDef = this._def) {
3673
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3674
+ ...this._def,
3675
+ ...newDef,
3676
+ });
3677
+ }
3678
+ }
3679
+ _ZodEnum_cache = new WeakMap();
3680
+ ZodEnum.create = createZodEnum;
3681
+ class ZodNativeEnum extends ZodType {
3682
+ constructor() {
3683
+ super(...arguments);
3684
+ _ZodNativeEnum_cache.set(this, void 0);
3685
+ }
3686
+ _parse(input) {
3687
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
3688
+ const ctx = this._getOrReturnCtx(input);
3689
+ if (ctx.parsedType !== ZodParsedType.string &&
3690
+ ctx.parsedType !== ZodParsedType.number) {
3691
+ const expectedValues = util.objectValues(nativeEnumValues);
3692
+ addIssueToContext(ctx, {
3693
+ expected: util.joinValues(expectedValues),
3694
+ received: ctx.parsedType,
3695
+ code: ZodIssueCode.invalid_type,
3696
+ });
3697
+ return INVALID;
3698
+ }
3699
+ if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
3700
+ __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
3701
+ }
3702
+ if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
3703
+ const expectedValues = util.objectValues(nativeEnumValues);
3704
+ addIssueToContext(ctx, {
3705
+ received: ctx.data,
3706
+ code: ZodIssueCode.invalid_enum_value,
3707
+ options: expectedValues,
3708
+ });
3709
+ return INVALID;
3710
+ }
3711
+ return OK(input.data);
3712
+ }
3713
+ get enum() {
3714
+ return this._def.values;
3715
+ }
3716
+ }
3717
+ _ZodNativeEnum_cache = new WeakMap();
3718
+ ZodNativeEnum.create = (values, params) => {
3719
+ return new ZodNativeEnum({
3720
+ values: values,
3721
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3722
+ ...processCreateParams(params),
3723
+ });
3724
+ };
3725
+ class ZodPromise extends ZodType {
3726
+ unwrap() {
3727
+ return this._def.type;
3728
+ }
3729
+ _parse(input) {
3730
+ const { ctx } = this._processInputParams(input);
3731
+ if (ctx.parsedType !== ZodParsedType.promise &&
3732
+ ctx.common.async === false) {
3733
+ addIssueToContext(ctx, {
3734
+ code: ZodIssueCode.invalid_type,
3735
+ expected: ZodParsedType.promise,
3736
+ received: ctx.parsedType,
3737
+ });
3738
+ return INVALID;
3739
+ }
3740
+ const promisified = ctx.parsedType === ZodParsedType.promise
3741
+ ? ctx.data
3742
+ : Promise.resolve(ctx.data);
3743
+ return OK(promisified.then((data) => {
3744
+ return this._def.type.parseAsync(data, {
3745
+ path: ctx.path,
3746
+ errorMap: ctx.common.contextualErrorMap,
3747
+ });
3748
+ }));
3749
+ }
3750
+ }
3751
+ ZodPromise.create = (schema, params) => {
3752
+ return new ZodPromise({
3753
+ type: schema,
3754
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
3755
+ ...processCreateParams(params),
3756
+ });
3757
+ };
3758
+ class ZodEffects extends ZodType {
3759
+ innerType() {
3760
+ return this._def.schema;
3761
+ }
3762
+ sourceType() {
3763
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects
3764
+ ? this._def.schema.sourceType()
3765
+ : this._def.schema;
3766
+ }
3767
+ _parse(input) {
3768
+ const { status, ctx } = this._processInputParams(input);
3769
+ const effect = this._def.effect || null;
3770
+ const checkCtx = {
3771
+ addIssue: (arg) => {
3772
+ addIssueToContext(ctx, arg);
3773
+ if (arg.fatal) {
3774
+ status.abort();
3775
+ }
3776
+ else {
3777
+ status.dirty();
3778
+ }
3779
+ },
3780
+ get path() {
3781
+ return ctx.path;
3782
+ },
3783
+ };
3784
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3785
+ if (effect.type === "preprocess") {
3786
+ const processed = effect.transform(ctx.data, checkCtx);
3787
+ if (ctx.common.async) {
3788
+ return Promise.resolve(processed).then(async (processed) => {
3789
+ if (status.value === "aborted")
3790
+ return INVALID;
3791
+ const result = await this._def.schema._parseAsync({
3792
+ data: processed,
3793
+ path: ctx.path,
3794
+ parent: ctx,
3795
+ });
3796
+ if (result.status === "aborted")
3797
+ return INVALID;
3798
+ if (result.status === "dirty")
3799
+ return DIRTY(result.value);
3800
+ if (status.value === "dirty")
3801
+ return DIRTY(result.value);
3802
+ return result;
3803
+ });
3804
+ }
3805
+ else {
3806
+ if (status.value === "aborted")
3807
+ return INVALID;
3808
+ const result = this._def.schema._parseSync({
3809
+ data: processed,
3810
+ path: ctx.path,
3811
+ parent: ctx,
3812
+ });
3813
+ if (result.status === "aborted")
3814
+ return INVALID;
3815
+ if (result.status === "dirty")
3816
+ return DIRTY(result.value);
3817
+ if (status.value === "dirty")
3818
+ return DIRTY(result.value);
3819
+ return result;
3820
+ }
3821
+ }
3822
+ if (effect.type === "refinement") {
3823
+ const executeRefinement = (acc) => {
3824
+ const result = effect.refinement(acc, checkCtx);
3825
+ if (ctx.common.async) {
3826
+ return Promise.resolve(result);
3827
+ }
3828
+ if (result instanceof Promise) {
3829
+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3830
+ }
3831
+ return acc;
3832
+ };
3833
+ if (ctx.common.async === false) {
3834
+ const inner = this._def.schema._parseSync({
3835
+ data: ctx.data,
3836
+ path: ctx.path,
3837
+ parent: ctx,
3838
+ });
3839
+ if (inner.status === "aborted")
3840
+ return INVALID;
3841
+ if (inner.status === "dirty")
3842
+ status.dirty();
3843
+ // return value is ignored
3844
+ executeRefinement(inner.value);
3845
+ return { status: status.value, value: inner.value };
3846
+ }
3847
+ else {
3848
+ return this._def.schema
3849
+ ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
3850
+ .then((inner) => {
3851
+ if (inner.status === "aborted")
3852
+ return INVALID;
3853
+ if (inner.status === "dirty")
3854
+ status.dirty();
3855
+ return executeRefinement(inner.value).then(() => {
3856
+ return { status: status.value, value: inner.value };
3857
+ });
3858
+ });
3859
+ }
3860
+ }
3861
+ if (effect.type === "transform") {
3862
+ if (ctx.common.async === false) {
3863
+ const base = this._def.schema._parseSync({
3864
+ data: ctx.data,
3865
+ path: ctx.path,
3866
+ parent: ctx,
3867
+ });
3868
+ if (!isValid(base))
3869
+ return base;
3870
+ const result = effect.transform(base.value, checkCtx);
3871
+ if (result instanceof Promise) {
3872
+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3873
+ }
3874
+ return { status: status.value, value: result };
3875
+ }
3876
+ else {
3877
+ return this._def.schema
3878
+ ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
3879
+ .then((base) => {
3880
+ if (!isValid(base))
3881
+ return base;
3882
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
3883
+ });
3884
+ }
3885
+ }
3886
+ util.assertNever(effect);
3887
+ }
3888
+ }
3889
+ ZodEffects.create = (schema, effect, params) => {
3890
+ return new ZodEffects({
3891
+ schema,
3892
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3893
+ effect,
3894
+ ...processCreateParams(params),
3895
+ });
3896
+ };
3897
+ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3898
+ return new ZodEffects({
3899
+ schema,
3900
+ effect: { type: "preprocess", transform: preprocess },
3901
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3902
+ ...processCreateParams(params),
3903
+ });
3904
+ };
3905
+ class ZodOptional extends ZodType {
3906
+ _parse(input) {
3907
+ const parsedType = this._getType(input);
3908
+ if (parsedType === ZodParsedType.undefined) {
3909
+ return OK(undefined);
3910
+ }
3911
+ return this._def.innerType._parse(input);
3912
+ }
3913
+ unwrap() {
3914
+ return this._def.innerType;
3915
+ }
3916
+ }
3917
+ ZodOptional.create = (type, params) => {
3918
+ return new ZodOptional({
3919
+ innerType: type,
3920
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
3921
+ ...processCreateParams(params),
3922
+ });
3923
+ };
3924
+ class ZodNullable extends ZodType {
3925
+ _parse(input) {
3926
+ const parsedType = this._getType(input);
3927
+ if (parsedType === ZodParsedType.null) {
3928
+ return OK(null);
3929
+ }
3930
+ return this._def.innerType._parse(input);
3931
+ }
3932
+ unwrap() {
3933
+ return this._def.innerType;
3934
+ }
3935
+ }
3936
+ ZodNullable.create = (type, params) => {
3937
+ return new ZodNullable({
3938
+ innerType: type,
3939
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
3940
+ ...processCreateParams(params),
3941
+ });
3942
+ };
3943
+ class ZodDefault extends ZodType {
3944
+ _parse(input) {
3945
+ const { ctx } = this._processInputParams(input);
3946
+ let data = ctx.data;
3947
+ if (ctx.parsedType === ZodParsedType.undefined) {
3948
+ data = this._def.defaultValue();
3949
+ }
3950
+ return this._def.innerType._parse({
3951
+ data,
3952
+ path: ctx.path,
3953
+ parent: ctx,
3954
+ });
3955
+ }
3956
+ removeDefault() {
3957
+ return this._def.innerType;
3958
+ }
3959
+ }
3960
+ ZodDefault.create = (type, params) => {
3961
+ return new ZodDefault({
3962
+ innerType: type,
3963
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
3964
+ defaultValue: typeof params.default === "function"
3965
+ ? params.default
3966
+ : () => params.default,
3967
+ ...processCreateParams(params),
3968
+ });
3969
+ };
3970
+ class ZodCatch extends ZodType {
3971
+ _parse(input) {
3972
+ const { ctx } = this._processInputParams(input);
3973
+ // newCtx is used to not collect issues from inner types in ctx
3974
+ const newCtx = {
3975
+ ...ctx,
3976
+ common: {
3977
+ ...ctx.common,
3978
+ issues: [],
3979
+ },
3980
+ };
3981
+ const result = this._def.innerType._parse({
3982
+ data: newCtx.data,
3983
+ path: newCtx.path,
3984
+ parent: {
3985
+ ...newCtx,
3986
+ },
3987
+ });
3988
+ if (isAsync(result)) {
3989
+ return result.then((result) => {
3990
+ return {
3991
+ status: "valid",
3992
+ value: result.status === "valid"
3993
+ ? result.value
3994
+ : this._def.catchValue({
3995
+ get error() {
3996
+ return new ZodError(newCtx.common.issues);
3997
+ },
3998
+ input: newCtx.data,
3999
+ }),
4000
+ };
4001
+ });
4002
+ }
4003
+ else {
4004
+ return {
4005
+ status: "valid",
4006
+ value: result.status === "valid"
4007
+ ? result.value
4008
+ : this._def.catchValue({
4009
+ get error() {
4010
+ return new ZodError(newCtx.common.issues);
4011
+ },
4012
+ input: newCtx.data,
4013
+ }),
4014
+ };
4015
+ }
4016
+ }
4017
+ removeCatch() {
4018
+ return this._def.innerType;
4019
+ }
4020
+ }
4021
+ ZodCatch.create = (type, params) => {
4022
+ return new ZodCatch({
4023
+ innerType: type,
4024
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
4025
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
4026
+ ...processCreateParams(params),
4027
+ });
4028
+ };
4029
+ class ZodNaN extends ZodType {
4030
+ _parse(input) {
4031
+ const parsedType = this._getType(input);
4032
+ if (parsedType !== ZodParsedType.nan) {
4033
+ const ctx = this._getOrReturnCtx(input);
4034
+ addIssueToContext(ctx, {
4035
+ code: ZodIssueCode.invalid_type,
4036
+ expected: ZodParsedType.nan,
4037
+ received: ctx.parsedType,
4038
+ });
4039
+ return INVALID;
4040
+ }
4041
+ return { status: "valid", value: input.data };
4042
+ }
4043
+ }
4044
+ ZodNaN.create = (params) => {
4045
+ return new ZodNaN({
4046
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
4047
+ ...processCreateParams(params),
4048
+ });
4049
+ };
4050
+ const BRAND = Symbol("zod_brand");
4051
+ class ZodBranded extends ZodType {
4052
+ _parse(input) {
4053
+ const { ctx } = this._processInputParams(input);
4054
+ const data = ctx.data;
4055
+ return this._def.type._parse({
4056
+ data,
4057
+ path: ctx.path,
4058
+ parent: ctx,
4059
+ });
4060
+ }
4061
+ unwrap() {
4062
+ return this._def.type;
4063
+ }
4064
+ }
4065
+ class ZodPipeline extends ZodType {
4066
+ _parse(input) {
4067
+ const { status, ctx } = this._processInputParams(input);
4068
+ if (ctx.common.async) {
4069
+ const handleAsync = async () => {
4070
+ const inResult = await this._def.in._parseAsync({
4071
+ data: ctx.data,
4072
+ path: ctx.path,
4073
+ parent: ctx,
4074
+ });
4075
+ if (inResult.status === "aborted")
4076
+ return INVALID;
4077
+ if (inResult.status === "dirty") {
4078
+ status.dirty();
4079
+ return DIRTY(inResult.value);
4080
+ }
4081
+ else {
4082
+ return this._def.out._parseAsync({
4083
+ data: inResult.value,
4084
+ path: ctx.path,
4085
+ parent: ctx,
4086
+ });
4087
+ }
4088
+ };
4089
+ return handleAsync();
4090
+ }
4091
+ else {
4092
+ const inResult = this._def.in._parseSync({
4093
+ data: ctx.data,
4094
+ path: ctx.path,
4095
+ parent: ctx,
4096
+ });
4097
+ if (inResult.status === "aborted")
4098
+ return INVALID;
4099
+ if (inResult.status === "dirty") {
4100
+ status.dirty();
4101
+ return {
4102
+ status: "dirty",
4103
+ value: inResult.value,
4104
+ };
4105
+ }
4106
+ else {
4107
+ return this._def.out._parseSync({
4108
+ data: inResult.value,
4109
+ path: ctx.path,
4110
+ parent: ctx,
4111
+ });
4112
+ }
4113
+ }
4114
+ }
4115
+ static create(a, b) {
4116
+ return new ZodPipeline({
4117
+ in: a,
4118
+ out: b,
4119
+ typeName: ZodFirstPartyTypeKind.ZodPipeline,
4120
+ });
4121
+ }
4122
+ }
4123
+ class ZodReadonly extends ZodType {
4124
+ _parse(input) {
4125
+ const result = this._def.innerType._parse(input);
4126
+ const freeze = (data) => {
4127
+ if (isValid(data)) {
4128
+ data.value = Object.freeze(data.value);
4129
+ }
4130
+ return data;
4131
+ };
4132
+ return isAsync(result)
4133
+ ? result.then((data) => freeze(data))
4134
+ : freeze(result);
4135
+ }
4136
+ unwrap() {
4137
+ return this._def.innerType;
4138
+ }
4139
+ }
4140
+ ZodReadonly.create = (type, params) => {
4141
+ return new ZodReadonly({
4142
+ innerType: type,
4143
+ typeName: ZodFirstPartyTypeKind.ZodReadonly,
4144
+ ...processCreateParams(params),
4145
+ });
4146
+ };
4147
+ ////////////////////////////////////////
4148
+ ////////////////////////////////////////
4149
+ ////////// //////////
4150
+ ////////// z.custom //////////
4151
+ ////////// //////////
4152
+ ////////////////////////////////////////
4153
+ ////////////////////////////////////////
4154
+ function cleanParams(params, data) {
4155
+ const p = typeof params === "function"
4156
+ ? params(data)
4157
+ : typeof params === "string"
4158
+ ? { message: params }
4159
+ : params;
4160
+ const p2 = typeof p === "string" ? { message: p } : p;
4161
+ return p2;
4162
+ }
4163
+ function custom(check, _params = {},
4164
+ /**
4165
+ * @deprecated
4166
+ *
4167
+ * Pass `fatal` into the params object instead:
4168
+ *
4169
+ * ```ts
4170
+ * z.string().custom((val) => val.length > 5, { fatal: false })
4171
+ * ```
4172
+ *
4173
+ */
4174
+ fatal) {
4175
+ if (check)
4176
+ return ZodAny.create().superRefine((data, ctx) => {
4177
+ var _a, _b;
4178
+ const r = check(data);
4179
+ if (r instanceof Promise) {
4180
+ return r.then((r) => {
4181
+ var _a, _b;
4182
+ if (!r) {
4183
+ const params = cleanParams(_params, data);
4184
+ const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
4185
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
4186
+ }
4187
+ });
4188
+ }
4189
+ if (!r) {
4190
+ const params = cleanParams(_params, data);
4191
+ const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
4192
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
4193
+ }
4194
+ return;
4195
+ });
4196
+ return ZodAny.create();
4197
+ }
4198
+ const late = {
4199
+ object: ZodObject.lazycreate,
4200
+ };
4201
+ var ZodFirstPartyTypeKind;
4202
+ (function (ZodFirstPartyTypeKind) {
4203
+ ZodFirstPartyTypeKind["ZodString"] = "ZodString";
4204
+ ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
4205
+ ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
4206
+ ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
4207
+ ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
4208
+ ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
4209
+ ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
4210
+ ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
4211
+ ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
4212
+ ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
4213
+ ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
4214
+ ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
4215
+ ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
4216
+ ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
4217
+ ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
4218
+ ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
4219
+ ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
4220
+ ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
4221
+ ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
4222
+ ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
4223
+ ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
4224
+ ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
4225
+ ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
4226
+ ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
4227
+ ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
4228
+ ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
4229
+ ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
4230
+ ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
4231
+ ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
4232
+ ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
4233
+ ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
4234
+ ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
4235
+ ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
4236
+ ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
4237
+ ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
4238
+ ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
4239
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
4240
+ const instanceOfType = (
4241
+ // const instanceOfType = <T extends new (...args: any[]) => any>(
4242
+ cls, params = {
4243
+ message: `Input not instance of ${cls.name}`,
4244
+ }) => custom((data) => data instanceof cls, params);
4245
+ const stringType = ZodString.create;
4246
+ const numberType = ZodNumber.create;
4247
+ const nanType = ZodNaN.create;
4248
+ const bigIntType = ZodBigInt.create;
4249
+ const booleanType = ZodBoolean.create;
4250
+ const dateType = ZodDate.create;
4251
+ const symbolType = ZodSymbol.create;
4252
+ const undefinedType = ZodUndefined.create;
4253
+ const nullType = ZodNull.create;
4254
+ const anyType = ZodAny.create;
4255
+ const unknownType = ZodUnknown.create;
4256
+ const neverType = ZodNever.create;
4257
+ const voidType = ZodVoid.create;
4258
+ const arrayType = ZodArray.create;
4259
+ const objectType = ZodObject.create;
4260
+ const strictObjectType = ZodObject.strictCreate;
4261
+ const unionType = ZodUnion.create;
4262
+ const discriminatedUnionType = ZodDiscriminatedUnion.create;
4263
+ const intersectionType = ZodIntersection.create;
4264
+ const tupleType = ZodTuple.create;
4265
+ const recordType = ZodRecord.create;
4266
+ const mapType = ZodMap.create;
4267
+ const setType = ZodSet.create;
4268
+ const functionType = ZodFunction.create;
4269
+ const lazyType = ZodLazy.create;
4270
+ const literalType = ZodLiteral.create;
4271
+ const enumType = ZodEnum.create;
4272
+ const nativeEnumType = ZodNativeEnum.create;
4273
+ const promiseType = ZodPromise.create;
4274
+ const effectsType = ZodEffects.create;
4275
+ const optionalType = ZodOptional.create;
4276
+ const nullableType = ZodNullable.create;
4277
+ const preprocessType = ZodEffects.createWithPreprocess;
4278
+ const pipelineType = ZodPipeline.create;
4279
+ const ostring = () => stringType().optional();
4280
+ const onumber = () => numberType().optional();
4281
+ const oboolean = () => booleanType().optional();
4282
+ const coerce = {
4283
+ string: ((arg) => ZodString.create({ ...arg, coerce: true })),
4284
+ number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
4285
+ boolean: ((arg) => ZodBoolean.create({
4286
+ ...arg,
4287
+ coerce: true,
4288
+ })),
4289
+ bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
4290
+ date: ((arg) => ZodDate.create({ ...arg, coerce: true })),
4291
+ };
4292
+ const NEVER = INVALID;
4293
+
4294
+ var z = /*#__PURE__*/Object.freeze({
4295
+ __proto__: null,
4296
+ defaultErrorMap: errorMap,
4297
+ setErrorMap: setErrorMap,
4298
+ getErrorMap: getErrorMap,
4299
+ makeIssue: makeIssue,
4300
+ EMPTY_PATH: EMPTY_PATH,
4301
+ addIssueToContext: addIssueToContext,
4302
+ ParseStatus: ParseStatus,
4303
+ INVALID: INVALID,
4304
+ DIRTY: DIRTY,
4305
+ OK: OK,
4306
+ isAborted: isAborted,
4307
+ isDirty: isDirty,
4308
+ isValid: isValid,
4309
+ isAsync: isAsync,
4310
+ get util () { return util; },
4311
+ get objectUtil () { return objectUtil; },
4312
+ ZodParsedType: ZodParsedType,
4313
+ getParsedType: getParsedType,
4314
+ ZodType: ZodType,
4315
+ datetimeRegex: datetimeRegex,
4316
+ ZodString: ZodString,
4317
+ ZodNumber: ZodNumber,
4318
+ ZodBigInt: ZodBigInt,
4319
+ ZodBoolean: ZodBoolean,
4320
+ ZodDate: ZodDate,
4321
+ ZodSymbol: ZodSymbol,
4322
+ ZodUndefined: ZodUndefined,
4323
+ ZodNull: ZodNull,
4324
+ ZodAny: ZodAny,
4325
+ ZodUnknown: ZodUnknown,
4326
+ ZodNever: ZodNever,
4327
+ ZodVoid: ZodVoid,
4328
+ ZodArray: ZodArray,
4329
+ ZodObject: ZodObject,
4330
+ ZodUnion: ZodUnion,
4331
+ ZodDiscriminatedUnion: ZodDiscriminatedUnion,
4332
+ ZodIntersection: ZodIntersection,
4333
+ ZodTuple: ZodTuple,
4334
+ ZodRecord: ZodRecord,
4335
+ ZodMap: ZodMap,
4336
+ ZodSet: ZodSet,
4337
+ ZodFunction: ZodFunction,
4338
+ ZodLazy: ZodLazy,
4339
+ ZodLiteral: ZodLiteral,
4340
+ ZodEnum: ZodEnum,
4341
+ ZodNativeEnum: ZodNativeEnum,
4342
+ ZodPromise: ZodPromise,
4343
+ ZodEffects: ZodEffects,
4344
+ ZodTransformer: ZodEffects,
4345
+ ZodOptional: ZodOptional,
4346
+ ZodNullable: ZodNullable,
4347
+ ZodDefault: ZodDefault,
4348
+ ZodCatch: ZodCatch,
4349
+ ZodNaN: ZodNaN,
4350
+ BRAND: BRAND,
4351
+ ZodBranded: ZodBranded,
4352
+ ZodPipeline: ZodPipeline,
4353
+ ZodReadonly: ZodReadonly,
4354
+ custom: custom,
4355
+ Schema: ZodType,
4356
+ ZodSchema: ZodType,
4357
+ late: late,
4358
+ get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },
4359
+ coerce: coerce,
4360
+ any: anyType,
4361
+ array: arrayType,
4362
+ bigint: bigIntType,
4363
+ boolean: booleanType,
4364
+ date: dateType,
4365
+ discriminatedUnion: discriminatedUnionType,
4366
+ effect: effectsType,
4367
+ 'enum': enumType,
4368
+ 'function': functionType,
4369
+ 'instanceof': instanceOfType,
4370
+ intersection: intersectionType,
4371
+ lazy: lazyType,
4372
+ literal: literalType,
4373
+ map: mapType,
4374
+ nan: nanType,
4375
+ nativeEnum: nativeEnumType,
4376
+ never: neverType,
4377
+ 'null': nullType,
4378
+ nullable: nullableType,
4379
+ number: numberType,
4380
+ object: objectType,
4381
+ oboolean: oboolean,
4382
+ onumber: onumber,
4383
+ optional: optionalType,
4384
+ ostring: ostring,
4385
+ pipeline: pipelineType,
4386
+ preprocess: preprocessType,
4387
+ promise: promiseType,
4388
+ record: recordType,
4389
+ set: setType,
4390
+ strictObject: strictObjectType,
4391
+ string: stringType,
4392
+ symbol: symbolType,
4393
+ transformer: effectsType,
4394
+ tuple: tupleType,
4395
+ 'undefined': undefinedType,
4396
+ union: unionType,
4397
+ unknown: unknownType,
4398
+ 'void': voidType,
4399
+ NEVER: NEVER,
4400
+ ZodIssueCode: ZodIssueCode,
4401
+ quotelessJson: quotelessJson,
4402
+ ZodError: ZodError
4403
+ });
4404
+
4405
+ export { BRAND, DIRTY, EMPTY_PATH, INVALID, NEVER, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, ZodCatch, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodError, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodIssueCode, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPipeline, ZodPromise, ZodReadonly, ZodRecord, ZodType as ZodSchema, ZodSet, ZodString, ZodSymbol, ZodEffects as ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, coerce, custom, dateType as date, datetimeRegex, z as default, errorMap as defaultErrorMap, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, getErrorMap, getParsedType, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setType as set, setErrorMap, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, util, voidType as void, z };
4406
+ //# sourceMappingURL=index.js.map