@opentiny/next-sdk 0.4.0 → 0.4.2

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