@fleettools/events 0.1.0

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