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