@hasna/todos 0.1.0

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