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