@mastra/mcp 0.3.10-alpha.5 → 0.3.10-alpha.6

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