zod 3.20.6 → 3.21.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/types.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.custom = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.objectUtil = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0;
4
- exports.NEVER = exports.void = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports.null = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports.instanceof = exports.function = exports.enum = exports.effect = exports.discriminatedUnion = void 0;
3
+ exports.discriminatedUnion = exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.custom = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0;
4
+ exports.NEVER = exports.void = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports.null = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports.instanceof = exports.function = exports.enum = exports.effect = void 0;
5
5
  const errors_1 = require("./errors");
6
6
  const errorUtil_1 = require("./helpers/errorUtil");
7
7
  const parseUtil_1 = require("./helpers/parseUtil");
@@ -9,13 +9,22 @@ const util_1 = require("./helpers/util");
9
9
  const ZodError_1 = require("./ZodError");
10
10
  class ParseInputLazyPath {
11
11
  constructor(parent, value, path, key) {
12
+ this._cachedPath = [];
12
13
  this.parent = parent;
13
14
  this.data = value;
14
15
  this._path = path;
15
16
  this._key = key;
16
17
  }
17
18
  get path() {
18
- return this._path.concat(this._key);
19
+ if (!this._cachedPath.length) {
20
+ if (this._key instanceof Array) {
21
+ this._cachedPath.push(...this._path, ...this._key);
22
+ }
23
+ else {
24
+ this._cachedPath.push(...this._path, this._key);
25
+ }
26
+ }
27
+ return this._cachedPath;
19
28
  }
20
29
  }
21
30
  const handleResult = (ctx, result) => {
@@ -26,8 +35,16 @@ const handleResult = (ctx, result) => {
26
35
  if (!ctx.common.issues.length) {
27
36
  throw new Error("Validation failed but no issues detected.");
28
37
  }
29
- const error = new ZodError_1.ZodError(ctx.common.issues);
30
- return { success: false, error };
38
+ return {
39
+ success: false,
40
+ get error() {
41
+ if (this._error)
42
+ return this._error;
43
+ const error = new ZodError_1.ZodError(ctx.common.issues);
44
+ this._error = error;
45
+ return this._error;
46
+ },
47
+ };
31
48
  }
32
49
  };
33
50
  function processCreateParams(params) {
@@ -51,7 +68,6 @@ function processCreateParams(params) {
51
68
  }
52
69
  class ZodType {
53
70
  constructor(def) {
54
- /** Alias of safeParseAsync */
55
71
  this.spa = this.safeParseAsync;
56
72
  this._def = def;
57
73
  this.parse = this.parse.bind(this);
@@ -303,21 +319,12 @@ exports.Schema = ZodType;
303
319
  exports.ZodSchema = ZodType;
304
320
  const cuidRegex = /^c[^\s-]{8,}$/i;
305
321
  const cuid2Regex = /^[a-z][a-z0-9]*$/;
322
+ const ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/;
306
323
  const uuidRegex = /^([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;
307
- // from https://stackoverflow.com/a/46181/1550155
308
- // old version: too slow, didn't support unicode
309
- // 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;
310
- //old email regex
311
- // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
312
- // eslint-disable-next-line
313
- const emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|([^-]([a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}))$/;
314
- // interface IsDateStringOptions extends StringDateOptions {
315
- /**
316
- * Match any configuration
317
- */
318
- // any?: boolean;
319
- // }
320
- // Adapted from https://stackoverflow.com/a/3143231
324
+ const emailRegex = /^(([^<>()[\]\\.,;:\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,})+))$/;
325
+ const emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u;
326
+ const ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;
327
+ const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
321
328
  const datetimeRegex = (args) => {
322
329
  if (args.precision) {
323
330
  if (args.offset) {
@@ -344,6 +351,15 @@ const datetimeRegex = (args) => {
344
351
  }
345
352
  }
346
353
  };
354
+ function isValidIP(ip, version) {
355
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
356
+ return true;
357
+ }
358
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
359
+ return true;
360
+ }
361
+ return false;
362
+ }
347
363
  class ZodString extends ZodType {
348
364
  constructor() {
349
365
  super(...arguments);
@@ -352,15 +368,19 @@ class ZodString extends ZodType {
352
368
  code: ZodError_1.ZodIssueCode.invalid_string,
353
369
  ...errorUtil_1.errorUtil.errToObj(message),
354
370
  });
355
- /**
356
- * @deprecated Use z.string().min(1) instead.
357
- * @see {@link ZodString.min}
358
- */
359
371
  this.nonempty = (message) => this.min(1, errorUtil_1.errorUtil.errToObj(message));
360
372
  this.trim = () => new ZodString({
361
373
  ...this._def,
362
374
  checks: [...this._def.checks, { kind: "trim" }],
363
375
  });
376
+ this.toLowerCase = () => new ZodString({
377
+ ...this._def,
378
+ checks: [...this._def.checks, { kind: "toLowerCase" }],
379
+ });
380
+ this.toUpperCase = () => new ZodString({
381
+ ...this._def,
382
+ checks: [...this._def.checks, { kind: "toUpperCase" }],
383
+ });
364
384
  }
365
385
  _parse(input) {
366
386
  if (this._def.coerce) {
@@ -373,9 +393,7 @@ class ZodString extends ZodType {
373
393
  code: ZodError_1.ZodIssueCode.invalid_type,
374
394
  expected: util_1.ZodParsedType.string,
375
395
  received: ctx.parsedType,
376
- }
377
- //
378
- );
396
+ });
379
397
  return parseUtil_1.INVALID;
380
398
  }
381
399
  const status = new parseUtil_1.ParseStatus();
@@ -448,6 +466,17 @@ class ZodString extends ZodType {
448
466
  status.dirty();
449
467
  }
450
468
  }
469
+ else if (check.kind === "emoji") {
470
+ if (!emojiRegex.test(input.data)) {
471
+ ctx = this._getOrReturnCtx(input, ctx);
472
+ (0, parseUtil_1.addIssueToContext)(ctx, {
473
+ validation: "emoji",
474
+ code: ZodError_1.ZodIssueCode.invalid_string,
475
+ message: check.message,
476
+ });
477
+ status.dirty();
478
+ }
479
+ }
451
480
  else if (check.kind === "uuid") {
452
481
  if (!uuidRegex.test(input.data)) {
453
482
  ctx = this._getOrReturnCtx(input, ctx);
@@ -481,6 +510,17 @@ class ZodString extends ZodType {
481
510
  status.dirty();
482
511
  }
483
512
  }
513
+ else if (check.kind === "ulid") {
514
+ if (!ulidRegex.test(input.data)) {
515
+ ctx = this._getOrReturnCtx(input, ctx);
516
+ (0, parseUtil_1.addIssueToContext)(ctx, {
517
+ validation: "ulid",
518
+ code: ZodError_1.ZodIssueCode.invalid_string,
519
+ message: check.message,
520
+ });
521
+ status.dirty();
522
+ }
523
+ }
484
524
  else if (check.kind === "url") {
485
525
  try {
486
526
  new URL(input.data);
@@ -511,6 +551,23 @@ class ZodString extends ZodType {
511
551
  else if (check.kind === "trim") {
512
552
  input.data = input.data.trim();
513
553
  }
554
+ else if (check.kind === "includes") {
555
+ if (!input.data.includes(check.value, check.position)) {
556
+ ctx = this._getOrReturnCtx(input, ctx);
557
+ (0, parseUtil_1.addIssueToContext)(ctx, {
558
+ code: ZodError_1.ZodIssueCode.invalid_string,
559
+ validation: { includes: check.value, position: check.position },
560
+ message: check.message,
561
+ });
562
+ status.dirty();
563
+ }
564
+ }
565
+ else if (check.kind === "toLowerCase") {
566
+ input.data = input.data.toLowerCase();
567
+ }
568
+ else if (check.kind === "toUpperCase") {
569
+ input.data = input.data.toUpperCase();
570
+ }
514
571
  else if (check.kind === "startsWith") {
515
572
  if (!input.data.startsWith(check.value)) {
516
573
  ctx = this._getOrReturnCtx(input, ctx);
@@ -545,6 +602,17 @@ class ZodString extends ZodType {
545
602
  status.dirty();
546
603
  }
547
604
  }
605
+ else if (check.kind === "ip") {
606
+ if (!isValidIP(input.data, check.version)) {
607
+ ctx = this._getOrReturnCtx(input, ctx);
608
+ (0, parseUtil_1.addIssueToContext)(ctx, {
609
+ validation: "ip",
610
+ code: ZodError_1.ZodIssueCode.invalid_string,
611
+ message: check.message,
612
+ });
613
+ status.dirty();
614
+ }
615
+ }
548
616
  else {
549
617
  util_1.util.assertNever(check);
550
618
  }
@@ -563,6 +631,9 @@ class ZodString extends ZodType {
563
631
  url(message) {
564
632
  return this._addCheck({ kind: "url", ...errorUtil_1.errorUtil.errToObj(message) });
565
633
  }
634
+ emoji(message) {
635
+ return this._addCheck({ kind: "emoji", ...errorUtil_1.errorUtil.errToObj(message) });
636
+ }
566
637
  uuid(message) {
567
638
  return this._addCheck({ kind: "uuid", ...errorUtil_1.errorUtil.errToObj(message) });
568
639
  }
@@ -572,6 +643,12 @@ class ZodString extends ZodType {
572
643
  cuid2(message) {
573
644
  return this._addCheck({ kind: "cuid2", ...errorUtil_1.errorUtil.errToObj(message) });
574
645
  }
646
+ ulid(message) {
647
+ return this._addCheck({ kind: "ulid", ...errorUtil_1.errorUtil.errToObj(message) });
648
+ }
649
+ ip(options) {
650
+ return this._addCheck({ kind: "ip", ...errorUtil_1.errorUtil.errToObj(options) });
651
+ }
575
652
  datetime(options) {
576
653
  var _a;
577
654
  if (typeof options === "string") {
@@ -596,6 +673,14 @@ class ZodString extends ZodType {
596
673
  ...errorUtil_1.errorUtil.errToObj(message),
597
674
  });
598
675
  }
676
+ includes(value, options) {
677
+ return this._addCheck({
678
+ kind: "includes",
679
+ value: value,
680
+ position: options === null || options === void 0 ? void 0 : options.position,
681
+ ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
682
+ });
683
+ }
599
684
  startsWith(value, message) {
600
685
  return this._addCheck({
601
686
  kind: "startsWith",
@@ -640,6 +725,9 @@ class ZodString extends ZodType {
640
725
  get isURL() {
641
726
  return !!this._def.checks.find((ch) => ch.kind === "url");
642
727
  }
728
+ get isEmoji() {
729
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
730
+ }
643
731
  get isUUID() {
644
732
  return !!this._def.checks.find((ch) => ch.kind === "uuid");
645
733
  }
@@ -649,6 +737,12 @@ class ZodString extends ZodType {
649
737
  get isCUID2() {
650
738
  return !!this._def.checks.find((ch) => ch.kind === "cuid2");
651
739
  }
740
+ get isULID() {
741
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
742
+ }
743
+ get isIP() {
744
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
745
+ }
652
746
  get minLength() {
653
747
  let min = null;
654
748
  for (const ch of this._def.checks) {
@@ -680,7 +774,6 @@ ZodString.create = (params) => {
680
774
  ...processCreateParams(params),
681
775
  });
682
776
  };
683
- // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
684
777
  function floatSafeRemainder(val, step) {
685
778
  const valDecCount = (val.toString().split(".")[1] || "").length;
686
779
  const stepDecCount = (step.toString().split(".")[1] || "").length;
@@ -869,6 +962,19 @@ class ZodNumber extends ZodType {
869
962
  message: errorUtil_1.errorUtil.toString(message),
870
963
  });
871
964
  }
965
+ safe(message) {
966
+ return this._addCheck({
967
+ kind: "min",
968
+ inclusive: true,
969
+ value: Number.MIN_SAFE_INTEGER,
970
+ message: errorUtil_1.errorUtil.toString(message),
971
+ })._addCheck({
972
+ kind: "max",
973
+ inclusive: true,
974
+ value: Number.MAX_SAFE_INTEGER,
975
+ message: errorUtil_1.errorUtil.toString(message),
976
+ });
977
+ }
872
978
  get minValue() {
873
979
  let min = null;
874
980
  for (const ch of this._def.checks) {
@@ -923,6 +1029,11 @@ ZodNumber.create = (params) => {
923
1029
  });
924
1030
  };
925
1031
  class ZodBigInt extends ZodType {
1032
+ constructor() {
1033
+ super(...arguments);
1034
+ this.min = this.gte;
1035
+ this.max = this.lte;
1036
+ }
926
1037
  _parse(input) {
927
1038
  if (this._def.coerce) {
928
1039
  input.data = BigInt(input.data);
@@ -937,13 +1048,155 @@ class ZodBigInt extends ZodType {
937
1048
  });
938
1049
  return parseUtil_1.INVALID;
939
1050
  }
940
- return (0, parseUtil_1.OK)(input.data);
1051
+ let ctx = undefined;
1052
+ const status = new parseUtil_1.ParseStatus();
1053
+ for (const check of this._def.checks) {
1054
+ if (check.kind === "min") {
1055
+ const tooSmall = check.inclusive
1056
+ ? input.data < check.value
1057
+ : input.data <= check.value;
1058
+ if (tooSmall) {
1059
+ ctx = this._getOrReturnCtx(input, ctx);
1060
+ (0, parseUtil_1.addIssueToContext)(ctx, {
1061
+ code: ZodError_1.ZodIssueCode.too_small,
1062
+ type: "bigint",
1063
+ minimum: check.value,
1064
+ inclusive: check.inclusive,
1065
+ message: check.message,
1066
+ });
1067
+ status.dirty();
1068
+ }
1069
+ }
1070
+ else if (check.kind === "max") {
1071
+ const tooBig = check.inclusive
1072
+ ? input.data > check.value
1073
+ : input.data >= check.value;
1074
+ if (tooBig) {
1075
+ ctx = this._getOrReturnCtx(input, ctx);
1076
+ (0, parseUtil_1.addIssueToContext)(ctx, {
1077
+ code: ZodError_1.ZodIssueCode.too_big,
1078
+ type: "bigint",
1079
+ maximum: check.value,
1080
+ inclusive: check.inclusive,
1081
+ message: check.message,
1082
+ });
1083
+ status.dirty();
1084
+ }
1085
+ }
1086
+ else if (check.kind === "multipleOf") {
1087
+ if (input.data % check.value !== BigInt(0)) {
1088
+ ctx = this._getOrReturnCtx(input, ctx);
1089
+ (0, parseUtil_1.addIssueToContext)(ctx, {
1090
+ code: ZodError_1.ZodIssueCode.not_multiple_of,
1091
+ multipleOf: check.value,
1092
+ message: check.message,
1093
+ });
1094
+ status.dirty();
1095
+ }
1096
+ }
1097
+ else {
1098
+ util_1.util.assertNever(check);
1099
+ }
1100
+ }
1101
+ return { status: status.value, value: input.data };
1102
+ }
1103
+ gte(value, message) {
1104
+ return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message));
1105
+ }
1106
+ gt(value, message) {
1107
+ return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message));
1108
+ }
1109
+ lte(value, message) {
1110
+ return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message));
1111
+ }
1112
+ lt(value, message) {
1113
+ return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message));
1114
+ }
1115
+ setLimit(kind, value, inclusive, message) {
1116
+ return new ZodBigInt({
1117
+ ...this._def,
1118
+ checks: [
1119
+ ...this._def.checks,
1120
+ {
1121
+ kind,
1122
+ value,
1123
+ inclusive,
1124
+ message: errorUtil_1.errorUtil.toString(message),
1125
+ },
1126
+ ],
1127
+ });
1128
+ }
1129
+ _addCheck(check) {
1130
+ return new ZodBigInt({
1131
+ ...this._def,
1132
+ checks: [...this._def.checks, check],
1133
+ });
1134
+ }
1135
+ positive(message) {
1136
+ return this._addCheck({
1137
+ kind: "min",
1138
+ value: BigInt(0),
1139
+ inclusive: false,
1140
+ message: errorUtil_1.errorUtil.toString(message),
1141
+ });
1142
+ }
1143
+ negative(message) {
1144
+ return this._addCheck({
1145
+ kind: "max",
1146
+ value: BigInt(0),
1147
+ inclusive: false,
1148
+ message: errorUtil_1.errorUtil.toString(message),
1149
+ });
1150
+ }
1151
+ nonpositive(message) {
1152
+ return this._addCheck({
1153
+ kind: "max",
1154
+ value: BigInt(0),
1155
+ inclusive: true,
1156
+ message: errorUtil_1.errorUtil.toString(message),
1157
+ });
1158
+ }
1159
+ nonnegative(message) {
1160
+ return this._addCheck({
1161
+ kind: "min",
1162
+ value: BigInt(0),
1163
+ inclusive: true,
1164
+ message: errorUtil_1.errorUtil.toString(message),
1165
+ });
1166
+ }
1167
+ multipleOf(value, message) {
1168
+ return this._addCheck({
1169
+ kind: "multipleOf",
1170
+ value,
1171
+ message: errorUtil_1.errorUtil.toString(message),
1172
+ });
1173
+ }
1174
+ get minValue() {
1175
+ let min = null;
1176
+ for (const ch of this._def.checks) {
1177
+ if (ch.kind === "min") {
1178
+ if (min === null || ch.value > min)
1179
+ min = ch.value;
1180
+ }
1181
+ }
1182
+ return min;
1183
+ }
1184
+ get maxValue() {
1185
+ let max = null;
1186
+ for (const ch of this._def.checks) {
1187
+ if (ch.kind === "max") {
1188
+ if (max === null || ch.value < max)
1189
+ max = ch.value;
1190
+ }
1191
+ }
1192
+ return max;
941
1193
  }
942
1194
  }
943
1195
  exports.ZodBigInt = ZodBigInt;
944
1196
  ZodBigInt.create = (params) => {
945
1197
  var _a;
946
1198
  return new ZodBigInt({
1199
+ checks: [],
947
1200
  typeName: ZodFirstPartyTypeKind.ZodBigInt,
948
1201
  coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
949
1202
  ...processCreateParams(params),
@@ -1156,7 +1409,6 @@ ZodNull.create = (params) => {
1156
1409
  class ZodAny extends ZodType {
1157
1410
  constructor() {
1158
1411
  super(...arguments);
1159
- // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
1160
1412
  this._any = true;
1161
1413
  }
1162
1414
  _parse(input) {
@@ -1173,7 +1425,6 @@ ZodAny.create = (params) => {
1173
1425
  class ZodUnknown extends ZodType {
1174
1426
  constructor() {
1175
1427
  super(...arguments);
1176
- // required
1177
1428
  this._unknown = true;
1178
1429
  }
1179
1430
  _parse(input) {
@@ -1329,22 +1580,6 @@ ZodArray.create = (schema, params) => {
1329
1580
  ...processCreateParams(params),
1330
1581
  });
1331
1582
  };
1332
- /////////////////////////////////////////
1333
- /////////////////////////////////////////
1334
- ////////// //////////
1335
- ////////// ZodObject //////////
1336
- ////////// //////////
1337
- /////////////////////////////////////////
1338
- /////////////////////////////////////////
1339
- var objectUtil;
1340
- (function (objectUtil) {
1341
- objectUtil.mergeShapes = (first, second) => {
1342
- return {
1343
- ...first,
1344
- ...second, // second overwrites first
1345
- };
1346
- };
1347
- })(objectUtil = exports.objectUtil || (exports.objectUtil = {}));
1348
1583
  function deepPartialify(schema) {
1349
1584
  if (schema instanceof ZodObject) {
1350
1585
  const newShape = {};
@@ -1358,7 +1593,10 @@ function deepPartialify(schema) {
1358
1593
  });
1359
1594
  }
1360
1595
  else if (schema instanceof ZodArray) {
1361
- return ZodArray.create(deepPartialify(schema.element));
1596
+ return new ZodArray({
1597
+ ...schema._def,
1598
+ type: deepPartialify(schema.element),
1599
+ });
1362
1600
  }
1363
1601
  else if (schema instanceof ZodOptional) {
1364
1602
  return ZodOptional.create(deepPartialify(schema.unwrap()));
@@ -1377,47 +1615,7 @@ class ZodObject extends ZodType {
1377
1615
  constructor() {
1378
1616
  super(...arguments);
1379
1617
  this._cached = null;
1380
- /**
1381
- * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
1382
- * If you want to pass through unknown properties, use `.passthrough()` instead.
1383
- */
1384
1618
  this.nonstrict = this.passthrough;
1385
- // extend<
1386
- // Augmentation extends ZodRawShape,
1387
- // NewOutput extends util.flatten<{
1388
- // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
1389
- // ? Augmentation[k]["_output"]
1390
- // : k extends keyof Output
1391
- // ? Output[k]
1392
- // : never;
1393
- // }>,
1394
- // NewInput extends util.flatten<{
1395
- // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
1396
- // ? Augmentation[k]["_input"]
1397
- // : k extends keyof Input
1398
- // ? Input[k]
1399
- // : never;
1400
- // }>
1401
- // >(
1402
- // augmentation: Augmentation
1403
- // ): ZodObject<
1404
- // extendShape<T, Augmentation>,
1405
- // UnknownKeys,
1406
- // Catchall,
1407
- // NewOutput,
1408
- // NewInput
1409
- // > {
1410
- // return new ZodObject({
1411
- // ...this._def,
1412
- // shape: () => ({
1413
- // ...this._def.shape(),
1414
- // ...augmentation,
1415
- // }),
1416
- // }) as any;
1417
- // }
1418
- /**
1419
- * @deprecated Use `.extend` instead
1420
- * */
1421
1619
  this.augment = this.extend;
1422
1620
  }
1423
1621
  _getCached() {
@@ -1485,14 +1683,12 @@ class ZodObject extends ZodType {
1485
1683
  }
1486
1684
  }
1487
1685
  else {
1488
- // run catchall validation
1489
1686
  const catchall = this._def.catchall;
1490
1687
  for (const key of extraKeys) {
1491
1688
  const value = ctx.data[key];
1492
1689
  pairs.push({
1493
1690
  key: { status: "valid", value: key },
1494
- value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
1495
- ),
1691
+ value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
1496
1692
  alwaysSet: key in ctx.data,
1497
1693
  });
1498
1694
  }
@@ -1556,23 +1752,6 @@ class ZodObject extends ZodType {
1556
1752
  unknownKeys: "passthrough",
1557
1753
  });
1558
1754
  }
1559
- // const AugmentFactory =
1560
- // <Def extends ZodObjectDef>(def: Def) =>
1561
- // <Augmentation extends ZodRawShape>(
1562
- // augmentation: Augmentation
1563
- // ): ZodObject<
1564
- // extendShape<ReturnType<Def["shape"]>, Augmentation>,
1565
- // Def["unknownKeys"],
1566
- // Def["catchall"]
1567
- // > => {
1568
- // return new ZodObject({
1569
- // ...def,
1570
- // shape: () => ({
1571
- // ...def.shape(),
1572
- // ...augmentation,
1573
- // }),
1574
- // }) as any;
1575
- // };
1576
1755
  extend(augmentation) {
1577
1756
  return new ZodObject({
1578
1757
  ...this._def,
@@ -1582,79 +1761,21 @@ class ZodObject extends ZodType {
1582
1761
  }),
1583
1762
  });
1584
1763
  }
1585
- /**
1586
- * Prior to zod@1.0.12 there was a bug in the
1587
- * inferred type of merged objects. Please
1588
- * upgrade if you are experiencing issues.
1589
- */
1590
1764
  merge(merging) {
1591
1765
  const merged = new ZodObject({
1592
1766
  unknownKeys: merging._def.unknownKeys,
1593
1767
  catchall: merging._def.catchall,
1594
- shape: () => objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
1768
+ shape: () => ({
1769
+ ...this._def.shape(),
1770
+ ...merging._def.shape(),
1771
+ }),
1595
1772
  typeName: ZodFirstPartyTypeKind.ZodObject,
1596
1773
  });
1597
1774
  return merged;
1598
1775
  }
1599
- // merge<
1600
- // Incoming extends AnyZodObject,
1601
- // Augmentation extends Incoming["shape"],
1602
- // NewOutput extends {
1603
- // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
1604
- // ? Augmentation[k]["_output"]
1605
- // : k extends keyof Output
1606
- // ? Output[k]
1607
- // : never;
1608
- // },
1609
- // NewInput extends {
1610
- // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
1611
- // ? Augmentation[k]["_input"]
1612
- // : k extends keyof Input
1613
- // ? Input[k]
1614
- // : never;
1615
- // }
1616
- // >(
1617
- // merging: Incoming
1618
- // ): ZodObject<
1619
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
1620
- // Incoming["_def"]["unknownKeys"],
1621
- // Incoming["_def"]["catchall"],
1622
- // NewOutput,
1623
- // NewInput
1624
- // > {
1625
- // const merged: any = new ZodObject({
1626
- // unknownKeys: merging._def.unknownKeys,
1627
- // catchall: merging._def.catchall,
1628
- // shape: () =>
1629
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
1630
- // typeName: ZodFirstPartyTypeKind.ZodObject,
1631
- // }) as any;
1632
- // return merged;
1633
- // }
1634
1776
  setKey(key, schema) {
1635
1777
  return this.augment({ [key]: schema });
1636
1778
  }
1637
- // merge<Incoming extends AnyZodObject>(
1638
- // merging: Incoming
1639
- // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
1640
- // ZodObject<
1641
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
1642
- // Incoming["_def"]["unknownKeys"],
1643
- // Incoming["_def"]["catchall"]
1644
- // > {
1645
- // // const mergedShape = objectUtil.mergeShapes(
1646
- // // this._def.shape(),
1647
- // // merging._def.shape()
1648
- // // );
1649
- // const merged: any = new ZodObject({
1650
- // unknownKeys: merging._def.unknownKeys,
1651
- // catchall: merging._def.catchall,
1652
- // shape: () =>
1653
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
1654
- // typeName: ZodFirstPartyTypeKind.ZodObject,
1655
- // }) as any;
1656
- // return merged;
1657
- // }
1658
1779
  catchall(index) {
1659
1780
  return new ZodObject({
1660
1781
  ...this._def,
@@ -1761,7 +1882,6 @@ class ZodUnion extends ZodType {
1761
1882
  const { ctx } = this._processInputParams(input);
1762
1883
  const options = this._def.options;
1763
1884
  function handleResults(results) {
1764
- // return first issue-free validation if it exists
1765
1885
  for (const result of results) {
1766
1886
  if (result.result.status === "valid") {
1767
1887
  return result.result;
@@ -1769,12 +1889,10 @@ class ZodUnion extends ZodType {
1769
1889
  }
1770
1890
  for (const result of results) {
1771
1891
  if (result.result.status === "dirty") {
1772
- // add issues from dirty option
1773
1892
  ctx.common.issues.push(...result.ctx.common.issues);
1774
1893
  return result.result;
1775
1894
  }
1776
1895
  }
1777
- // return invalid
1778
1896
  const unionErrors = results.map((result) => new ZodError_1.ZodError(result.ctx.common.issues));
1779
1897
  (0, parseUtil_1.addIssueToContext)(ctx, {
1780
1898
  code: ZodError_1.ZodIssueCode.invalid_union,
@@ -1853,13 +1971,6 @@ ZodUnion.create = (types, params) => {
1853
1971
  ...processCreateParams(params),
1854
1972
  });
1855
1973
  };
1856
- /////////////////////////////////////////////////////
1857
- /////////////////////////////////////////////////////
1858
- ////////// //////////
1859
- ////////// ZodDiscriminatedUnion //////////
1860
- ////////// //////////
1861
- /////////////////////////////////////////////////////
1862
- /////////////////////////////////////////////////////
1863
1974
  const getDiscriminator = (type) => {
1864
1975
  if (type instanceof ZodLazy) {
1865
1976
  return getDiscriminator(type.schema);
@@ -1874,7 +1985,6 @@ const getDiscriminator = (type) => {
1874
1985
  return type.options;
1875
1986
  }
1876
1987
  else if (type instanceof ZodNativeEnum) {
1877
- // eslint-disable-next-line ban/ban
1878
1988
  return Object.keys(type.enum);
1879
1989
  }
1880
1990
  else if (type instanceof ZodDefault) {
@@ -1936,18 +2046,8 @@ class ZodDiscriminatedUnion extends ZodType {
1936
2046
  get optionsMap() {
1937
2047
  return this._def.optionsMap;
1938
2048
  }
1939
- /**
1940
- * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
1941
- * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
1942
- * have a different value for each object in the union.
1943
- * @param discriminator the name of the discriminator property
1944
- * @param types an array of object schemas
1945
- * @param params
1946
- */
1947
2049
  static create(discriminator, options, params) {
1948
- // Get all the valid discriminator values
1949
2050
  const optionsMap = new Map();
1950
- // try {
1951
2051
  for (const type of options) {
1952
2052
  const discriminatorValues = getDiscriminator(type.shape[discriminator]);
1953
2053
  if (!discriminatorValues) {
@@ -2110,7 +2210,7 @@ class ZodTuple extends ZodType {
2110
2210
  return null;
2111
2211
  return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
2112
2212
  })
2113
- .filter((x) => !!x); // filter nulls
2213
+ .filter((x) => !!x);
2114
2214
  if (ctx.common.async) {
2115
2215
  return Promise.all(items).then((results) => {
2116
2216
  return parseUtil_1.ParseStatus.mergeArray(status, results);
@@ -2691,9 +2791,7 @@ class ZodEffects extends ZodType {
2691
2791
  };
2692
2792
  checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
2693
2793
  if (effect.type === "refinement") {
2694
- const executeRefinement = (acc
2695
- // effect: RefinementEffect<any>
2696
- ) => {
2794
+ const executeRefinement = (acc) => {
2697
2795
  const result = effect.refinement(acc, checkCtx);
2698
2796
  if (ctx.common.async) {
2699
2797
  return Promise.resolve(result);
@@ -2713,7 +2811,6 @@ class ZodEffects extends ZodType {
2713
2811
  return parseUtil_1.INVALID;
2714
2812
  if (inner.status === "dirty")
2715
2813
  status.dirty();
2716
- // return value is ignored
2717
2814
  executeRefinement(inner.value);
2718
2815
  return { status: status.value, value: inner.value };
2719
2816
  }
@@ -2738,10 +2835,6 @@ class ZodEffects extends ZodType {
2738
2835
  path: ctx.path,
2739
2836
  parent: ctx,
2740
2837
  });
2741
- // if (base.status === "aborted") return INVALID;
2742
- // if (base.status === "dirty") {
2743
- // return { status: "dirty", value: base.value };
2744
- // }
2745
2838
  if (!(0, parseUtil_1.isValid)(base))
2746
2839
  return base;
2747
2840
  const result = effect.transform(base.value, checkCtx);
@@ -2756,10 +2849,6 @@ class ZodEffects extends ZodType {
2756
2849
  .then((base) => {
2757
2850
  if (!(0, parseUtil_1.isValid)(base))
2758
2851
  return base;
2759
- // if (base.status === "aborted") return INVALID;
2760
- // if (base.status === "dirty") {
2761
- // return { status: "dirty", value: base.value };
2762
- // }
2763
2852
  return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
2764
2853
  });
2765
2854
  }
@@ -2856,29 +2945,46 @@ ZodDefault.create = (type, params) => {
2856
2945
  class ZodCatch extends ZodType {
2857
2946
  _parse(input) {
2858
2947
  const { ctx } = this._processInputParams(input);
2948
+ const newCtx = {
2949
+ ...ctx,
2950
+ common: {
2951
+ ...ctx.common,
2952
+ issues: [],
2953
+ },
2954
+ };
2859
2955
  const result = this._def.innerType._parse({
2860
- data: ctx.data,
2861
- path: ctx.path,
2956
+ data: newCtx.data,
2957
+ path: newCtx.path,
2862
2958
  parent: {
2863
- ...ctx,
2864
- common: {
2865
- ...ctx.common,
2866
- issues: [], // don't collect issues from inner type
2867
- },
2959
+ ...newCtx,
2868
2960
  },
2869
2961
  });
2870
2962
  if ((0, parseUtil_1.isAsync)(result)) {
2871
2963
  return result.then((result) => {
2872
2964
  return {
2873
2965
  status: "valid",
2874
- value: result.status === "valid" ? result.value : this._def.catchValue(),
2966
+ value: result.status === "valid"
2967
+ ? result.value
2968
+ : this._def.catchValue({
2969
+ get error() {
2970
+ return new ZodError_1.ZodError(newCtx.common.issues);
2971
+ },
2972
+ input: newCtx.data,
2973
+ }),
2875
2974
  };
2876
2975
  });
2877
2976
  }
2878
2977
  else {
2879
2978
  return {
2880
2979
  status: "valid",
2881
- value: result.status === "valid" ? result.value : this._def.catchValue(),
2980
+ value: result.status === "valid"
2981
+ ? result.value
2982
+ : this._def.catchValue({
2983
+ get error() {
2984
+ return new ZodError_1.ZodError(newCtx.common.issues);
2985
+ },
2986
+ input: newCtx.data,
2987
+ }),
2882
2988
  };
2883
2989
  }
2884
2990
  }
@@ -2995,10 +3101,16 @@ exports.ZodPipeline = ZodPipeline;
2995
3101
  const custom = (check, params = {}, fatal) => {
2996
3102
  if (check)
2997
3103
  return ZodAny.create().superRefine((data, ctx) => {
3104
+ var _a, _b;
2998
3105
  if (!check(data)) {
2999
- const p = typeof params === "function" ? params(data) : params;
3106
+ const p = typeof params === "function"
3107
+ ? params(data)
3108
+ : typeof params === "string"
3109
+ ? { message: params }
3110
+ : params;
3111
+ const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
3000
3112
  const p2 = typeof p === "string" ? { message: p } : p;
3001
- ctx.addIssue({ code: "custom", ...p2, fatal });
3113
+ ctx.addIssue({ code: "custom", ...p2, fatal: _fatal });
3002
3114
  }
3003
3115
  });
3004
3116
  return ZodAny.create();
@@ -3045,16 +3157,12 @@ var ZodFirstPartyTypeKind;
3045
3157
  ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
3046
3158
  ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
3047
3159
  })(ZodFirstPartyTypeKind = exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {}));
3048
- // new approach that works for abstract classes
3049
- // but requires TS 4.4+
3050
3160
  class Class {
3051
3161
  constructor(..._) { }
3052
3162
  }
3053
- const instanceOfType = (
3054
- // const instanceOfType = <T extends new (...args: any[]) => any>(
3055
- cls, params = {
3163
+ const instanceOfType = (cls, params = {
3056
3164
  message: `Input not instance of ${cls.name}`,
3057
- }) => (0, exports.custom)((data) => data instanceof cls, params, true);
3165
+ }) => (0, exports.custom)((data) => data instanceof cls, params);
3058
3166
  exports.instanceof = instanceOfType;
3059
3167
  const stringType = ZodString.create;
3060
3168
  exports.string = stringType;