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