unocab 0.8.0

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