@marteye/studiojs 1.1.13 → 1.1.15

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