@embeddable.com/sdk-utils 0.2.0 → 0.2.1

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