@mastra/observability 0.0.0-cloud-storage-adapter-20251106204059 → 0.0.0-cloud-604-map-nested-flow-details-to-side-panel-20251212192149

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