zod 3.17.5 → 3.17.8

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/README.md CHANGED
@@ -313,6 +313,7 @@ There are a growing number of tools that are built atop or support Zod natively!
313
313
  - [`prisma-zod-generator`](https://github.com/omar-dulaimi/prisma-zod-generator): Emit Zod schemas from your Prisma schema.
314
314
  - [`prisma-trpc-generator`](https://github.com/omar-dulaimi/prisma-trpc-generator): Emit fully implemented tRPC routers and their validation schemas using Zod.
315
315
  - [`nestjs-graphql-zod`](https://github.com/incetarik/nestjs-graphql-zod): Generates NestJS GraphQL model classes from Zod schemas dynamically and provides GraphQL method decorators working with Zod schemas.
316
+ - [`zod-xlsx`](https://github.com/sidwebworks/zod-xlsx): A xlsx based resource validator using Zod schemas.
316
317
  - [`remix-domains`](https://github.com/SeasonedSoftware/remix-domains/): Improves end-to-end type safety in [Remix](https://remix.run/) by leveraging Zod to parse the framework's inputs such as FormData, URLSearchParams, etc.
317
318
 
318
319
  #### Form integrations
@@ -351,7 +352,7 @@ pnpm add zod # pnpm
351
352
 
352
353
  ### Deno
353
354
 
354
- Unlike Node, Deno relies on direct URL imports instead of a package manager like npm. Zod is available on [deno.land/x](deno.land/x). The latest version can be imported like so:
355
+ Unlike Node, Deno relies on direct URL imports instead of a package manager like NPM. Zod is available on [deno.land/x](https://deno.land/x). The latest version can be imported like so:
355
356
 
356
357
  ```ts
357
358
  import { z } from "https://deno.land/x/zod/mod.ts";
@@ -360,7 +361,7 @@ import { z } from "https://deno.land/x/zod/mod.ts";
360
361
  You can also specify a particular version:
361
362
 
362
363
  ```ts
363
- import { z } from from "https://deno.land/x/zod@v3.16.1/mod.ts"
364
+ import { z } from "https://deno.land/x/zod@v3.16.1/mod.ts";
364
365
  ```
365
366
 
366
367
  > The rest of this README assumes you are using npm and importing directly from the `"zod"` package.
@@ -438,7 +439,7 @@ const tru = z.literal(true);
438
439
  tuna.value; // "tuna"
439
440
  ```
440
441
 
441
- > Currently there is no support for Date or bigint literals in Zod. If you have a use case for this feature, please file an issue.
442
+ > Currently there is no support for Date literals in Zod. If you have a use case for this feature, please file an issue.
442
443
 
443
444
  ## Strings
444
445
 
@@ -549,14 +550,32 @@ const isActive = z.boolean({
549
550
 
550
551
  ## Dates
551
552
 
552
- z.date() accepts a date, not a date string
553
+ Use z.date() to validate `Date` instances.
553
554
 
554
555
  ```ts
555
556
  z.date().safeParse(new Date()); // success: true
556
557
  z.date().safeParse("2022-01-12T00:00:00.000Z"); // success: false
557
558
  ```
558
559
 
559
- To allow for dates or date strings, you can use preprocess
560
+ You can customize certain error messages when creating a boolean schema.
561
+
562
+ ```ts
563
+ const myDateSchema = z.date({
564
+ required_error: "Please select a date and time",
565
+ invalid_type_error: "That's not a date!",
566
+ });
567
+ ```
568
+
569
+ Zod provides a handful of date-specific validations.
570
+
571
+ ```ts
572
+ z.date().min(new Date("1900-01-01"), { message: "Too old" });
573
+ z.date().max(new Date(), { message: "Too young!" });
574
+ ```
575
+
576
+ **Supporting date strings**
577
+
578
+ To write a schema that accepts either a `Date` or a date string, use (`z.preprocess`)[#preprocess].
560
579
 
561
580
  ```ts
562
581
  const dateSchema = z.preprocess((arg) => {
package/lib/ZodError.d.ts CHANGED
@@ -81,13 +81,13 @@ export interface ZodTooSmallIssue extends ZodIssueBase {
81
81
  code: typeof ZodIssueCode.too_small;
82
82
  minimum: number;
83
83
  inclusive: boolean;
84
- type: "array" | "string" | "number" | "set";
84
+ type: "array" | "string" | "number" | "set" | "date";
85
85
  }
86
86
  export interface ZodTooBigIssue extends ZodIssueBase {
87
87
  code: typeof ZodIssueCode.too_big;
88
88
  maximum: number;
89
89
  inclusive: boolean;
90
- type: "array" | "string" | "number" | "set";
90
+ type: "array" | "string" | "number" | "set" | "date";
91
91
  }
92
92
  export interface ZodInvalidIntersectionTypesIssue extends ZodIssueBase {
93
93
  code: typeof ZodIssueCode.invalid_intersection_types;
@@ -150,8 +150,8 @@ export declare type ZodErrorMap = typeof defaultErrorMap;
150
150
  export declare const defaultErrorMap: (issue: ZodIssueOptionalMessage, _ctx: ErrorMapCtx) => {
151
151
  message: string;
152
152
  };
153
- export declare let overrideErrorMap: (issue: ZodIssueOptionalMessage, _ctx: ErrorMapCtx) => {
153
+ export declare function setErrorMap(map: ZodErrorMap): void;
154
+ export declare function getErrorMap(): (issue: ZodIssueOptionalMessage, _ctx: ErrorMapCtx) => {
154
155
  message: string;
155
156
  };
156
- export declare const setErrorMap: (map: ZodErrorMap) => void;
157
157
  export {};
package/lib/ZodError.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.setErrorMap = exports.overrideErrorMap = exports.defaultErrorMap = exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0;
3
+ exports.getErrorMap = exports.setErrorMap = exports.defaultErrorMap = exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0;
4
+ const parseUtil_1 = require("./helpers/parseUtil");
4
5
  const util_1 = require("./helpers/util");
5
6
  exports.ZodIssueCode = util_1.util.arrayToEnum([
6
7
  "invalid_type",
@@ -101,7 +102,7 @@ class ZodError extends Error {
101
102
  return this.message;
102
103
  }
103
104
  get message() {
104
- return JSON.stringify(this.issues, null, 2);
105
+ return JSON.stringify(this.issues, parseUtil_1.jsonStringifyReplacer, 2);
105
106
  }
106
107
  get isEmpty() {
107
108
  return this.issues.length === 0;
@@ -141,7 +142,7 @@ const defaultErrorMap = (issue, _ctx) => {
141
142
  }
142
143
  break;
143
144
  case exports.ZodIssueCode.invalid_literal:
144
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected)}`;
145
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, parseUtil_1.jsonStringifyReplacer)}`;
145
146
  break;
146
147
  case exports.ZodIssueCode.unrecognized_keys:
147
148
  message = `Unrecognized key(s) in object: ${util_1.util.joinValues(issue.keys, ", ")}`;
@@ -190,6 +191,8 @@ const defaultErrorMap = (issue, _ctx) => {
190
191
  message = `String must contain ${issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
191
192
  else if (issue.type === "number")
192
193
  message = `Number must be greater than ${issue.inclusive ? `or equal to ` : ``}${issue.minimum}`;
194
+ else if (issue.type === "date")
195
+ message = `Date must be greater than ${issue.inclusive ? `or equal to ` : ``}${new Date(issue.minimum)}`;
193
196
  else
194
197
  message = "Invalid input";
195
198
  break;
@@ -200,6 +203,8 @@ const defaultErrorMap = (issue, _ctx) => {
200
203
  message = `String must contain ${issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
201
204
  else if (issue.type === "number")
202
205
  message = `Number must be less than ${issue.inclusive ? `or equal to ` : ``}${issue.maximum}`;
206
+ else if (issue.type === "date")
207
+ message = `Date must be smaller than ${issue.inclusive ? `or equal to ` : ``}${new Date(issue.maximum)}`;
203
208
  else
204
209
  message = "Invalid input";
205
210
  break;
@@ -219,8 +224,12 @@ const defaultErrorMap = (issue, _ctx) => {
219
224
  return { message };
220
225
  };
221
226
  exports.defaultErrorMap = defaultErrorMap;
222
- exports.overrideErrorMap = exports.defaultErrorMap;
223
- const setErrorMap = (map) => {
224
- exports.overrideErrorMap = map;
225
- };
227
+ let overrideErrorMap = exports.defaultErrorMap;
228
+ function setErrorMap(map) {
229
+ overrideErrorMap = map;
230
+ }
226
231
  exports.setErrorMap = setErrorMap;
232
+ function getErrorMap() {
233
+ return overrideErrorMap;
234
+ }
235
+ exports.getErrorMap = getErrorMap;
@@ -76,3 +76,4 @@ export declare const isAborted: (x: ParseReturnType<any>) => x is INVALID;
76
76
  export declare const isDirty: <T>(x: ParseReturnType<T>) => x is OK<T> | DIRTY<T>;
77
77
  export declare const isValid: <T>(x: ParseReturnType<T>) => x is OK<T> | DIRTY<T>;
78
78
  export declare const isAsync: <T>(x: ParseReturnType<T>) => x is AsyncParseReturnType<T>;
79
+ export declare const jsonStringifyReplacer: (_: string, value: any) => any;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.addIssueToContext = exports.EMPTY_PATH = exports.makeIssue = void 0;
3
+ exports.jsonStringifyReplacer = exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.addIssueToContext = exports.EMPTY_PATH = exports.makeIssue = void 0;
4
4
  const ZodError_1 = require("../ZodError");
5
5
  const makeIssue = (params) => {
6
6
  const { data, path, errorMaps, issueData } = params;
@@ -33,7 +33,7 @@ function addIssueToContext(ctx, issueData) {
33
33
  errorMaps: [
34
34
  ctx.common.contextualErrorMap,
35
35
  ctx.schemaErrorMap,
36
- ZodError_1.overrideErrorMap,
36
+ ZodError_1.getErrorMap(),
37
37
  ZodError_1.defaultErrorMap,
38
38
  ].filter((x) => !!x),
39
39
  });
@@ -108,3 +108,10 @@ const isValid = (x) => x.status === "valid";
108
108
  exports.isValid = isValid;
109
109
  const isAsync = (x) => typeof Promise !== undefined && x instanceof Promise;
110
110
  exports.isAsync = isAsync;
111
+ const jsonStringifyReplacer = (_, value) => {
112
+ if (typeof value === "bigint") {
113
+ return value.toString();
114
+ }
115
+ return value;
116
+ };
117
+ exports.jsonStringifyReplacer = jsonStringifyReplacer;
@@ -1,5 +1,6 @@
1
1
  export declare namespace util {
2
2
  type AssertEqual<T, Expected> = [T] extends [Expected] ? [Expected] extends [T] ? true : false : false;
3
+ function assertEqual<A, B>(_cond: AssertEqual<A, B>): void;
3
4
  function assertNever(_x: never): never;
4
5
  type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
5
6
  type OmitKeys<T, K extends string> = Pick<T, Exclude<keyof T, K>>;
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getParsedType = exports.ZodParsedType = exports.util = void 0;
4
4
  var util;
5
5
  (function (util) {
6
+ function assertEqual(_cond) { }
7
+ util.assertEqual = assertEqual;
6
8
  function assertNever(_x) {
7
9
  throw new Error();
8
10
  }
package/lib/index.mjs CHANGED
@@ -1,5 +1,7 @@
1
1
  var util;
2
2
  (function (util) {
3
+ function assertEqual(_cond) { }
4
+ util.assertEqual = assertEqual;
3
5
  function assertNever(_x) {
4
6
  throw new Error();
5
7
  }
@@ -215,7 +217,7 @@ class ZodError extends Error {
215
217
  return this.message;
216
218
  }
217
219
  get message() {
218
- return JSON.stringify(this.issues, null, 2);
220
+ return JSON.stringify(this.issues, jsonStringifyReplacer, 2);
219
221
  }
220
222
  get isEmpty() {
221
223
  return this.issues.length === 0;
@@ -254,7 +256,7 @@ const defaultErrorMap = (issue, _ctx) => {
254
256
  }
255
257
  break;
256
258
  case ZodIssueCode.invalid_literal:
257
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected)}`;
259
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, jsonStringifyReplacer)}`;
258
260
  break;
259
261
  case ZodIssueCode.unrecognized_keys:
260
262
  message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
@@ -303,6 +305,8 @@ const defaultErrorMap = (issue, _ctx) => {
303
305
  message = `String must contain ${issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
304
306
  else if (issue.type === "number")
305
307
  message = `Number must be greater than ${issue.inclusive ? `or equal to ` : ``}${issue.minimum}`;
308
+ else if (issue.type === "date")
309
+ message = `Date must be greater than ${issue.inclusive ? `or equal to ` : ``}${new Date(issue.minimum)}`;
306
310
  else
307
311
  message = "Invalid input";
308
312
  break;
@@ -313,6 +317,8 @@ const defaultErrorMap = (issue, _ctx) => {
313
317
  message = `String must contain ${issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
314
318
  else if (issue.type === "number")
315
319
  message = `Number must be less than ${issue.inclusive ? `or equal to ` : ``}${issue.maximum}`;
320
+ else if (issue.type === "date")
321
+ message = `Date must be smaller than ${issue.inclusive ? `or equal to ` : ``}${new Date(issue.maximum)}`;
316
322
  else
317
323
  message = "Invalid input";
318
324
  break;
@@ -332,9 +338,12 @@ const defaultErrorMap = (issue, _ctx) => {
332
338
  return { message };
333
339
  };
334
340
  let overrideErrorMap = defaultErrorMap;
335
- const setErrorMap = (map) => {
341
+ function setErrorMap(map) {
336
342
  overrideErrorMap = map;
337
- };
343
+ }
344
+ function getErrorMap() {
345
+ return overrideErrorMap;
346
+ }
338
347
 
339
348
  const makeIssue = (params) => {
340
349
  const { data, path, errorMaps, issueData } = params;
@@ -366,7 +375,7 @@ function addIssueToContext(ctx, issueData) {
366
375
  errorMaps: [
367
376
  ctx.common.contextualErrorMap,
368
377
  ctx.schemaErrorMap,
369
- overrideErrorMap,
378
+ getErrorMap(),
370
379
  defaultErrorMap,
371
380
  ].filter((x) => !!x),
372
381
  });
@@ -433,6 +442,12 @@ const isAborted = (x) => x.status === "aborted";
433
442
  const isDirty = (x) => x.status === "dirty";
434
443
  const isValid = (x) => x.status === "valid";
435
444
  const isAsync = (x) => typeof Promise !== undefined && x instanceof Promise;
445
+ const jsonStringifyReplacer = (_, value) => {
446
+ if (typeof value === "bigint") {
447
+ return value.toString();
448
+ }
449
+ return value;
450
+ };
436
451
 
437
452
  var errorUtil;
438
453
  (function (errorUtil) {
@@ -1220,14 +1235,88 @@ class ZodDate extends ZodType {
1220
1235
  });
1221
1236
  return INVALID;
1222
1237
  }
1238
+ const status = new ParseStatus();
1239
+ let ctx = undefined;
1240
+ for (const check of this._def.checks) {
1241
+ if (check.kind === "min") {
1242
+ if (input.data.getTime() < check.value) {
1243
+ ctx = this._getOrReturnCtx(input, ctx);
1244
+ addIssueToContext(ctx, {
1245
+ code: ZodIssueCode.too_small,
1246
+ message: check.message,
1247
+ inclusive: true,
1248
+ minimum: check.value,
1249
+ type: "date",
1250
+ });
1251
+ status.dirty();
1252
+ }
1253
+ }
1254
+ else if (check.kind === "max") {
1255
+ if (input.data.getTime() > check.value) {
1256
+ ctx = this._getOrReturnCtx(input, ctx);
1257
+ addIssueToContext(ctx, {
1258
+ code: ZodIssueCode.too_big,
1259
+ message: check.message,
1260
+ inclusive: true,
1261
+ maximum: check.value,
1262
+ type: "date",
1263
+ });
1264
+ status.dirty();
1265
+ }
1266
+ }
1267
+ else {
1268
+ util.assertNever(check);
1269
+ }
1270
+ }
1223
1271
  return {
1224
- status: "valid",
1272
+ status: status.value,
1225
1273
  value: new Date(input.data.getTime()),
1226
1274
  };
1227
1275
  }
1276
+ _addCheck(check) {
1277
+ return new ZodDate({
1278
+ ...this._def,
1279
+ checks: [...this._def.checks, check],
1280
+ });
1281
+ }
1282
+ min(minDate, message) {
1283
+ return this._addCheck({
1284
+ kind: "min",
1285
+ value: minDate.getTime(),
1286
+ message: errorUtil.toString(message),
1287
+ });
1288
+ }
1289
+ max(maxDate, message) {
1290
+ return this._addCheck({
1291
+ kind: "max",
1292
+ value: maxDate.getTime(),
1293
+ message: errorUtil.toString(message),
1294
+ });
1295
+ }
1296
+ get minDate() {
1297
+ let min = null;
1298
+ for (const ch of this._def.checks) {
1299
+ if (ch.kind === "min") {
1300
+ if (min === null || ch.value > min)
1301
+ min = ch.value;
1302
+ }
1303
+ }
1304
+ return min != null ? new Date(min) : null;
1305
+ }
1306
+ get maxDate() {
1307
+ let max = null;
1308
+ for (const ch of this._def.checks) {
1309
+ if (ch.kind === "max") {
1310
+ if (max === null || ch.value < max)
1311
+ max = ch.value;
1312
+ }
1313
+ }
1314
+ return max != null ? new Date(max) : null;
1315
+ }
1228
1316
  }
1229
1317
  ZodDate.create = (params) => {
1230
1318
  return new ZodDate({
1319
+ checks: [],
1231
1320
  typeName: ZodFirstPartyTypeKind.ZodDate,
1232
1321
  ...processCreateParams(params),
1233
1322
  });
@@ -2303,7 +2392,7 @@ class ZodFunction extends ZodType {
2303
2392
  errorMaps: [
2304
2393
  ctx.common.contextualErrorMap,
2305
2394
  ctx.schemaErrorMap,
2306
- overrideErrorMap,
2395
+ getErrorMap(),
2307
2396
  defaultErrorMap,
2308
2397
  ].filter((x) => !!x),
2309
2398
  issueData: {
@@ -2319,7 +2408,7 @@ class ZodFunction extends ZodType {
2319
2408
  errorMaps: [
2320
2409
  ctx.common.contextualErrorMap,
2321
2410
  ctx.schemaErrorMap,
2322
- overrideErrorMap,
2411
+ getErrorMap(),
2323
2412
  defaultErrorMap,
2324
2413
  ].filter((x) => !!x),
2325
2414
  issueData: {
@@ -2883,6 +2972,7 @@ var mod = /*#__PURE__*/Object.freeze({
2883
2972
  isDirty: isDirty,
2884
2973
  isValid: isValid,
2885
2974
  isAsync: isAsync,
2975
+ jsonStringifyReplacer: jsonStringifyReplacer,
2886
2976
  ZodType: ZodType,
2887
2977
  ZodString: ZodString,
2888
2978
  ZodNumber: ZodNumber,
@@ -2963,8 +3053,8 @@ var mod = /*#__PURE__*/Object.freeze({
2963
3053
  quotelessJson: quotelessJson,
2964
3054
  ZodError: ZodError,
2965
3055
  defaultErrorMap: defaultErrorMap,
2966
- get overrideErrorMap () { return overrideErrorMap; },
2967
- setErrorMap: setErrorMap
3056
+ setErrorMap: setErrorMap,
3057
+ getErrorMap: getErrorMap
2968
3058
  });
2969
3059
 
2970
- export { DIRTY, EMPTY_PATH, INVALID, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodError, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodIssueCode, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPromise, ZodRecord, ZodType as ZodSchema, ZodSet, ZodString, ZodEffects as ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, custom, dateType as date, mod as default, defaultErrorMap, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, getParsedType, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, overrideErrorMap, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setType as set, setErrorMap, strictObjectType as strictObject, stringType as string, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, mod as z };
3060
+ export { DIRTY, EMPTY_PATH, INVALID, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodError, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodIssueCode, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPromise, ZodRecord, ZodType as ZodSchema, ZodSet, ZodString, ZodEffects as ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, custom, dateType as date, mod as default, defaultErrorMap, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, getErrorMap, getParsedType, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, jsonStringifyReplacer, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setType as set, setErrorMap, strictObjectType as strictObject, stringType as string, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, mod as z };
package/lib/index.umd.js CHANGED
@@ -6,6 +6,8 @@
6
6
 
7
7
  var util;
8
8
  (function (util) {
9
+ function assertEqual(_cond) { }
10
+ util.assertEqual = assertEqual;
9
11
  function assertNever(_x) {
10
12
  throw new Error();
11
13
  }
@@ -221,7 +223,7 @@
221
223
  return this.message;
222
224
  }
223
225
  get message() {
224
- return JSON.stringify(this.issues, null, 2);
226
+ return JSON.stringify(this.issues, jsonStringifyReplacer, 2);
225
227
  }
226
228
  get isEmpty() {
227
229
  return this.issues.length === 0;
@@ -260,7 +262,7 @@
260
262
  }
261
263
  break;
262
264
  case ZodIssueCode.invalid_literal:
263
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected)}`;
265
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, jsonStringifyReplacer)}`;
264
266
  break;
265
267
  case ZodIssueCode.unrecognized_keys:
266
268
  message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
@@ -309,6 +311,8 @@
309
311
  message = `String must contain ${issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
310
312
  else if (issue.type === "number")
311
313
  message = `Number must be greater than ${issue.inclusive ? `or equal to ` : ``}${issue.minimum}`;
314
+ else if (issue.type === "date")
315
+ message = `Date must be greater than ${issue.inclusive ? `or equal to ` : ``}${new Date(issue.minimum)}`;
312
316
  else
313
317
  message = "Invalid input";
314
318
  break;
@@ -319,6 +323,8 @@
319
323
  message = `String must contain ${issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
320
324
  else if (issue.type === "number")
321
325
  message = `Number must be less than ${issue.inclusive ? `or equal to ` : ``}${issue.maximum}`;
326
+ else if (issue.type === "date")
327
+ message = `Date must be smaller than ${issue.inclusive ? `or equal to ` : ``}${new Date(issue.maximum)}`;
322
328
  else
323
329
  message = "Invalid input";
324
330
  break;
@@ -337,10 +343,13 @@
337
343
  }
338
344
  return { message };
339
345
  };
340
- exports.overrideErrorMap = defaultErrorMap;
341
- const setErrorMap = (map) => {
342
- exports.overrideErrorMap = map;
343
- };
346
+ let overrideErrorMap = defaultErrorMap;
347
+ function setErrorMap(map) {
348
+ overrideErrorMap = map;
349
+ }
350
+ function getErrorMap() {
351
+ return overrideErrorMap;
352
+ }
344
353
 
345
354
  const makeIssue = (params) => {
346
355
  const { data, path, errorMaps, issueData } = params;
@@ -372,7 +381,7 @@
372
381
  errorMaps: [
373
382
  ctx.common.contextualErrorMap,
374
383
  ctx.schemaErrorMap,
375
- exports.overrideErrorMap,
384
+ getErrorMap(),
376
385
  defaultErrorMap,
377
386
  ].filter((x) => !!x),
378
387
  });
@@ -439,6 +448,12 @@
439
448
  const isDirty = (x) => x.status === "dirty";
440
449
  const isValid = (x) => x.status === "valid";
441
450
  const isAsync = (x) => typeof Promise !== undefined && x instanceof Promise;
451
+ const jsonStringifyReplacer = (_, value) => {
452
+ if (typeof value === "bigint") {
453
+ return value.toString();
454
+ }
455
+ return value;
456
+ };
442
457
 
443
458
  var errorUtil;
444
459
  (function (errorUtil) {
@@ -1226,14 +1241,88 @@
1226
1241
  });
1227
1242
  return INVALID;
1228
1243
  }
1244
+ const status = new ParseStatus();
1245
+ let ctx = undefined;
1246
+ for (const check of this._def.checks) {
1247
+ if (check.kind === "min") {
1248
+ if (input.data.getTime() < check.value) {
1249
+ ctx = this._getOrReturnCtx(input, ctx);
1250
+ addIssueToContext(ctx, {
1251
+ code: ZodIssueCode.too_small,
1252
+ message: check.message,
1253
+ inclusive: true,
1254
+ minimum: check.value,
1255
+ type: "date",
1256
+ });
1257
+ status.dirty();
1258
+ }
1259
+ }
1260
+ else if (check.kind === "max") {
1261
+ if (input.data.getTime() > check.value) {
1262
+ ctx = this._getOrReturnCtx(input, ctx);
1263
+ addIssueToContext(ctx, {
1264
+ code: ZodIssueCode.too_big,
1265
+ message: check.message,
1266
+ inclusive: true,
1267
+ maximum: check.value,
1268
+ type: "date",
1269
+ });
1270
+ status.dirty();
1271
+ }
1272
+ }
1273
+ else {
1274
+ util.assertNever(check);
1275
+ }
1276
+ }
1229
1277
  return {
1230
- status: "valid",
1278
+ status: status.value,
1231
1279
  value: new Date(input.data.getTime()),
1232
1280
  };
1233
1281
  }
1282
+ _addCheck(check) {
1283
+ return new ZodDate({
1284
+ ...this._def,
1285
+ checks: [...this._def.checks, check],
1286
+ });
1287
+ }
1288
+ min(minDate, message) {
1289
+ return this._addCheck({
1290
+ kind: "min",
1291
+ value: minDate.getTime(),
1292
+ message: errorUtil.toString(message),
1293
+ });
1294
+ }
1295
+ max(maxDate, message) {
1296
+ return this._addCheck({
1297
+ kind: "max",
1298
+ value: maxDate.getTime(),
1299
+ message: errorUtil.toString(message),
1300
+ });
1301
+ }
1302
+ get minDate() {
1303
+ let min = null;
1304
+ for (const ch of this._def.checks) {
1305
+ if (ch.kind === "min") {
1306
+ if (min === null || ch.value > min)
1307
+ min = ch.value;
1308
+ }
1309
+ }
1310
+ return min != null ? new Date(min) : null;
1311
+ }
1312
+ get maxDate() {
1313
+ let max = null;
1314
+ for (const ch of this._def.checks) {
1315
+ if (ch.kind === "max") {
1316
+ if (max === null || ch.value < max)
1317
+ max = ch.value;
1318
+ }
1319
+ }
1320
+ return max != null ? new Date(max) : null;
1321
+ }
1234
1322
  }
1235
1323
  ZodDate.create = (params) => {
1236
1324
  return new ZodDate({
1325
+ checks: [],
1237
1326
  typeName: exports.ZodFirstPartyTypeKind.ZodDate,
1238
1327
  ...processCreateParams(params),
1239
1328
  });
@@ -2309,7 +2398,7 @@
2309
2398
  errorMaps: [
2310
2399
  ctx.common.contextualErrorMap,
2311
2400
  ctx.schemaErrorMap,
2312
- exports.overrideErrorMap,
2401
+ getErrorMap(),
2313
2402
  defaultErrorMap,
2314
2403
  ].filter((x) => !!x),
2315
2404
  issueData: {
@@ -2325,7 +2414,7 @@
2325
2414
  errorMaps: [
2326
2415
  ctx.common.contextualErrorMap,
2327
2416
  ctx.schemaErrorMap,
2328
- exports.overrideErrorMap,
2417
+ getErrorMap(),
2329
2418
  defaultErrorMap,
2330
2419
  ].filter((x) => !!x),
2331
2420
  issueData: {
@@ -2889,6 +2978,7 @@
2889
2978
  isDirty: isDirty,
2890
2979
  isValid: isValid,
2891
2980
  isAsync: isAsync,
2981
+ jsonStringifyReplacer: jsonStringifyReplacer,
2892
2982
  ZodType: ZodType,
2893
2983
  ZodString: ZodString,
2894
2984
  ZodNumber: ZodNumber,
@@ -2969,8 +3059,8 @@
2969
3059
  quotelessJson: quotelessJson,
2970
3060
  ZodError: ZodError,
2971
3061
  defaultErrorMap: defaultErrorMap,
2972
- get overrideErrorMap () { return exports.overrideErrorMap; },
2973
- setErrorMap: setErrorMap
3062
+ setErrorMap: setErrorMap,
3063
+ getErrorMap: getErrorMap
2974
3064
  });
2975
3065
 
2976
3066
  exports.DIRTY = DIRTY;
@@ -3029,6 +3119,7 @@
3029
3119
  exports.effect = effectsType;
3030
3120
  exports["enum"] = enumType;
3031
3121
  exports["function"] = functionType;
3122
+ exports.getErrorMap = getErrorMap;
3032
3123
  exports.getParsedType = getParsedType;
3033
3124
  exports["instanceof"] = instanceOfType;
3034
3125
  exports.intersection = intersectionType;
@@ -3036,6 +3127,7 @@
3036
3127
  exports.isAsync = isAsync;
3037
3128
  exports.isDirty = isDirty;
3038
3129
  exports.isValid = isValid;
3130
+ exports.jsonStringifyReplacer = jsonStringifyReplacer;
3039
3131
  exports.late = late;
3040
3132
  exports.lazy = lazyType;
3041
3133
  exports.literal = literalType;
package/lib/types.d.ts CHANGED
@@ -214,11 +214,26 @@ export declare class ZodBoolean extends ZodType<boolean, ZodBooleanDef> {
214
214
  _parse(input: ParseInput): ParseReturnType<boolean>;
215
215
  static create: (params?: RawCreateParams) => ZodBoolean;
216
216
  }
217
+ declare type ZodDateCheck = {
218
+ kind: "min";
219
+ value: number;
220
+ message?: string;
221
+ } | {
222
+ kind: "max";
223
+ value: number;
224
+ message?: string;
225
+ };
217
226
  export interface ZodDateDef extends ZodTypeDef {
227
+ checks: ZodDateCheck[];
218
228
  typeName: ZodFirstPartyTypeKind.ZodDate;
219
229
  }
220
230
  export declare class ZodDate extends ZodType<Date, ZodDateDef> {
221
231
  _parse(input: ParseInput): ParseReturnType<this["_output"]>;
232
+ _addCheck(check: ZodDateCheck): ZodDate;
233
+ min(minDate: Date, message?: errorUtil.ErrMessage): ZodDate;
234
+ max(maxDate: Date, message?: errorUtil.ErrMessage): ZodDate;
235
+ get minDate(): Date | null;
236
+ get maxDate(): Date | null;
222
237
  static create: (params?: RawCreateParams) => ZodDate;
223
238
  }
224
239
  export interface ZodUndefinedDef extends ZodTypeDef {
@@ -518,9 +533,9 @@ export declare class ZodFunction<Args extends ZodTuple<any, any>, Returns extend
518
533
  returnType(): Returns;
519
534
  args<Items extends Parameters<typeof ZodTuple["create"]>[0]>(...items: Items): ZodFunction<ZodTuple<Items, ZodUnknown>, Returns>;
520
535
  returns<NewReturnType extends ZodType<any, any>>(returnType: NewReturnType): ZodFunction<Args, NewReturnType>;
521
- implement<F extends InnerTypeOfFunction<Args, Returns>>(func: F): F;
536
+ implement<F extends InnerTypeOfFunction<Args, Returns>>(func: F): ReturnType<F> extends Returns["_output"] ? (...args: Args["_input"]) => ReturnType<F> : OuterTypeOfFunction<Args, Returns>;
522
537
  strictImplement(func: InnerTypeOfFunction<Args, Returns>): InnerTypeOfFunction<Args, Returns>;
523
- validate: <F extends InnerTypeOfFunction<Args, Returns>>(func: F) => F;
538
+ validate: <F extends InnerTypeOfFunction<Args, Returns>>(func: F) => ReturnType<F> extends Returns["_output"] ? (...args: Args["_input"]) => ReturnType<F> : OuterTypeOfFunction<Args, Returns>;
524
539
  static create: <T extends ZodTuple<any, any> = ZodTuple<[], ZodUnknown>, U extends ZodTypeAny = ZodUnknown>(args?: T | undefined, returns?: U | undefined, params?: RawCreateParams) => ZodFunction<T, U>;
525
540
  }
526
541
  export interface ZodLazyDef<T extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef {
package/lib/types.js CHANGED
@@ -793,15 +793,89 @@ class ZodDate extends ZodType {
793
793
  });
794
794
  return parseUtil_1.INVALID;
795
795
  }
796
+ const status = new parseUtil_1.ParseStatus();
797
+ let ctx = undefined;
798
+ for (const check of this._def.checks) {
799
+ if (check.kind === "min") {
800
+ if (input.data.getTime() < check.value) {
801
+ ctx = this._getOrReturnCtx(input, ctx);
802
+ parseUtil_1.addIssueToContext(ctx, {
803
+ code: ZodError_1.ZodIssueCode.too_small,
804
+ message: check.message,
805
+ inclusive: true,
806
+ minimum: check.value,
807
+ type: "date",
808
+ });
809
+ status.dirty();
810
+ }
811
+ }
812
+ else if (check.kind === "max") {
813
+ if (input.data.getTime() > check.value) {
814
+ ctx = this._getOrReturnCtx(input, ctx);
815
+ parseUtil_1.addIssueToContext(ctx, {
816
+ code: ZodError_1.ZodIssueCode.too_big,
817
+ message: check.message,
818
+ inclusive: true,
819
+ maximum: check.value,
820
+ type: "date",
821
+ });
822
+ status.dirty();
823
+ }
824
+ }
825
+ else {
826
+ util_1.util.assertNever(check);
827
+ }
828
+ }
796
829
  return {
797
- status: "valid",
830
+ status: status.value,
798
831
  value: new Date(input.data.getTime()),
799
832
  };
800
833
  }
834
+ _addCheck(check) {
835
+ return new ZodDate({
836
+ ...this._def,
837
+ checks: [...this._def.checks, check],
838
+ });
839
+ }
840
+ min(minDate, message) {
841
+ return this._addCheck({
842
+ kind: "min",
843
+ value: minDate.getTime(),
844
+ message: errorUtil_1.errorUtil.toString(message),
845
+ });
846
+ }
847
+ max(maxDate, message) {
848
+ return this._addCheck({
849
+ kind: "max",
850
+ value: maxDate.getTime(),
851
+ message: errorUtil_1.errorUtil.toString(message),
852
+ });
853
+ }
854
+ get minDate() {
855
+ let min = null;
856
+ for (const ch of this._def.checks) {
857
+ if (ch.kind === "min") {
858
+ if (min === null || ch.value > min)
859
+ min = ch.value;
860
+ }
861
+ }
862
+ return min != null ? new Date(min) : null;
863
+ }
864
+ get maxDate() {
865
+ let max = null;
866
+ for (const ch of this._def.checks) {
867
+ if (ch.kind === "max") {
868
+ if (max === null || ch.value < max)
869
+ max = ch.value;
870
+ }
871
+ }
872
+ return max != null ? new Date(max) : null;
873
+ }
801
874
  }
802
875
  exports.ZodDate = ZodDate;
803
876
  ZodDate.create = (params) => {
804
877
  return new ZodDate({
878
+ checks: [],
805
879
  typeName: ZodFirstPartyTypeKind.ZodDate,
806
880
  ...processCreateParams(params),
807
881
  });
@@ -1893,7 +1967,7 @@ class ZodFunction extends ZodType {
1893
1967
  errorMaps: [
1894
1968
  ctx.common.contextualErrorMap,
1895
1969
  ctx.schemaErrorMap,
1896
- ZodError_1.overrideErrorMap,
1970
+ ZodError_1.getErrorMap(),
1897
1971
  ZodError_1.defaultErrorMap,
1898
1972
  ].filter((x) => !!x),
1899
1973
  issueData: {
@@ -1909,7 +1983,7 @@ class ZodFunction extends ZodType {
1909
1983
  errorMaps: [
1910
1984
  ctx.common.contextualErrorMap,
1911
1985
  ctx.schemaErrorMap,
1912
- ZodError_1.overrideErrorMap,
1986
+ ZodError_1.getErrorMap(),
1913
1987
  ZodError_1.defaultErrorMap,
1914
1988
  ].filter((x) => !!x),
1915
1989
  issueData: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zod",
3
- "version": "3.17.5",
3
+ "version": "3.17.8",
4
4
  "description": "TypeScript-first schema declaration and validation library with static type inference",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./index.d.ts",