zod 3.18.0 → 3.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -63,7 +63,7 @@
63
63
  - [Nullables](#nullables)
64
64
  - [Objects](#objects)
65
65
  - [.shape](#shape)
66
- - [.enum](#enum)
66
+ - [.keyof](#keyof)
67
67
  - [.extend](#extend)
68
68
  - [.merge](#merge)
69
69
  - [.pick/.omit](#pickomit)
@@ -90,7 +90,6 @@
90
90
  - [Instanceof](#instanceof)
91
91
  - [Function schemas](#function-schemas)
92
92
  - [Preprocess](#preprocess)
93
- - [Branded types](#branded-types)
94
93
  - [Schema methods](#schema-methods)
95
94
  - [.parse](#parse)
96
95
  - [.parseAsync](#parseasync)
@@ -107,6 +106,7 @@
107
106
  - [.promise](#promise)
108
107
  - [.or](#or)
109
108
  - [.and](#and)
109
+ - [.brand](#brand)
110
110
  - [Guides and concepts](#guides-and-concepts)
111
111
  - [Type inference](#type-inference)
112
112
  - [Writing generic functions](#writing-generic-functions)
@@ -306,9 +306,9 @@ There are a growing number of tools that are built atop or support Zod natively!
306
306
  - [`tRPC`](https://github.com/trpc/trpc): Build end-to-end typesafe APIs without GraphQL.
307
307
  - [`ts-to-zod`](https://github.com/fabien0102/ts-to-zod): Convert TypeScript definitions into Zod schemas.
308
308
  - [`zod-to-ts`](https://github.com/sachinraja/zod-to-ts): Generate TypeScript definitions from Zod schemas.
309
- - [`@anatine/zod-openapi`](https://github.com/anatine/zod-plugins/tree/main/libs/zod-openapi): Converts a Zod schema to an OpenAPI v3.x `SchemaObject`.
310
- - [`@anatine/zod-mock`](https://github.com/anatine/zod-plugins/tree/main/libs/zod-mock): Generate mock data from a Zod schema. Powered by [faker.js](https://github.com/Marak/Faker.js).
311
- - [`@anatine/zod-nestjs`](https://github.com/anatine/zod-plugins/tree/main/libs/zod-nestjs): Helper methods for using Zod in a NestJS project.
309
+ - [`@anatine/zod-openapi`](https://github.com/anatine/zod-plugins/tree/main/packages/zod-openapi): Converts a Zod schema to an OpenAPI v3.x `SchemaObject`.
310
+ - [`@anatine/zod-mock`](https://github.com/anatine/zod-plugins/tree/main/packages/zod-mock): Generate mock data from a Zod schema. Powered by [faker.js](https://github.com/Marak/Faker.js).
311
+ - [`@anatine/zod-nestjs`](https://github.com/anatine/zod-plugins/tree/main/packages/zod-nestjs): Helper methods for using Zod in a NestJS project.
312
312
  - [`zod-mocking`](https://github.com/dipasqualew/zod-mocking): Generate mock data from your Zod schemas.
313
313
  - [`zod-fast-check`](https://github.com/DavidTimms/zod-fast-check): Generate `fast-check` arbitraries from Zod schemas.
314
314
  - [`zod-endpoints`](https://github.com/flock-community/zod-endpoints): Contract-first strictly typed endpoints with Zod. OpenAPI compatible.
@@ -330,6 +330,7 @@ There are a growing number of tools that are built atop or support Zod natively!
330
330
  - [`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.
331
331
  - [`@zodios/core`](https://github.com/ecyrbe/zodios): A typescript API client with runtime and compile time validation backed by axios and zod.
332
332
  - [`@runtyping/zod`](https://github.com/johngeorgewright/runtyping/tree/master/packages/zod): Generate zod from static types & JSON schema.
333
+ - [`slonik`](https://github.com/gajus/slonik/tree/gajus/add-zod-validation-backwards-compatible#runtime-validation-and-static-type-inference): Node.js Postgres client with strong Zod integration
333
334
 
334
335
  #### Form integrations
335
336
 
@@ -799,7 +800,7 @@ Dog.shape.age; // => number schema
799
800
 
800
801
  ### `.keyof`
801
802
 
802
- Use `.key` to create a `ZodEnum` schema from the keys of an object schema.
803
+ Use `.keyof` to create a `ZodEnum` schema from the keys of an object schema.
803
804
 
804
805
  ```ts
805
806
  const keySchema = Dog.keyof();
@@ -1073,6 +1074,14 @@ type Athlete = z.infer<typeof athleteSchema>;
1073
1074
  // type Athlete = [string, number, { pointsScored: number }]
1074
1075
  ```
1075
1076
 
1077
+ A variadic ("rest") argument can be added with the `.rest` method.
1078
+
1079
+ ```ts
1080
+ const variadicTuple = z.tuple([z.string()]).rest(z.number());
1081
+ const result = variadicTuple.parse(["hello", 1, 2, 3]);
1082
+ // => [string, ...number[]];
1083
+ ```
1084
+
1076
1085
  ## Unions
1077
1086
 
1078
1087
  Zod includes a built-in `z.union` method for composing "OR" types.
@@ -1683,34 +1692,33 @@ const Strings = z.array(z.string()).superRefine((val, ctx) => {
1683
1692
  });
1684
1693
  ```
1685
1694
 
1686
- You can add as many issues as you like. If `ctx.addIssue` is NOT called during the execution of the function, validation passes.
1695
+ You can add as many issues as you like. If `ctx.addIssue` is _not_ called during the execution of the function, validation passes.
1687
1696
 
1688
1697
  Normally refinements always create issues with a `ZodIssueCode.custom` error code, but with `superRefine` you can create any issue of any code. Each issue code is described in detail in the Error Handling guide: [ERROR_HANDLING.md](ERROR_HANDLING.md).
1689
1698
 
1690
1699
  #### Abort early
1691
1700
 
1692
- By default, parsing will continue even after a refinement check fails. For instance, if you chain together multiple refinements, they will all be executed. However, it may be desirable to _abort early_ to prevent later refinements from being executed. To achieve this, pass the `fatal` flag to `ctx.addIssue`:
1701
+ By default, parsing will continue even after a refinement check fails. For instance, if you chain together multiple refinements, they will all be executed. However, it may be desirable to _abort early_ to prevent later refinements from being executed. To achieve this, pass the `fatal` flag to `ctx.addIssue` and return `z.NEVER`.
1693
1702
 
1694
1703
  ```ts
1695
- const Strings = z
1696
- .number()
1697
- .superRefine((val, ctx) => {
1698
- if (val < 10) {
1699
- ctx.addIssue({
1700
- code: z.ZodIssueCode.custom,
1701
- message: "foo",
1702
- fatal: true,
1703
- });
1704
- }
1705
- })
1706
- .superRefine((val, ctx) => {
1707
- if (val !== " ") {
1708
- ctx.addIssue({
1709
- code: z.ZodIssueCode.custom,
1710
- message: "bar",
1711
- });
1712
- }
1713
- });
1704
+ const schema = z.number().superRefine((val, ctx) => {
1705
+ if (val < 10) {
1706
+ ctx.addIssue({
1707
+ code: z.ZodIssueCode.custom,
1708
+ message: "should be >= 10",
1709
+ fatal: true,
1710
+ });
1711
+
1712
+ return z.NEVER;
1713
+ }
1714
+
1715
+ if (val !== 12) {
1716
+ ctx.addIssue({
1717
+ code: z.ZodIssueCode.custom,
1718
+ message: "should be twelve",
1719
+ });
1720
+ }
1721
+ });
1714
1722
  ```
1715
1723
 
1716
1724
  ### `.transform`
@@ -1722,8 +1730,6 @@ const stringToNumber = z.string().transform((val) => val.length);
1722
1730
  stringToNumber.parse("string"); // => 6
1723
1731
  ```
1724
1732
 
1725
- > ⚠️ Transform functions must not throw. Make sure to use refinements before the transform or addIssue within the transform to make sure the input can be parsed by the transform.
1726
-
1727
1733
  #### Chaining order
1728
1734
 
1729
1735
  Note that `stringToNumber` above is an instance of the `ZodEffects` subclass. It is NOT an instance of `ZodString`. If you want to use the built-in methods of `ZodString` (e.g. `.email()`) you must apply those methods _before_ any transforms.
@@ -1739,7 +1745,9 @@ emailToDomain.parse("colinhacks@example.com"); // => example.com
1739
1745
 
1740
1746
  #### Validating during transform
1741
1747
 
1742
- Similar to `superRefine`, `transform` can optionally take a `ctx`. This allows you to simultaneously validate and transform the value, which can be simpler than chaining `refine` and `validate`. When calling `ctx.addIssue` make sure to still return a value of the correct type otherwise the inferred type will include `undefined`.
1748
+ The `.transform` method can simultaneously validate and transform the value. This is often simpler and less duplicative than chaining `refine` and `validate`.
1749
+
1750
+ As with `.superRefine`, the transform function receives a `ctx` object with a `addIssue` method that can be used to register validation issues.
1743
1751
 
1744
1752
  ```ts
1745
1753
  const Strings = z.string().transform((val, ctx) => {
@@ -1749,6 +1757,12 @@ const Strings = z.string().transform((val, ctx) => {
1749
1757
  code: z.ZodIssueCode.custom,
1750
1758
  message: "Not a number",
1751
1759
  });
1760
+
1761
+ // This is a special symbol you can use to
1762
+ // return early from the transform function.
1763
+ // It has type `never` so it does not affect the
1764
+ // inferred return type.
1765
+ return z.NEVER;
1752
1766
  }
1753
1767
  return parsed;
1754
1768
  });
package/lib/ZodError.d.ts CHANGED
@@ -142,16 +142,11 @@ export declare type IssueData = stripPath<ZodIssueOptionalMessage> & {
142
142
  fatal?: boolean;
143
143
  };
144
144
  export declare type MakeErrorData = IssueData;
145
- declare type ErrorMapCtx = {
145
+ export declare type ErrorMapCtx = {
146
146
  defaultError: string;
147
147
  data: any;
148
148
  };
149
- export declare type ZodErrorMap = typeof defaultErrorMap;
150
- export declare const defaultErrorMap: (issue: ZodIssueOptionalMessage, _ctx: ErrorMapCtx) => {
151
- message: string;
152
- };
153
- export declare function setErrorMap(map: ZodErrorMap): void;
154
- export declare function getErrorMap(): (issue: ZodIssueOptionalMessage, _ctx: ErrorMapCtx) => {
149
+ export declare type ZodErrorMap = (issue: ZodIssueOptionalMessage, _ctx: ErrorMapCtx) => {
155
150
  message: string;
156
151
  };
157
152
  export {};
package/lib/ZodError.js CHANGED
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getErrorMap = exports.setErrorMap = exports.defaultErrorMap = exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0;
4
- const parseUtil_1 = require("./helpers/parseUtil");
3
+ exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0;
5
4
  const util_1 = require("./helpers/util");
6
5
  exports.ZodIssueCode = util_1.util.arrayToEnum([
7
6
  "invalid_type",
@@ -102,7 +101,7 @@ class ZodError extends Error {
102
101
  return this.message;
103
102
  }
104
103
  get message() {
105
- return JSON.stringify(this.issues, parseUtil_1.jsonStringifyReplacer, 2);
104
+ return JSON.stringify(this.issues, util_1.util.jsonStringifyReplacer, 2);
106
105
  }
107
106
  get isEmpty() {
108
107
  return this.issues.length === 0;
@@ -130,106 +129,3 @@ ZodError.create = (issues) => {
130
129
  const error = new ZodError(issues);
131
130
  return error;
132
131
  };
133
- const defaultErrorMap = (issue, _ctx) => {
134
- let message;
135
- switch (issue.code) {
136
- case exports.ZodIssueCode.invalid_type:
137
- if (issue.received === util_1.ZodParsedType.undefined) {
138
- message = "Required";
139
- }
140
- else {
141
- message = `Expected ${issue.expected}, received ${issue.received}`;
142
- }
143
- break;
144
- case exports.ZodIssueCode.invalid_literal:
145
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, parseUtil_1.jsonStringifyReplacer)}`;
146
- break;
147
- case exports.ZodIssueCode.unrecognized_keys:
148
- message = `Unrecognized key(s) in object: ${util_1.util.joinValues(issue.keys, ", ")}`;
149
- break;
150
- case exports.ZodIssueCode.invalid_union:
151
- message = `Invalid input`;
152
- break;
153
- case exports.ZodIssueCode.invalid_union_discriminator:
154
- message = `Invalid discriminator value. Expected ${util_1.util.joinValues(issue.options)}`;
155
- break;
156
- case exports.ZodIssueCode.invalid_enum_value:
157
- message = `Invalid enum value. Expected ${util_1.util.joinValues(issue.options)}, received '${issue.received}'`;
158
- break;
159
- case exports.ZodIssueCode.invalid_arguments:
160
- message = `Invalid function arguments`;
161
- break;
162
- case exports.ZodIssueCode.invalid_return_type:
163
- message = `Invalid function return type`;
164
- break;
165
- case exports.ZodIssueCode.invalid_date:
166
- message = `Invalid date`;
167
- break;
168
- case exports.ZodIssueCode.invalid_string:
169
- if (typeof issue.validation === "object") {
170
- if ("startsWith" in issue.validation) {
171
- message = `Invalid input: must start with "${issue.validation.startsWith}"`;
172
- }
173
- else if ("endsWith" in issue.validation) {
174
- message = `Invalid input: must end with "${issue.validation.endsWith}"`;
175
- }
176
- else {
177
- util_1.util.assertNever(issue.validation);
178
- }
179
- }
180
- else if (issue.validation !== "regex") {
181
- message = `Invalid ${issue.validation}`;
182
- }
183
- else {
184
- message = "Invalid";
185
- }
186
- break;
187
- case exports.ZodIssueCode.too_small:
188
- if (issue.type === "array")
189
- message = `Array must contain ${issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
190
- else if (issue.type === "string")
191
- message = `String must contain ${issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
192
- else if (issue.type === "number")
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)}`;
196
- else
197
- message = "Invalid input";
198
- break;
199
- case exports.ZodIssueCode.too_big:
200
- if (issue.type === "array")
201
- message = `Array must contain ${issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
202
- else if (issue.type === "string")
203
- message = `String must contain ${issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
204
- else if (issue.type === "number")
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)}`;
208
- else
209
- message = "Invalid input";
210
- break;
211
- case exports.ZodIssueCode.custom:
212
- message = `Invalid input`;
213
- break;
214
- case exports.ZodIssueCode.invalid_intersection_types:
215
- message = `Intersection results could not be merged`;
216
- break;
217
- case exports.ZodIssueCode.not_multiple_of:
218
- message = `Number must be a multiple of ${issue.multipleOf}`;
219
- break;
220
- default:
221
- message = _ctx.defaultError;
222
- util_1.util.assertNever(issue);
223
- }
224
- return { message };
225
- };
226
- exports.defaultErrorMap = defaultErrorMap;
227
- let overrideErrorMap = exports.defaultErrorMap;
228
- function setErrorMap(map) {
229
- overrideErrorMap = map;
230
- }
231
- exports.setErrorMap = setErrorMap;
232
- function getErrorMap() {
233
- return overrideErrorMap;
234
- }
235
- exports.getErrorMap = getErrorMap;
@@ -0,0 +1,5 @@
1
+ import defaultErrorMap from "./locales/en";
2
+ import type { ZodErrorMap } from "./ZodError";
3
+ export { defaultErrorMap };
4
+ export declare function setErrorMap(map: ZodErrorMap): void;
5
+ export declare function getErrorMap(): ZodErrorMap;
package/lib/errors.js ADDED
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getErrorMap = exports.setErrorMap = exports.defaultErrorMap = void 0;
7
+ const en_1 = __importDefault(require("./locales/en"));
8
+ exports.defaultErrorMap = en_1.default;
9
+ let overrideErrorMap = en_1.default;
10
+ function setErrorMap(map) {
11
+ overrideErrorMap = map;
12
+ }
13
+ exports.setErrorMap = setErrorMap;
14
+ function getErrorMap() {
15
+ return overrideErrorMap;
16
+ }
17
+ exports.getErrorMap = getErrorMap;
package/lib/external.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export * from "./errors";
1
2
  export * from "./helpers/parseUtil";
2
3
  export * from "./helpers/typeAliases";
3
4
  export { getParsedType, ZodParsedType } from "./helpers/util";
package/lib/external.js CHANGED
@@ -11,6 +11,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
11
11
  };
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
13
  exports.ZodParsedType = exports.getParsedType = void 0;
14
+ __exportStar(require("./errors"), exports);
14
15
  __exportStar(require("./helpers/parseUtil"), exports);
15
16
  __exportStar(require("./helpers/typeAliases"), exports);
16
17
  var util_1 = require("./helpers/util");
@@ -76,4 +76,3 @@ 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,7 +1,11 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
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
- const ZodError_1 = require("../ZodError");
6
+ 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;
7
+ const errors_1 = require("../errors");
8
+ const en_1 = __importDefault(require("../locales/en"));
5
9
  const makeIssue = (params) => {
6
10
  const { data, path, errorMaps, issueData } = params;
7
11
  const fullPath = [...path, ...(issueData.path || [])];
@@ -33,8 +37,8 @@ function addIssueToContext(ctx, issueData) {
33
37
  errorMaps: [
34
38
  ctx.common.contextualErrorMap,
35
39
  ctx.schemaErrorMap,
36
- ZodError_1.getErrorMap(),
37
- ZodError_1.defaultErrorMap,
40
+ errors_1.getErrorMap(),
41
+ en_1.default,
38
42
  ].filter((x) => !!x),
39
43
  });
40
44
  ctx.common.issues.push(issue);
@@ -108,10 +112,3 @@ const isValid = (x) => x.status === "valid";
108
112
  exports.isValid = isValid;
109
113
  const isAsync = (x) => typeof Promise !== undefined && x instanceof Promise;
110
114
  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;
@@ -18,6 +18,7 @@ export declare namespace util {
18
18
  export type noUndefined<T> = T extends undefined ? never : T;
19
19
  export const isInteger: NumberConstructor["isInteger"];
20
20
  export function joinValues<T extends any[]>(array: T, separator?: string): string;
21
+ export const jsonStringifyReplacer: (_: string, value: any) => any;
21
22
  export {};
22
23
  }
23
24
  export declare const ZodParsedType: {
@@ -57,6 +57,12 @@ var util;
57
57
  .join(separator);
58
58
  }
59
59
  util.joinValues = joinValues;
60
+ util.jsonStringifyReplacer = (_, value) => {
61
+ if (typeof value === "bigint") {
62
+ return value.toString();
63
+ }
64
+ return value;
65
+ };
60
66
  })(util = exports.util || (exports.util = {}));
61
67
  exports.ZodParsedType = util.arrayToEnum([
62
68
  "string",
package/lib/index.mjs CHANGED
@@ -54,6 +54,12 @@ var util;
54
54
  .join(separator);
55
55
  }
56
56
  util.joinValues = joinValues;
57
+ util.jsonStringifyReplacer = (_, value) => {
58
+ if (typeof value === "bigint") {
59
+ return value.toString();
60
+ }
61
+ return value;
62
+ };
57
63
  })(util || (util = {}));
58
64
  const ZodParsedType = util.arrayToEnum([
59
65
  "string",
@@ -218,7 +224,7 @@ class ZodError extends Error {
218
224
  return this.message;
219
225
  }
220
226
  get message() {
221
- return JSON.stringify(this.issues, jsonStringifyReplacer, 2);
227
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
222
228
  }
223
229
  get isEmpty() {
224
230
  return this.issues.length === 0;
@@ -245,7 +251,8 @@ ZodError.create = (issues) => {
245
251
  const error = new ZodError(issues);
246
252
  return error;
247
253
  };
248
- const defaultErrorMap = (issue, _ctx) => {
254
+
255
+ const errorMap = (issue, _ctx) => {
249
256
  let message;
250
257
  switch (issue.code) {
251
258
  case ZodIssueCode.invalid_type:
@@ -257,7 +264,7 @@ const defaultErrorMap = (issue, _ctx) => {
257
264
  }
258
265
  break;
259
266
  case ZodIssueCode.invalid_literal:
260
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, jsonStringifyReplacer)}`;
267
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
261
268
  break;
262
269
  case ZodIssueCode.unrecognized_keys:
263
270
  message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
@@ -338,7 +345,8 @@ const defaultErrorMap = (issue, _ctx) => {
338
345
  }
339
346
  return { message };
340
347
  };
341
- let overrideErrorMap = defaultErrorMap;
348
+
349
+ let overrideErrorMap = errorMap;
342
350
  function setErrorMap(map) {
343
351
  overrideErrorMap = map;
344
352
  }
@@ -377,7 +385,7 @@ function addIssueToContext(ctx, issueData) {
377
385
  ctx.common.contextualErrorMap,
378
386
  ctx.schemaErrorMap,
379
387
  getErrorMap(),
380
- defaultErrorMap,
388
+ errorMap,
381
389
  ].filter((x) => !!x),
382
390
  });
383
391
  ctx.common.issues.push(issue);
@@ -443,12 +451,6 @@ const isAborted = (x) => x.status === "aborted";
443
451
  const isDirty = (x) => x.status === "dirty";
444
452
  const isValid = (x) => x.status === "valid";
445
453
  const isAsync = (x) => typeof Promise !== undefined && x instanceof Promise;
446
- const jsonStringifyReplacer = (_, value) => {
447
- if (typeof value === "bigint") {
448
- return value.toString();
449
- }
450
- return value;
451
- };
452
454
 
453
455
  var errorUtil;
454
456
  (function (errorUtil) {
@@ -484,7 +486,7 @@ function processCreateParams(params) {
484
486
  return {};
485
487
  const { errorMap, invalid_type_error, required_error, description } = params;
486
488
  if (errorMap && (invalid_type_error || required_error)) {
487
- throw new Error(`Can't use "invalid" or "required" in conjunction with custom error map.`);
489
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
488
490
  }
489
491
  if (errorMap)
490
492
  return { errorMap: errorMap, description };
@@ -1605,9 +1607,12 @@ class ZodObject extends ZodType {
1605
1607
  const { status, ctx } = this._processInputParams(input);
1606
1608
  const { shape, keys: shapeKeys } = this._getCached();
1607
1609
  const extraKeys = [];
1608
- for (const key in ctx.data) {
1609
- if (!shapeKeys.includes(key)) {
1610
- extraKeys.push(key);
1610
+ if (!(this._def.catchall instanceof ZodNever &&
1611
+ this._def.unknownKeys === "strip")) {
1612
+ for (const key in ctx.data) {
1613
+ if (!shapeKeys.includes(key)) {
1614
+ extraKeys.push(key);
1615
+ }
1611
1616
  }
1612
1617
  }
1613
1618
  const pairs = [];
@@ -2175,6 +2180,9 @@ class ZodTuple extends ZodType {
2175
2180
  }
2176
2181
  }
2177
2182
  ZodTuple.create = (schemas, params) => {
2183
+ if (!Array.isArray(schemas)) {
2184
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
2185
+ }
2178
2186
  return new ZodTuple({
2179
2187
  items: schemas,
2180
2188
  typeName: ZodFirstPartyTypeKind.ZodTuple,
@@ -2403,7 +2411,7 @@ class ZodFunction extends ZodType {
2403
2411
  ctx.common.contextualErrorMap,
2404
2412
  ctx.schemaErrorMap,
2405
2413
  getErrorMap(),
2406
- defaultErrorMap,
2414
+ errorMap,
2407
2415
  ].filter((x) => !!x),
2408
2416
  issueData: {
2409
2417
  code: ZodIssueCode.invalid_arguments,
@@ -2419,7 +2427,7 @@ class ZodFunction extends ZodType {
2419
2427
  ctx.common.contextualErrorMap,
2420
2428
  ctx.schemaErrorMap,
2421
2429
  getErrorMap(),
2422
- defaultErrorMap,
2430
+ errorMap,
2423
2431
  ].filter((x) => !!x),
2424
2432
  issueData: {
2425
2433
  code: ZodIssueCode.invalid_return_type,
@@ -2489,17 +2497,17 @@ class ZodFunction extends ZodType {
2489
2497
  const validatedFunc = this.parse(func);
2490
2498
  return validatedFunc;
2491
2499
  }
2500
+ static create(args, returns, params) {
2501
+ return new ZodFunction({
2502
+ args: (args
2503
+ ? args
2504
+ : ZodTuple.create([]).rest(ZodUnknown.create())),
2505
+ returns: returns || ZodUnknown.create(),
2506
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
2507
+ ...processCreateParams(params),
2508
+ });
2509
+ }
2492
2510
  }
2493
- ZodFunction.create = (args, returns, params) => {
2494
- return new ZodFunction({
2495
- args: (args
2496
- ? args.rest(ZodUnknown.create())
2497
- : ZodTuple.create([]).rest(ZodUnknown.create())),
2498
- returns: returns || ZodUnknown.create(),
2499
- typeName: ZodFirstPartyTypeKind.ZodFunction,
2500
- ...processCreateParams(params),
2501
- });
2502
- };
2503
2511
  class ZodLazy extends ZodType {
2504
2512
  get schema() {
2505
2513
  return this._def.getter();
@@ -2944,6 +2952,12 @@ var ZodFirstPartyTypeKind;
2944
2952
  ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
2945
2953
  ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
2946
2954
  })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
2955
+ // new approach that works for abstract classes
2956
+ // but required TS 4.4+
2957
+ // abstract class Class {
2958
+ // constructor(..._: any[]) {}
2959
+ // }
2960
+ // const instanceOfType = <T extends typeof Class>(
2947
2961
  const instanceOfType = (cls, params = {
2948
2962
  message: `Input not instance of ${cls.name}`,
2949
2963
  }) => custom((data) => data instanceof cls, params, true);
@@ -2982,11 +2996,15 @@ const preprocessType = ZodEffects.createWithPreprocess;
2982
2996
  const ostring = () => stringType().optional();
2983
2997
  const onumber = () => numberType().optional();
2984
2998
  const oboolean = () => booleanType().optional();
2999
+ const NEVER = INVALID;
2985
3000
 
2986
3001
  var mod = /*#__PURE__*/Object.freeze({
2987
3002
  __proto__: null,
2988
3003
  getParsedType: getParsedType,
2989
3004
  ZodParsedType: ZodParsedType,
3005
+ defaultErrorMap: errorMap,
3006
+ setErrorMap: setErrorMap,
3007
+ getErrorMap: getErrorMap,
2990
3008
  makeIssue: makeIssue,
2991
3009
  EMPTY_PATH: EMPTY_PATH,
2992
3010
  addIssueToContext: addIssueToContext,
@@ -2998,7 +3016,6 @@ var mod = /*#__PURE__*/Object.freeze({
2998
3016
  isDirty: isDirty,
2999
3017
  isValid: isValid,
3000
3018
  isAsync: isAsync,
3001
- jsonStringifyReplacer: jsonStringifyReplacer,
3002
3019
  ZodType: ZodType,
3003
3020
  ZodString: ZodString,
3004
3021
  ZodNumber: ZodNumber,
@@ -3077,12 +3094,10 @@ var mod = /*#__PURE__*/Object.freeze({
3077
3094
  union: unionType,
3078
3095
  unknown: unknownType,
3079
3096
  'void': voidType,
3097
+ NEVER: NEVER,
3080
3098
  ZodIssueCode: ZodIssueCode,
3081
3099
  quotelessJson: quotelessJson,
3082
- ZodError: ZodError,
3083
- defaultErrorMap: defaultErrorMap,
3084
- setErrorMap: setErrorMap,
3085
- getErrorMap: getErrorMap
3100
+ ZodError: ZodError
3086
3101
  });
3087
3102
 
3088
- export { BRAND, DIRTY, EMPTY_PATH, INVALID, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, 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 };
3103
+ export { BRAND, DIRTY, EMPTY_PATH, INVALID, NEVER, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, 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, errorMap as 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, 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
@@ -60,6 +60,12 @@
60
60
  .join(separator);
61
61
  }
62
62
  util.joinValues = joinValues;
63
+ util.jsonStringifyReplacer = (_, value) => {
64
+ if (typeof value === "bigint") {
65
+ return value.toString();
66
+ }
67
+ return value;
68
+ };
63
69
  })(util || (util = {}));
64
70
  const ZodParsedType = util.arrayToEnum([
65
71
  "string",
@@ -224,7 +230,7 @@
224
230
  return this.message;
225
231
  }
226
232
  get message() {
227
- return JSON.stringify(this.issues, jsonStringifyReplacer, 2);
233
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
228
234
  }
229
235
  get isEmpty() {
230
236
  return this.issues.length === 0;
@@ -251,7 +257,8 @@
251
257
  const error = new ZodError(issues);
252
258
  return error;
253
259
  };
254
- const defaultErrorMap = (issue, _ctx) => {
260
+
261
+ const errorMap = (issue, _ctx) => {
255
262
  let message;
256
263
  switch (issue.code) {
257
264
  case ZodIssueCode.invalid_type:
@@ -263,7 +270,7 @@
263
270
  }
264
271
  break;
265
272
  case ZodIssueCode.invalid_literal:
266
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, jsonStringifyReplacer)}`;
273
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
267
274
  break;
268
275
  case ZodIssueCode.unrecognized_keys:
269
276
  message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
@@ -344,7 +351,8 @@
344
351
  }
345
352
  return { message };
346
353
  };
347
- let overrideErrorMap = defaultErrorMap;
354
+
355
+ let overrideErrorMap = errorMap;
348
356
  function setErrorMap(map) {
349
357
  overrideErrorMap = map;
350
358
  }
@@ -383,7 +391,7 @@
383
391
  ctx.common.contextualErrorMap,
384
392
  ctx.schemaErrorMap,
385
393
  getErrorMap(),
386
- defaultErrorMap,
394
+ errorMap,
387
395
  ].filter((x) => !!x),
388
396
  });
389
397
  ctx.common.issues.push(issue);
@@ -449,12 +457,6 @@
449
457
  const isDirty = (x) => x.status === "dirty";
450
458
  const isValid = (x) => x.status === "valid";
451
459
  const isAsync = (x) => typeof Promise !== undefined && x instanceof Promise;
452
- const jsonStringifyReplacer = (_, value) => {
453
- if (typeof value === "bigint") {
454
- return value.toString();
455
- }
456
- return value;
457
- };
458
460
 
459
461
  var errorUtil;
460
462
  (function (errorUtil) {
@@ -490,7 +492,7 @@
490
492
  return {};
491
493
  const { errorMap, invalid_type_error, required_error, description } = params;
492
494
  if (errorMap && (invalid_type_error || required_error)) {
493
- throw new Error(`Can't use "invalid" or "required" in conjunction with custom error map.`);
495
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
494
496
  }
495
497
  if (errorMap)
496
498
  return { errorMap: errorMap, description };
@@ -1611,9 +1613,12 @@
1611
1613
  const { status, ctx } = this._processInputParams(input);
1612
1614
  const { shape, keys: shapeKeys } = this._getCached();
1613
1615
  const extraKeys = [];
1614
- for (const key in ctx.data) {
1615
- if (!shapeKeys.includes(key)) {
1616
- extraKeys.push(key);
1616
+ if (!(this._def.catchall instanceof ZodNever &&
1617
+ this._def.unknownKeys === "strip")) {
1618
+ for (const key in ctx.data) {
1619
+ if (!shapeKeys.includes(key)) {
1620
+ extraKeys.push(key);
1621
+ }
1617
1622
  }
1618
1623
  }
1619
1624
  const pairs = [];
@@ -2181,6 +2186,9 @@
2181
2186
  }
2182
2187
  }
2183
2188
  ZodTuple.create = (schemas, params) => {
2189
+ if (!Array.isArray(schemas)) {
2190
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
2191
+ }
2184
2192
  return new ZodTuple({
2185
2193
  items: schemas,
2186
2194
  typeName: exports.ZodFirstPartyTypeKind.ZodTuple,
@@ -2409,7 +2417,7 @@
2409
2417
  ctx.common.contextualErrorMap,
2410
2418
  ctx.schemaErrorMap,
2411
2419
  getErrorMap(),
2412
- defaultErrorMap,
2420
+ errorMap,
2413
2421
  ].filter((x) => !!x),
2414
2422
  issueData: {
2415
2423
  code: ZodIssueCode.invalid_arguments,
@@ -2425,7 +2433,7 @@
2425
2433
  ctx.common.contextualErrorMap,
2426
2434
  ctx.schemaErrorMap,
2427
2435
  getErrorMap(),
2428
- defaultErrorMap,
2436
+ errorMap,
2429
2437
  ].filter((x) => !!x),
2430
2438
  issueData: {
2431
2439
  code: ZodIssueCode.invalid_return_type,
@@ -2495,17 +2503,17 @@
2495
2503
  const validatedFunc = this.parse(func);
2496
2504
  return validatedFunc;
2497
2505
  }
2506
+ static create(args, returns, params) {
2507
+ return new ZodFunction({
2508
+ args: (args
2509
+ ? args
2510
+ : ZodTuple.create([]).rest(ZodUnknown.create())),
2511
+ returns: returns || ZodUnknown.create(),
2512
+ typeName: exports.ZodFirstPartyTypeKind.ZodFunction,
2513
+ ...processCreateParams(params),
2514
+ });
2515
+ }
2498
2516
  }
2499
- ZodFunction.create = (args, returns, params) => {
2500
- return new ZodFunction({
2501
- args: (args
2502
- ? args.rest(ZodUnknown.create())
2503
- : ZodTuple.create([]).rest(ZodUnknown.create())),
2504
- returns: returns || ZodUnknown.create(),
2505
- typeName: exports.ZodFirstPartyTypeKind.ZodFunction,
2506
- ...processCreateParams(params),
2507
- });
2508
- };
2509
2517
  class ZodLazy extends ZodType {
2510
2518
  get schema() {
2511
2519
  return this._def.getter();
@@ -2950,6 +2958,12 @@
2950
2958
  ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
2951
2959
  ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
2952
2960
  })(exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {}));
2961
+ // new approach that works for abstract classes
2962
+ // but required TS 4.4+
2963
+ // abstract class Class {
2964
+ // constructor(..._: any[]) {}
2965
+ // }
2966
+ // const instanceOfType = <T extends typeof Class>(
2953
2967
  const instanceOfType = (cls, params = {
2954
2968
  message: `Input not instance of ${cls.name}`,
2955
2969
  }) => custom((data) => data instanceof cls, params, true);
@@ -2988,11 +3002,15 @@
2988
3002
  const ostring = () => stringType().optional();
2989
3003
  const onumber = () => numberType().optional();
2990
3004
  const oboolean = () => booleanType().optional();
3005
+ const NEVER = INVALID;
2991
3006
 
2992
3007
  var mod = /*#__PURE__*/Object.freeze({
2993
3008
  __proto__: null,
2994
3009
  getParsedType: getParsedType,
2995
3010
  ZodParsedType: ZodParsedType,
3011
+ defaultErrorMap: errorMap,
3012
+ setErrorMap: setErrorMap,
3013
+ getErrorMap: getErrorMap,
2996
3014
  makeIssue: makeIssue,
2997
3015
  EMPTY_PATH: EMPTY_PATH,
2998
3016
  addIssueToContext: addIssueToContext,
@@ -3004,7 +3022,6 @@
3004
3022
  isDirty: isDirty,
3005
3023
  isValid: isValid,
3006
3024
  isAsync: isAsync,
3007
- jsonStringifyReplacer: jsonStringifyReplacer,
3008
3025
  ZodType: ZodType,
3009
3026
  ZodString: ZodString,
3010
3027
  ZodNumber: ZodNumber,
@@ -3083,18 +3100,17 @@
3083
3100
  union: unionType,
3084
3101
  unknown: unknownType,
3085
3102
  'void': voidType,
3103
+ NEVER: NEVER,
3086
3104
  ZodIssueCode: ZodIssueCode,
3087
3105
  quotelessJson: quotelessJson,
3088
- ZodError: ZodError,
3089
- defaultErrorMap: defaultErrorMap,
3090
- setErrorMap: setErrorMap,
3091
- getErrorMap: getErrorMap
3106
+ ZodError: ZodError
3092
3107
  });
3093
3108
 
3094
3109
  exports.BRAND = BRAND;
3095
3110
  exports.DIRTY = DIRTY;
3096
3111
  exports.EMPTY_PATH = EMPTY_PATH;
3097
3112
  exports.INVALID = INVALID;
3113
+ exports.NEVER = NEVER;
3098
3114
  exports.OK = OK;
3099
3115
  exports.ParseStatus = ParseStatus;
3100
3116
  exports.Schema = ZodType;
@@ -3144,7 +3160,7 @@
3144
3160
  exports.custom = custom;
3145
3161
  exports.date = dateType;
3146
3162
  exports["default"] = mod;
3147
- exports.defaultErrorMap = defaultErrorMap;
3163
+ exports.defaultErrorMap = errorMap;
3148
3164
  exports.discriminatedUnion = discriminatedUnionType;
3149
3165
  exports.effect = effectsType;
3150
3166
  exports["enum"] = enumType;
@@ -3157,7 +3173,6 @@
3157
3173
  exports.isAsync = isAsync;
3158
3174
  exports.isDirty = isDirty;
3159
3175
  exports.isValid = isValid;
3160
- exports.jsonStringifyReplacer = jsonStringifyReplacer;
3161
3176
  exports.late = late;
3162
3177
  exports.lazy = lazyType;
3163
3178
  exports.literal = literalType;
@@ -0,0 +1,3 @@
1
+ import { ZodErrorMap } from "../ZodError";
2
+ declare const errorMap: ZodErrorMap;
3
+ export default errorMap;
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const util_1 = require("../helpers/util");
4
+ const ZodError_1 = require("../ZodError");
5
+ const errorMap = (issue, _ctx) => {
6
+ let message;
7
+ switch (issue.code) {
8
+ case ZodError_1.ZodIssueCode.invalid_type:
9
+ if (issue.received === util_1.ZodParsedType.undefined) {
10
+ message = "Required";
11
+ }
12
+ else {
13
+ message = `Expected ${issue.expected}, received ${issue.received}`;
14
+ }
15
+ break;
16
+ case ZodError_1.ZodIssueCode.invalid_literal:
17
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_1.util.jsonStringifyReplacer)}`;
18
+ break;
19
+ case ZodError_1.ZodIssueCode.unrecognized_keys:
20
+ message = `Unrecognized key(s) in object: ${util_1.util.joinValues(issue.keys, ", ")}`;
21
+ break;
22
+ case ZodError_1.ZodIssueCode.invalid_union:
23
+ message = `Invalid input`;
24
+ break;
25
+ case ZodError_1.ZodIssueCode.invalid_union_discriminator:
26
+ message = `Invalid discriminator value. Expected ${util_1.util.joinValues(issue.options)}`;
27
+ break;
28
+ case ZodError_1.ZodIssueCode.invalid_enum_value:
29
+ message = `Invalid enum value. Expected ${util_1.util.joinValues(issue.options)}, received '${issue.received}'`;
30
+ break;
31
+ case ZodError_1.ZodIssueCode.invalid_arguments:
32
+ message = `Invalid function arguments`;
33
+ break;
34
+ case ZodError_1.ZodIssueCode.invalid_return_type:
35
+ message = `Invalid function return type`;
36
+ break;
37
+ case ZodError_1.ZodIssueCode.invalid_date:
38
+ message = `Invalid date`;
39
+ break;
40
+ case ZodError_1.ZodIssueCode.invalid_string:
41
+ if (typeof issue.validation === "object") {
42
+ if ("startsWith" in issue.validation) {
43
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
44
+ }
45
+ else if ("endsWith" in issue.validation) {
46
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
47
+ }
48
+ else {
49
+ util_1.util.assertNever(issue.validation);
50
+ }
51
+ }
52
+ else if (issue.validation !== "regex") {
53
+ message = `Invalid ${issue.validation}`;
54
+ }
55
+ else {
56
+ message = "Invalid";
57
+ }
58
+ break;
59
+ case ZodError_1.ZodIssueCode.too_small:
60
+ if (issue.type === "array")
61
+ message = `Array must contain ${issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
62
+ else if (issue.type === "string")
63
+ message = `String must contain ${issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
64
+ else if (issue.type === "number")
65
+ message = `Number must be greater than ${issue.inclusive ? `or equal to ` : ``}${issue.minimum}`;
66
+ else if (issue.type === "date")
67
+ message = `Date must be greater than ${issue.inclusive ? `or equal to ` : ``}${new Date(issue.minimum)}`;
68
+ else
69
+ message = "Invalid input";
70
+ break;
71
+ case ZodError_1.ZodIssueCode.too_big:
72
+ if (issue.type === "array")
73
+ message = `Array must contain ${issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
74
+ else if (issue.type === "string")
75
+ message = `String must contain ${issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
76
+ else if (issue.type === "number")
77
+ message = `Number must be less than ${issue.inclusive ? `or equal to ` : ``}${issue.maximum}`;
78
+ else if (issue.type === "date")
79
+ message = `Date must be smaller than ${issue.inclusive ? `or equal to ` : ``}${new Date(issue.maximum)}`;
80
+ else
81
+ message = "Invalid input";
82
+ break;
83
+ case ZodError_1.ZodIssueCode.custom:
84
+ message = `Invalid input`;
85
+ break;
86
+ case ZodError_1.ZodIssueCode.invalid_intersection_types:
87
+ message = `Intersection results could not be merged`;
88
+ break;
89
+ case ZodError_1.ZodIssueCode.not_multiple_of:
90
+ message = `Number must be a multiple of ${issue.multipleOf}`;
91
+ break;
92
+ default:
93
+ message = _ctx.defaultError;
94
+ util_1.util.assertNever(issue);
95
+ }
96
+ return { message };
97
+ };
98
+ exports.default = errorMap;
package/lib/types.d.ts CHANGED
@@ -58,9 +58,9 @@ export declare abstract class ZodType<Output = any, Def extends ZodTypeDef = Zod
58
58
  safeParseAsync(data: unknown, params?: Partial<ParseParams>): Promise<SafeParseReturnType<Input, Output>>;
59
59
  /** Alias of safeParseAsync */
60
60
  spa: (data: unknown, params?: Partial<ParseParams> | undefined) => Promise<SafeParseReturnType<Input, Output>>;
61
- refine<RefinedOutput extends Output>(check: (arg: Output) => arg is RefinedOutput, message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams)): ZodEffects<this, RefinedOutput, RefinedOutput>;
61
+ refine<RefinedOutput extends Output>(check: (arg: Output) => arg is RefinedOutput, message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams)): ZodEffects<this, RefinedOutput, Input>;
62
62
  refine(check: (arg: Output) => unknown | Promise<unknown>, message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams)): ZodEffects<this, Output, Input>;
63
- refinement<RefinedOutput extends Output>(check: (arg: Output) => arg is RefinedOutput, refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData)): ZodEffects<this, RefinedOutput, RefinedOutput>;
63
+ refinement<RefinedOutput extends Output>(check: (arg: Output) => arg is RefinedOutput, refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData)): ZodEffects<this, RefinedOutput, Input>;
64
64
  refinement(check: (arg: Output) => boolean, refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData)): ZodEffects<this, Output, Input>;
65
65
  _refinement(refinement: RefinementEffect<Output>["refinement"]): ZodEffects<this, Output, Input>;
66
66
  superRefine: (refinement: RefinementEffect<Output>["refinement"]) => ZodEffects<this, Output, Input>;
@@ -379,7 +379,7 @@ export declare class ZodObject<T extends ZodRawShape, UnknownKeys extends Unknow
379
379
  * inferred type of merged objects. Please
380
380
  * upgrade if you are experiencing issues.
381
381
  */
382
- merge<Incoming extends AnyZodObject>(merging: Incoming): ZodObject<extendShape<T, ReturnType<Incoming["_def"]["shape"]>>, UnknownKeys, Catchall>;
382
+ merge<Incoming extends AnyZodObject>(merging: Incoming): ZodObject<extendShape<T, ReturnType<Incoming["_def"]["shape"]>>, Incoming["_def"]["unknownKeys"], Incoming["_def"]["catchall"]>;
383
383
  catchall<Index extends ZodTypeAny>(index: Index): ZodObject<T, UnknownKeys, Index>;
384
384
  pick<Mask extends {
385
385
  [k in keyof T]?: true;
@@ -470,6 +470,10 @@ export interface ZodTupleDef<T extends ZodTupleItems | [] = ZodTupleItems, Rest
470
470
  rest: Rest;
471
471
  typeName: ZodFirstPartyTypeKind.ZodTuple;
472
472
  }
473
+ export declare type AnyZodTuple = ZodTuple<[
474
+ ZodTypeAny,
475
+ ...ZodTypeAny[]
476
+ ] | [], ZodTypeAny | null>;
473
477
  export declare class ZodTuple<T extends [ZodTypeAny, ...ZodTypeAny[]] | [] = [ZodTypeAny, ...ZodTypeAny[]], Rest extends ZodTypeAny | null = null> extends ZodType<OutputTypeOfTupleWithRest<T, Rest>, ZodTupleDef<T, Rest>, InputTypeOfTupleWithRest<T, Rest>> {
474
478
  _parse(input: ParseInput): ParseReturnType<this["_output"]>;
475
479
  get items(): T;
@@ -536,7 +540,10 @@ export declare class ZodFunction<Args extends ZodTuple<any, any>, Returns extend
536
540
  implement<F extends InnerTypeOfFunction<Args, Returns>>(func: F): ReturnType<F> extends Returns["_output"] ? (...args: Args["_input"]) => ReturnType<F> : OuterTypeOfFunction<Args, Returns>;
537
541
  strictImplement(func: InnerTypeOfFunction<Args, Returns>): InnerTypeOfFunction<Args, Returns>;
538
542
  validate: <F extends InnerTypeOfFunction<Args, Returns>>(func: F) => ReturnType<F> extends Returns["_output"] ? (...args: Args["_input"]) => ReturnType<F> : OuterTypeOfFunction<Args, Returns>;
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>;
543
+ static create(): ZodFunction<ZodTuple<[], ZodUnknown>, ZodUnknown>;
544
+ static create<T extends AnyZodTuple = ZodTuple<[], ZodUnknown>>(args: T): ZodFunction<T, ZodUnknown>;
545
+ static create<T extends AnyZodTuple, U extends ZodTypeAny>(args: T, returns: U): ZodFunction<T, U>;
546
+ static create<T extends AnyZodTuple = ZodTuple<[], ZodUnknown>, U extends ZodTypeAny = ZodUnknown>(args: T, returns: U, params?: RawCreateParams): ZodFunction<T, U>;
540
547
  }
541
548
  export interface ZodLazyDef<T extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef {
542
549
  getter: () => T;
@@ -624,7 +631,7 @@ export declare class ZodEffects<T extends ZodTypeAny, Output = T["_output"], Inp
624
631
  innerType(): T;
625
632
  _parse(input: ParseInput): ParseReturnType<this["_output"]>;
626
633
  static create: <I extends ZodTypeAny>(schema: I, effect: Effect<I["_output"]>, params?: RawCreateParams) => ZodEffects<I, I["_output"], I["_input"]>;
627
- static createWithPreprocess: <I extends ZodTypeAny>(preprocess: (arg: unknown) => unknown, schema: I, params?: RawCreateParams) => ZodEffects<I, I["_output"], I["_input"]>;
634
+ static createWithPreprocess: <I extends ZodTypeAny>(preprocess: (arg: unknown) => unknown, schema: I, params?: RawCreateParams) => ZodEffects<I, I["_output"], unknown>;
628
635
  }
629
636
  export { ZodEffects as ZodTransformer };
630
637
  export interface ZodOptionalDef<T extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef {
@@ -741,7 +748,7 @@ declare const tupleType: <T extends [] | [ZodTypeAny, ...ZodTypeAny[]]>(schemas:
741
748
  declare const recordType: typeof ZodRecord.create;
742
749
  declare const mapType: <Key extends ZodTypeAny = ZodTypeAny, Value extends ZodTypeAny = ZodTypeAny>(keyType: Key, valueType: Value, params?: RawCreateParams) => ZodMap<Key, Value>;
743
750
  declare const setType: <Value extends ZodTypeAny = ZodTypeAny>(valueType: Value, params?: RawCreateParams) => ZodSet<Value>;
744
- declare const functionType: <T extends ZodTuple<any, any> = ZodTuple<[], ZodUnknown>, U extends ZodTypeAny = ZodUnknown>(args?: T | undefined, returns?: U | undefined, params?: RawCreateParams) => ZodFunction<T, U>;
751
+ declare const functionType: typeof ZodFunction.create;
745
752
  declare const lazyType: <T extends ZodTypeAny>(getter: () => T, params?: RawCreateParams) => ZodLazy<T>;
746
753
  declare const literalType: <T extends string | number | bigint | boolean | null | undefined>(value: T, params?: RawCreateParams) => ZodLiteral<T>;
747
754
  declare const enumType: typeof createZodEnum;
@@ -750,8 +757,9 @@ declare const promiseType: <T extends ZodTypeAny>(schema: T, params?: RawCreateP
750
757
  declare const effectsType: <I extends ZodTypeAny>(schema: I, effect: Effect<I["_output"]>, params?: RawCreateParams) => ZodEffects<I, I["_output"], I["_input"]>;
751
758
  declare const optionalType: <T extends ZodTypeAny>(type: T, params?: RawCreateParams) => ZodOptional<T>;
752
759
  declare const nullableType: <T extends ZodTypeAny>(type: T, params?: RawCreateParams) => ZodNullable<T>;
753
- declare const preprocessType: <I extends ZodTypeAny>(preprocess: (arg: unknown) => unknown, schema: I, params?: RawCreateParams) => ZodEffects<I, I["_output"], I["_input"]>;
760
+ declare const preprocessType: <I extends ZodTypeAny>(preprocess: (arg: unknown) => unknown, schema: I, params?: RawCreateParams) => ZodEffects<I, I["_output"], unknown>;
754
761
  declare const ostring: () => ZodOptional<ZodString>;
755
762
  declare const onumber: () => ZodOptional<ZodNumber>;
756
763
  declare const oboolean: () => ZodOptional<ZodBoolean>;
757
764
  export { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };
765
+ export declare const NEVER: never;
package/lib/types.js CHANGED
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.function = exports.enum = exports.effect = exports.discriminatedUnion = exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.custom = exports.ZodBranded = exports.BRAND = exports.ZodNaN = 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.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0;
4
- exports.void = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = 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 = void 0;
4
+ exports.NEVER = exports.void = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = 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 = void 0;
5
+ const errors_1 = require("./errors");
5
6
  const errorUtil_1 = require("./helpers/errorUtil");
6
7
  const parseUtil_1 = require("./helpers/parseUtil");
7
8
  const util_1 = require("./helpers/util");
@@ -34,7 +35,7 @@ function processCreateParams(params) {
34
35
  return {};
35
36
  const { errorMap, invalid_type_error, required_error, description } = params;
36
37
  if (errorMap && (invalid_type_error || required_error)) {
37
- throw new Error(`Can't use "invalid" or "required" in conjunction with custom error map.`);
38
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
38
39
  }
39
40
  if (errorMap)
40
41
  return { errorMap: errorMap, description };
@@ -1170,9 +1171,12 @@ class ZodObject extends ZodType {
1170
1171
  const { status, ctx } = this._processInputParams(input);
1171
1172
  const { shape, keys: shapeKeys } = this._getCached();
1172
1173
  const extraKeys = [];
1173
- for (const key in ctx.data) {
1174
- if (!shapeKeys.includes(key)) {
1175
- extraKeys.push(key);
1174
+ if (!(this._def.catchall instanceof ZodNever &&
1175
+ this._def.unknownKeys === "strip")) {
1176
+ for (const key in ctx.data) {
1177
+ if (!shapeKeys.includes(key)) {
1178
+ extraKeys.push(key);
1179
+ }
1176
1180
  }
1177
1181
  }
1178
1182
  const pairs = [];
@@ -1746,6 +1750,9 @@ class ZodTuple extends ZodType {
1746
1750
  }
1747
1751
  exports.ZodTuple = ZodTuple;
1748
1752
  ZodTuple.create = (schemas, params) => {
1753
+ if (!Array.isArray(schemas)) {
1754
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
1755
+ }
1749
1756
  return new ZodTuple({
1750
1757
  items: schemas,
1751
1758
  typeName: ZodFirstPartyTypeKind.ZodTuple,
@@ -1976,8 +1983,8 @@ class ZodFunction extends ZodType {
1976
1983
  errorMaps: [
1977
1984
  ctx.common.contextualErrorMap,
1978
1985
  ctx.schemaErrorMap,
1979
- ZodError_1.getErrorMap(),
1980
- ZodError_1.defaultErrorMap,
1986
+ errors_1.getErrorMap(),
1987
+ errors_1.defaultErrorMap,
1981
1988
  ].filter((x) => !!x),
1982
1989
  issueData: {
1983
1990
  code: ZodError_1.ZodIssueCode.invalid_arguments,
@@ -1992,8 +1999,8 @@ class ZodFunction extends ZodType {
1992
1999
  errorMaps: [
1993
2000
  ctx.common.contextualErrorMap,
1994
2001
  ctx.schemaErrorMap,
1995
- ZodError_1.getErrorMap(),
1996
- ZodError_1.defaultErrorMap,
2002
+ errors_1.getErrorMap(),
2003
+ errors_1.defaultErrorMap,
1997
2004
  ].filter((x) => !!x),
1998
2005
  issueData: {
1999
2006
  code: ZodError_1.ZodIssueCode.invalid_return_type,
@@ -2063,18 +2070,18 @@ class ZodFunction extends ZodType {
2063
2070
  const validatedFunc = this.parse(func);
2064
2071
  return validatedFunc;
2065
2072
  }
2073
+ static create(args, returns, params) {
2074
+ return new ZodFunction({
2075
+ args: (args
2076
+ ? args
2077
+ : ZodTuple.create([]).rest(ZodUnknown.create())),
2078
+ returns: returns || ZodUnknown.create(),
2079
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
2080
+ ...processCreateParams(params),
2081
+ });
2082
+ }
2066
2083
  }
2067
2084
  exports.ZodFunction = ZodFunction;
2068
- ZodFunction.create = (args, returns, params) => {
2069
- return new ZodFunction({
2070
- args: (args
2071
- ? args.rest(ZodUnknown.create())
2072
- : ZodTuple.create([]).rest(ZodUnknown.create())),
2073
- returns: returns || ZodUnknown.create(),
2074
- typeName: ZodFirstPartyTypeKind.ZodFunction,
2075
- ...processCreateParams(params),
2076
- });
2077
- };
2078
2085
  class ZodLazy extends ZodType {
2079
2086
  get schema() {
2080
2087
  return this._def.getter();
@@ -2532,6 +2539,12 @@ var ZodFirstPartyTypeKind;
2532
2539
  ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
2533
2540
  ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
2534
2541
  })(ZodFirstPartyTypeKind = exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {}));
2542
+ // new approach that works for abstract classes
2543
+ // but required TS 4.4+
2544
+ // abstract class Class {
2545
+ // constructor(..._: any[]) {}
2546
+ // }
2547
+ // const instanceOfType = <T extends typeof Class>(
2535
2548
  const instanceOfType = (cls, params = {
2536
2549
  message: `Input not instance of ${cls.name}`,
2537
2550
  }) => exports.custom((data) => data instanceof cls, params, true);
@@ -2607,3 +2620,4 @@ const onumber = () => numberType().optional();
2607
2620
  exports.onumber = onumber;
2608
2621
  const oboolean = () => booleanType().optional();
2609
2622
  exports.oboolean = oboolean;
2623
+ exports.NEVER = parseUtil_1.INVALID;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zod",
3
- "version": "3.18.0",
3
+ "version": "3.19.1",
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",
@@ -12,7 +12,8 @@
12
12
  "import": "./lib/index.mjs",
13
13
  "types": "./index.d.ts"
14
14
  },
15
- "./package.json": "./package.json"
15
+ "./package.json": "./package.json",
16
+ "./locales/*": "./lib/locales/*"
16
17
  },
17
18
  "files": [
18
19
  "/lib",