@hasna/invoices 0.0.1

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,4691 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ var __defProp = Object.defineProperty;
4
+ var __returnValue = (v) => v;
5
+ function __exportSetter(name, newValue) {
6
+ this[name] = __returnValue.bind(null, newValue);
7
+ }
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, {
11
+ get: all[name],
12
+ enumerable: true,
13
+ configurable: true,
14
+ set: __exportSetter.bind(all, name)
15
+ });
16
+ };
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/db/database.ts
3992
+ import { mkdirSync } from "fs";
3993
+ import { dirname, join } from "path";
3994
+ import { Database } from "bun:sqlite";
3995
+ function defaultDatabasePath() {
3996
+ const baseDir = join(process.env.HOME ?? ".", ".hasna", "invoices");
3997
+ mkdirSync(baseDir, { recursive: true });
3998
+ return join(baseDir, "invoices.db");
3999
+ }
4000
+ function openInvoiceDatabase(options = {}) {
4001
+ const dbPath = options.dbPath ?? defaultDatabasePath();
4002
+ mkdirSync(dirname(dbPath), { recursive: true });
4003
+ const db = new Database(dbPath, { create: true, strict: true });
4004
+ db.exec("PRAGMA journal_mode = WAL;");
4005
+ db.exec("PRAGMA foreign_keys = ON;");
4006
+ db.exec("PRAGMA busy_timeout = 5000;");
4007
+ return db;
4008
+ }
4009
+
4010
+ // src/db/invoices.ts
4011
+ import { randomUUID } from "crypto";
4012
+ function toLineTotalCents(line) {
4013
+ const subtotal = Math.round(line.quantity * line.unitPriceCents);
4014
+ const taxRate = line.taxRateBasisPoints ?? 0;
4015
+ const tax = Math.round(subtotal * taxRate / 1e4);
4016
+ return { lineTotalCents: subtotal, lineTaxCents: tax };
4017
+ }
4018
+ function mapPartyRow(row) {
4019
+ return {
4020
+ id: row.id,
4021
+ kind: row.kind,
4022
+ legalName: row.legal_name,
4023
+ email: row.email ?? undefined,
4024
+ taxId: row.tax_id ?? undefined,
4025
+ country: row.country ?? undefined,
4026
+ address: row.address ?? undefined,
4027
+ createdAt: row.created_at,
4028
+ updatedAt: row.updated_at
4029
+ };
4030
+ }
4031
+ function mapInvoiceRow(row) {
4032
+ return {
4033
+ id: row.id,
4034
+ number: row.number,
4035
+ issuerId: row.issuer_id,
4036
+ customerId: row.customer_id,
4037
+ status: row.status,
4038
+ currency: row.currency,
4039
+ notes: row.notes ?? undefined,
4040
+ issuedAt: row.issued_at,
4041
+ dueAt: row.due_at ?? undefined,
4042
+ subtotalCents: row.subtotal_cents,
4043
+ taxCents: row.tax_cents,
4044
+ totalCents: row.total_cents,
4045
+ createdAt: row.created_at,
4046
+ updatedAt: row.updated_at
4047
+ };
4048
+ }
4049
+ function mapInvoiceLineRow(row) {
4050
+ return {
4051
+ id: row.id,
4052
+ invoiceId: row.invoice_id,
4053
+ position: row.position,
4054
+ description: row.description,
4055
+ quantity: row.quantity,
4056
+ unitPriceCents: row.unit_price_cents,
4057
+ taxRateBasisPoints: row.tax_rate_basis_points,
4058
+ lineTotalCents: row.line_total_cents,
4059
+ createdAt: row.created_at
4060
+ };
4061
+ }
4062
+ function createParty(db, input) {
4063
+ const id = input.id ?? randomUUID();
4064
+ db.query(`
4065
+ INSERT INTO parties (id, kind, legal_name, email, tax_id, country, address)
4066
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
4067
+ `).run(id, input.kind, input.legalName, input.email ?? null, input.taxId ?? null, input.country ?? null, input.address ?? null);
4068
+ return getPartyById(db, id);
4069
+ }
4070
+ function getPartyById(db, id) {
4071
+ const row = db.query("SELECT * FROM parties WHERE id = ?1").get(id);
4072
+ return row ? mapPartyRow(row) : null;
4073
+ }
4074
+ function listParties(db, kind) {
4075
+ if (kind) {
4076
+ return db.query("SELECT * FROM parties WHERE kind = ?1 ORDER BY legal_name ASC").all(kind).map(mapPartyRow);
4077
+ }
4078
+ return db.query("SELECT * FROM parties ORDER BY legal_name ASC").all().map(mapPartyRow);
4079
+ }
4080
+ function createInvoice(db, input) {
4081
+ const invoiceId = input.id ?? randomUUID();
4082
+ const preparedLines = input.lines.map((line, index) => {
4083
+ const { lineTotalCents, lineTaxCents } = toLineTotalCents(line);
4084
+ return {
4085
+ id: line.id ?? randomUUID(),
4086
+ position: index,
4087
+ description: line.description,
4088
+ quantity: line.quantity,
4089
+ unitPriceCents: line.unitPriceCents,
4090
+ taxRateBasisPoints: line.taxRateBasisPoints ?? 0,
4091
+ lineTotalCents,
4092
+ lineTaxCents
4093
+ };
4094
+ });
4095
+ const subtotalCents = preparedLines.reduce((sum, line) => sum + line.lineTotalCents, 0);
4096
+ const taxCents = preparedLines.reduce((sum, line) => sum + line.lineTaxCents, 0);
4097
+ const totalCents = subtotalCents + taxCents;
4098
+ db.transaction(() => {
4099
+ db.query(`
4100
+ INSERT INTO invoices (
4101
+ id, number, issuer_id, customer_id, status, currency, notes, issued_at, due_at, subtotal_cents, tax_cents, total_cents
4102
+ )
4103
+ VALUES (?1, ?2, ?3, ?4, 'draft', ?5, ?6, ?7, ?8, ?9, ?10, ?11)
4104
+ `).run(invoiceId, input.number, input.issuerId, input.customerId, input.currency, input.notes ?? null, input.issuedAt, input.dueAt ?? null, subtotalCents, taxCents, totalCents);
4105
+ const insertLine = db.query(`
4106
+ INSERT INTO invoice_lines (
4107
+ id, invoice_id, position, description, quantity, unit_price_cents, tax_rate_basis_points, line_total_cents
4108
+ )
4109
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
4110
+ `);
4111
+ for (const line of preparedLines) {
4112
+ insertLine.run(line.id, invoiceId, line.position, line.description, line.quantity, line.unitPriceCents, line.taxRateBasisPoints, line.lineTotalCents);
4113
+ }
4114
+ })();
4115
+ return getInvoiceById(db, invoiceId);
4116
+ }
4117
+ function getInvoiceById(db, id) {
4118
+ const invoiceRow = db.query("SELECT * FROM invoices WHERE id = ?1").get(id);
4119
+ if (!invoiceRow) {
4120
+ return null;
4121
+ }
4122
+ const lines = db.query("SELECT * FROM invoice_lines WHERE invoice_id = ?1 ORDER BY position ASC").all(id).map(mapInvoiceLineRow);
4123
+ return {
4124
+ ...mapInvoiceRow(invoiceRow),
4125
+ lines
4126
+ };
4127
+ }
4128
+ function listInvoices(db, options = {}) {
4129
+ const limit = options.limit ?? 50;
4130
+ const offset = options.offset ?? 0;
4131
+ if (options.status) {
4132
+ return db.query("SELECT * FROM invoices WHERE status = ?1 ORDER BY issued_at DESC, created_at DESC LIMIT ?2 OFFSET ?3").all(options.status, limit, offset).map(mapInvoiceRow);
4133
+ }
4134
+ return db.query("SELECT * FROM invoices ORDER BY issued_at DESC, created_at DESC LIMIT ?1 OFFSET ?2").all(limit, offset).map(mapInvoiceRow);
4135
+ }
4136
+ function updateInvoiceStatus(db, id, status) {
4137
+ db.query("UPDATE invoices SET status = ?2, updated_at = datetime('now') WHERE id = ?1").run(id, status);
4138
+ const row = db.query("SELECT * FROM invoices WHERE id = ?1").get(id);
4139
+ return row ? mapInvoiceRow(row) : null;
4140
+ }
4141
+ function searchInvoices(db, query, options = {}) {
4142
+ const limit = options.limit ?? 20;
4143
+ const offset = options.offset ?? 0;
4144
+ const escapedPhrase = `"${query.replace(/"/g, '""')}"`;
4145
+ if (options.status) {
4146
+ return db.query(`
4147
+ SELECT i.*
4148
+ FROM invoices_fts f
4149
+ JOIN invoices i ON i.id = f.invoice_id
4150
+ WHERE invoices_fts MATCH ?1
4151
+ AND i.status = ?2
4152
+ ORDER BY bm25(invoices_fts)
4153
+ LIMIT ?3
4154
+ OFFSET ?4
4155
+ `).all(escapedPhrase, options.status, limit, offset).map(mapInvoiceRow);
4156
+ }
4157
+ return db.query(`
4158
+ SELECT i.*
4159
+ FROM invoices_fts f
4160
+ JOIN invoices i ON i.id = f.invoice_id
4161
+ WHERE invoices_fts MATCH ?1
4162
+ ORDER BY bm25(invoices_fts)
4163
+ LIMIT ?2
4164
+ OFFSET ?3
4165
+ `).all(escapedPhrase, limit, offset).map(mapInvoiceRow);
4166
+ }
4167
+
4168
+ // src/db/schema.ts
4169
+ var MIGRATIONS = [
4170
+ {
4171
+ id: "0001_init",
4172
+ sql: `
4173
+ CREATE TABLE IF NOT EXISTS migrations (
4174
+ id TEXT PRIMARY KEY,
4175
+ applied_at TEXT NOT NULL DEFAULT (datetime('now'))
4176
+ );
4177
+
4178
+ CREATE TABLE IF NOT EXISTS parties (
4179
+ id TEXT PRIMARY KEY,
4180
+ kind TEXT NOT NULL CHECK(kind IN ('issuer', 'customer')),
4181
+ legal_name TEXT NOT NULL,
4182
+ email TEXT,
4183
+ tax_id TEXT,
4184
+ country TEXT,
4185
+ address TEXT,
4186
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
4187
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
4188
+ );
4189
+
4190
+ CREATE TABLE IF NOT EXISTS invoices (
4191
+ id TEXT PRIMARY KEY,
4192
+ number TEXT NOT NULL UNIQUE,
4193
+ issuer_id TEXT NOT NULL REFERENCES parties(id),
4194
+ customer_id TEXT NOT NULL REFERENCES parties(id),
4195
+ status TEXT NOT NULL CHECK(status IN ('draft', 'sent', 'partially_paid', 'paid', 'void', 'overdue')),
4196
+ currency TEXT NOT NULL,
4197
+ notes TEXT,
4198
+ issued_at TEXT NOT NULL,
4199
+ due_at TEXT,
4200
+ subtotal_cents INTEGER NOT NULL DEFAULT 0,
4201
+ tax_cents INTEGER NOT NULL DEFAULT 0,
4202
+ total_cents INTEGER NOT NULL DEFAULT 0,
4203
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
4204
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
4205
+ );
4206
+
4207
+ CREATE TABLE IF NOT EXISTS invoice_lines (
4208
+ id TEXT PRIMARY KEY,
4209
+ invoice_id TEXT NOT NULL REFERENCES invoices(id) ON DELETE CASCADE,
4210
+ position INTEGER NOT NULL,
4211
+ description TEXT NOT NULL,
4212
+ quantity REAL NOT NULL DEFAULT 1,
4213
+ unit_price_cents INTEGER NOT NULL DEFAULT 0,
4214
+ tax_rate_basis_points INTEGER NOT NULL DEFAULT 0,
4215
+ line_total_cents INTEGER NOT NULL DEFAULT 0,
4216
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
4217
+ );
4218
+
4219
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_invoice_lines_invoice_position
4220
+ ON invoice_lines(invoice_id, position);
4221
+
4222
+ CREATE INDEX IF NOT EXISTS idx_invoices_number ON invoices(number);
4223
+ CREATE INDEX IF NOT EXISTS idx_invoices_status ON invoices(status);
4224
+ CREATE INDEX IF NOT EXISTS idx_invoices_issued_at ON invoices(issued_at);
4225
+ CREATE INDEX IF NOT EXISTS idx_invoices_due_at ON invoices(due_at);
4226
+
4227
+ CREATE VIRTUAL TABLE IF NOT EXISTS invoices_fts USING fts5(
4228
+ invoice_id UNINDEXED,
4229
+ number,
4230
+ issuer_name,
4231
+ customer_name,
4232
+ notes
4233
+ );
4234
+
4235
+ CREATE TRIGGER IF NOT EXISTS invoices_ai_fts
4236
+ AFTER INSERT ON invoices
4237
+ BEGIN
4238
+ INSERT INTO invoices_fts(invoice_id, number, issuer_name, customer_name, notes)
4239
+ VALUES (
4240
+ NEW.id,
4241
+ NEW.number,
4242
+ COALESCE((SELECT legal_name FROM parties WHERE id = NEW.issuer_id), ''),
4243
+ COALESCE((SELECT legal_name FROM parties WHERE id = NEW.customer_id), ''),
4244
+ COALESCE(NEW.notes, '')
4245
+ );
4246
+ END;
4247
+
4248
+ CREATE TRIGGER IF NOT EXISTS invoices_au_fts
4249
+ AFTER UPDATE ON invoices
4250
+ BEGIN
4251
+ DELETE FROM invoices_fts WHERE invoice_id = OLD.id;
4252
+ INSERT INTO invoices_fts(invoice_id, number, issuer_name, customer_name, notes)
4253
+ VALUES (
4254
+ NEW.id,
4255
+ NEW.number,
4256
+ COALESCE((SELECT legal_name FROM parties WHERE id = NEW.issuer_id), ''),
4257
+ COALESCE((SELECT legal_name FROM parties WHERE id = NEW.customer_id), ''),
4258
+ COALESCE(NEW.notes, '')
4259
+ );
4260
+ END;
4261
+
4262
+ CREATE TRIGGER IF NOT EXISTS invoices_ad_fts
4263
+ AFTER DELETE ON invoices
4264
+ BEGIN
4265
+ DELETE FROM invoices_fts WHERE invoice_id = OLD.id;
4266
+ END;
4267
+ `
4268
+ },
4269
+ {
4270
+ id: "0002_party_fts_sync",
4271
+ sql: `
4272
+ CREATE TRIGGER IF NOT EXISTS parties_au_invoice_fts
4273
+ AFTER UPDATE ON parties
4274
+ BEGIN
4275
+ DELETE FROM invoices_fts
4276
+ WHERE invoice_id IN (
4277
+ SELECT id FROM invoices WHERE issuer_id = NEW.id OR customer_id = NEW.id
4278
+ );
4279
+
4280
+ INSERT INTO invoices_fts(invoice_id, number, issuer_name, customer_name, notes)
4281
+ SELECT
4282
+ i.id,
4283
+ i.number,
4284
+ COALESCE((SELECT legal_name FROM parties p WHERE p.id = i.issuer_id), ''),
4285
+ COALESCE((SELECT legal_name FROM parties p WHERE p.id = i.customer_id), ''),
4286
+ COALESCE(i.notes, '')
4287
+ FROM invoices i
4288
+ WHERE i.issuer_id = NEW.id OR i.customer_id = NEW.id;
4289
+ END;
4290
+
4291
+ INSERT INTO invoices_fts(invoice_id, number, issuer_name, customer_name, notes)
4292
+ SELECT
4293
+ i.id,
4294
+ i.number,
4295
+ COALESCE((SELECT legal_name FROM parties p WHERE p.id = i.issuer_id), ''),
4296
+ COALESCE((SELECT legal_name FROM parties p WHERE p.id = i.customer_id), ''),
4297
+ COALESCE(i.notes, '')
4298
+ FROM invoices i
4299
+ WHERE i.id NOT IN (SELECT invoice_id FROM invoices_fts);
4300
+ `
4301
+ },
4302
+ {
4303
+ id: "0003_agents",
4304
+ sql: `
4305
+ CREATE TABLE IF NOT EXISTS agents (
4306
+ id TEXT PRIMARY KEY,
4307
+ name TEXT NOT NULL UNIQUE,
4308
+ description TEXT,
4309
+ focus TEXT,
4310
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
4311
+ last_seen_at TEXT NOT NULL DEFAULT (datetime('now'))
4312
+ );
4313
+ `
4314
+ }
4315
+ ];
4316
+
4317
+ // src/db/migrate.ts
4318
+ function ensureMigrationsTable(db) {
4319
+ db.exec(`
4320
+ CREATE TABLE IF NOT EXISTS migrations (
4321
+ id TEXT PRIMARY KEY,
4322
+ applied_at TEXT NOT NULL DEFAULT (datetime('now'))
4323
+ );
4324
+ `);
4325
+ }
4326
+ function applyMigrations(db) {
4327
+ ensureMigrationsTable(db);
4328
+ const getMigration = db.query("SELECT id FROM migrations WHERE id = ?1");
4329
+ const markMigration = db.query("INSERT INTO migrations (id) VALUES (?1)");
4330
+ const applied = [];
4331
+ for (const migration of MIGRATIONS) {
4332
+ const row = getMigration.get(migration.id);
4333
+ if (row) {
4334
+ continue;
4335
+ }
4336
+ db.transaction(() => {
4337
+ db.exec(migration.sql);
4338
+ markMigration.run(migration.id);
4339
+ })();
4340
+ applied.push(migration.id);
4341
+ }
4342
+ return applied;
4343
+ }
4344
+ function migrateDatabase(options = {}) {
4345
+ const db = openInvoiceDatabase(options);
4346
+ try {
4347
+ return applyMigrations(db);
4348
+ } finally {
4349
+ db.close();
4350
+ }
4351
+ }
4352
+
4353
+ // src/db/agents.ts
4354
+ import { randomUUID as randomUUID2 } from "crypto";
4355
+ function mapAgent(row) {
4356
+ return {
4357
+ id: row.id,
4358
+ name: row.name,
4359
+ description: row.description ?? undefined,
4360
+ focus: row.focus ?? undefined,
4361
+ createdAt: row.created_at,
4362
+ lastSeenAt: row.last_seen_at
4363
+ };
4364
+ }
4365
+ function registerAgent(db, input) {
4366
+ const existing = db.query("SELECT * FROM agents WHERE name = ?1").get(input.name);
4367
+ if (existing) {
4368
+ db.query("UPDATE agents SET description = COALESCE(?2, description), last_seen_at = datetime('now') WHERE name = ?1").run(input.name, input.description ?? null);
4369
+ return getAgentByName(db, input.name);
4370
+ }
4371
+ const id = randomUUID2();
4372
+ db.query("INSERT INTO agents (id, name, description) VALUES (?1, ?2, ?3)").run(id, input.name, input.description ?? null);
4373
+ return getAgentById(db, id);
4374
+ }
4375
+ function getAgentById(db, id) {
4376
+ const row = db.query("SELECT * FROM agents WHERE id = ?1").get(id);
4377
+ return row ? mapAgent(row) : null;
4378
+ }
4379
+ function getAgentByName(db, name) {
4380
+ const row = db.query("SELECT * FROM agents WHERE name = ?1").get(name);
4381
+ return row ? mapAgent(row) : null;
4382
+ }
4383
+ function heartbeatAgent(db, agentId) {
4384
+ db.query("UPDATE agents SET last_seen_at = datetime('now') WHERE id = ?1").run(agentId);
4385
+ return getAgentById(db, agentId);
4386
+ }
4387
+ function setAgentFocus(db, agentId, focus) {
4388
+ db.query("UPDATE agents SET focus = ?2, last_seen_at = datetime('now') WHERE id = ?1").run(agentId, focus ?? null);
4389
+ return getAgentById(db, agentId);
4390
+ }
4391
+ function listAgents(db) {
4392
+ return db.query("SELECT * FROM agents ORDER BY last_seen_at DESC").all().map(mapAgent);
4393
+ }
4394
+
4395
+ // src/server/index.ts
4396
+ var port = Number(process.env.PORT ?? 3487);
4397
+ var statusSchema = exports_external.enum(["draft", "sent", "partially_paid", "paid", "void", "overdue"]);
4398
+ var createPartySchema = exports_external.object({
4399
+ kind: exports_external.enum(["issuer", "customer"]),
4400
+ legal_name: exports_external.string().min(1),
4401
+ email: exports_external.string().email().optional(),
4402
+ tax_id: exports_external.string().optional(),
4403
+ country: exports_external.string().optional(),
4404
+ address: exports_external.string().optional()
4405
+ });
4406
+ var createInvoiceSchema = exports_external.object({
4407
+ number: exports_external.string().min(1),
4408
+ issuer_id: exports_external.string().min(1),
4409
+ customer_id: exports_external.string().min(1),
4410
+ currency: exports_external.string().min(3),
4411
+ notes: exports_external.string().optional(),
4412
+ issued_at: exports_external.string().min(1),
4413
+ due_at: exports_external.string().optional(),
4414
+ lines: exports_external.array(exports_external.object({
4415
+ description: exports_external.string().min(1),
4416
+ quantity: exports_external.number().positive(),
4417
+ unit_price_cents: exports_external.number().int().nonnegative(),
4418
+ tax_rate_basis_points: exports_external.number().int().nonnegative().optional()
4419
+ }))
4420
+ });
4421
+ var registerAgentSchema = exports_external.object({
4422
+ name: exports_external.string().min(1),
4423
+ description: exports_external.string().optional()
4424
+ });
4425
+ function json(data, status = 200) {
4426
+ const allowedOrigin = process.env.INVOICES_ALLOWED_ORIGIN;
4427
+ return Response.json(data, {
4428
+ status,
4429
+ headers: {
4430
+ "x-content-type-options": "nosniff",
4431
+ "x-frame-options": "DENY",
4432
+ "referrer-policy": "no-referrer",
4433
+ "cache-control": "no-store",
4434
+ ...allowedOrigin ? { "access-control-allow-origin": allowedOrigin, vary: "Origin" } : {}
4435
+ }
4436
+ });
4437
+ }
4438
+ async function parseBody(request) {
4439
+ const contentLength = Number(request.headers.get("content-length") ?? "0");
4440
+ if (contentLength > 1024 * 1024) {
4441
+ throw new Error("Payload too large");
4442
+ }
4443
+ try {
4444
+ return await request.json();
4445
+ } catch {
4446
+ throw new Error("Invalid JSON body");
4447
+ }
4448
+ }
4449
+ function authenticate(request) {
4450
+ const required = process.env.INVOICES_API_KEY;
4451
+ if (!required)
4452
+ return true;
4453
+ const auth = request.headers.get("authorization") ?? "";
4454
+ if (!auth.startsWith("Bearer "))
4455
+ return false;
4456
+ const token = auth.slice("Bearer ".length).trim();
4457
+ return token.length > 0 && token === required;
4458
+ }
4459
+ var server = Bun.serve({
4460
+ port,
4461
+ async fetch(request) {
4462
+ const url = new URL(request.url);
4463
+ const method = request.method.toUpperCase();
4464
+ if (url.pathname === "/health" && method === "GET") {
4465
+ return json({ ok: true, service: "invoices" });
4466
+ }
4467
+ if (method === "OPTIONS") {
4468
+ const allowedOrigin = process.env.INVOICES_ALLOWED_ORIGIN;
4469
+ if (!allowedOrigin) {
4470
+ return new Response(null, { status: 204 });
4471
+ }
4472
+ return new Response(null, {
4473
+ status: 204,
4474
+ headers: {
4475
+ "access-control-allow-origin": allowedOrigin,
4476
+ "access-control-allow-methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
4477
+ "access-control-allow-headers": "content-type,authorization",
4478
+ "access-control-max-age": "600",
4479
+ vary: "Origin"
4480
+ }
4481
+ });
4482
+ }
4483
+ if (!authenticate(request)) {
4484
+ return json({ error: "Unauthorized" }, 401);
4485
+ }
4486
+ if (url.pathname === "/api/migrate" && method === "POST") {
4487
+ const applied = migrateDatabase();
4488
+ return json({ applied });
4489
+ }
4490
+ if (url.pathname === "/api/parties" && method === "POST") {
4491
+ const parsed = createPartySchema.parse(await parseBody(request));
4492
+ const db = openInvoiceDatabase();
4493
+ try {
4494
+ const party = createParty(db, {
4495
+ kind: parsed.kind,
4496
+ legalName: parsed.legal_name,
4497
+ email: parsed.email,
4498
+ taxId: parsed.tax_id,
4499
+ country: parsed.country,
4500
+ address: parsed.address
4501
+ });
4502
+ return json(party, 201);
4503
+ } finally {
4504
+ db.close();
4505
+ }
4506
+ }
4507
+ if (url.pathname === "/api/parties" && method === "GET") {
4508
+ const kind = url.searchParams.get("kind");
4509
+ const db = openInvoiceDatabase();
4510
+ try {
4511
+ const parties = listParties(db, kind === "issuer" || kind === "customer" ? kind : undefined);
4512
+ return json(parties);
4513
+ } finally {
4514
+ db.close();
4515
+ }
4516
+ }
4517
+ if (url.pathname === "/api/invoices" && method === "POST") {
4518
+ const parsed = createInvoiceSchema.parse(await parseBody(request));
4519
+ const db = openInvoiceDatabase();
4520
+ try {
4521
+ const invoice = createInvoice(db, {
4522
+ number: parsed.number,
4523
+ issuerId: parsed.issuer_id,
4524
+ customerId: parsed.customer_id,
4525
+ currency: parsed.currency,
4526
+ notes: parsed.notes,
4527
+ issuedAt: parsed.issued_at,
4528
+ dueAt: parsed.due_at,
4529
+ lines: parsed.lines.map((line) => ({
4530
+ description: line.description,
4531
+ quantity: line.quantity,
4532
+ unitPriceCents: line.unit_price_cents,
4533
+ taxRateBasisPoints: line.tax_rate_basis_points
4534
+ }))
4535
+ });
4536
+ return json(invoice, 201);
4537
+ } finally {
4538
+ db.close();
4539
+ }
4540
+ }
4541
+ if (url.pathname === "/api/invoices" && method === "GET") {
4542
+ const status = url.searchParams.get("status");
4543
+ const limit = Number(url.searchParams.get("limit") ?? "50");
4544
+ const offset = Number(url.searchParams.get("offset") ?? "0");
4545
+ const db = openInvoiceDatabase();
4546
+ try {
4547
+ const invoices = listInvoices(db, {
4548
+ status: statusSchema.safeParse(status).success ? status : undefined,
4549
+ limit,
4550
+ offset
4551
+ });
4552
+ return json(invoices);
4553
+ } finally {
4554
+ db.close();
4555
+ }
4556
+ }
4557
+ if (url.pathname === "/api/stats" && method === "GET") {
4558
+ const db = openInvoiceDatabase();
4559
+ try {
4560
+ const all = listInvoices(db, { limit: 1e4, offset: 0 });
4561
+ const parties = listParties(db);
4562
+ const agents = listAgents(db);
4563
+ const stats = {
4564
+ total_invoices: all.length,
4565
+ draft: all.filter((i) => i.status === "draft").length,
4566
+ sent: all.filter((i) => i.status === "sent").length,
4567
+ partially_paid: all.filter((i) => i.status === "partially_paid").length,
4568
+ paid: all.filter((i) => i.status === "paid").length,
4569
+ void: all.filter((i) => i.status === "void").length,
4570
+ overdue: all.filter((i) => i.status === "overdue").length,
4571
+ parties: parties.length,
4572
+ issuers: parties.filter((p) => p.kind === "issuer").length,
4573
+ customers: parties.filter((p) => p.kind === "customer").length,
4574
+ agents: agents.length
4575
+ };
4576
+ return json(stats);
4577
+ } finally {
4578
+ db.close();
4579
+ }
4580
+ }
4581
+ if (url.pathname === "/api/invoices/search" && method === "GET") {
4582
+ const query = url.searchParams.get("q");
4583
+ if (!query) {
4584
+ return json({ error: "Missing q query parameter" }, 400);
4585
+ }
4586
+ if (query.length > 200) {
4587
+ return json({ error: "Query too long" }, 400);
4588
+ }
4589
+ const status = url.searchParams.get("status");
4590
+ const limit = Number(url.searchParams.get("limit") ?? "20");
4591
+ const offset = Number(url.searchParams.get("offset") ?? "0");
4592
+ const db = openInvoiceDatabase();
4593
+ try {
4594
+ const invoices = searchInvoices(db, query, {
4595
+ status: statusSchema.safeParse(status).success ? status : undefined,
4596
+ limit,
4597
+ offset
4598
+ });
4599
+ return json(invoices);
4600
+ } finally {
4601
+ db.close();
4602
+ }
4603
+ }
4604
+ if (url.pathname.startsWith("/api/invoices/") && method === "GET") {
4605
+ const id = url.pathname.replace("/api/invoices/", "");
4606
+ if (!id || id.includes("/")) {
4607
+ return json({ error: "Invalid invoice id" }, 400);
4608
+ }
4609
+ const db = openInvoiceDatabase();
4610
+ try {
4611
+ const invoice = getInvoiceById(db, id);
4612
+ if (!invoice) {
4613
+ return json({ error: "Invoice not found" }, 404);
4614
+ }
4615
+ return json(invoice);
4616
+ } finally {
4617
+ db.close();
4618
+ }
4619
+ }
4620
+ if (url.pathname === "/api/agents" && method === "GET") {
4621
+ const db = openInvoiceDatabase();
4622
+ try {
4623
+ return json(listAgents(db));
4624
+ } finally {
4625
+ db.close();
4626
+ }
4627
+ }
4628
+ if (url.pathname === "/api/agents" && method === "POST") {
4629
+ const body = registerAgentSchema.parse(await parseBody(request));
4630
+ const db = openInvoiceDatabase();
4631
+ try {
4632
+ return json(registerAgent(db, body), 201);
4633
+ } finally {
4634
+ db.close();
4635
+ }
4636
+ }
4637
+ if (url.pathname.startsWith("/api/agents/") && url.pathname.endsWith("/heartbeat") && method === "POST") {
4638
+ const id = url.pathname.replace("/api/agents/", "").replace("/heartbeat", "");
4639
+ const db = openInvoiceDatabase();
4640
+ try {
4641
+ const agent = heartbeatAgent(db, id);
4642
+ if (!agent)
4643
+ return json({ error: "Agent not found" }, 404);
4644
+ return json(agent);
4645
+ } finally {
4646
+ db.close();
4647
+ }
4648
+ }
4649
+ if (url.pathname.startsWith("/api/agents/") && url.pathname.endsWith("/focus") && method === "POST") {
4650
+ const id = url.pathname.replace("/api/agents/", "").replace("/focus", "");
4651
+ const body = exports_external.object({ focus: exports_external.string().optional() }).parse(await parseBody(request));
4652
+ const db = openInvoiceDatabase();
4653
+ try {
4654
+ const agent = setAgentFocus(db, id, body.focus);
4655
+ if (!agent)
4656
+ return json({ error: "Agent not found" }, 404);
4657
+ return json(agent);
4658
+ } finally {
4659
+ db.close();
4660
+ }
4661
+ }
4662
+ if (url.pathname.endsWith("/status") && method === "POST") {
4663
+ const id = url.pathname.replace("/api/invoices/", "").replace("/status", "");
4664
+ if (!id || id.includes("/")) {
4665
+ return json({ error: "Invalid invoice id" }, 400);
4666
+ }
4667
+ const body = exports_external.object({ status: statusSchema }).parse(await parseBody(request));
4668
+ const db = openInvoiceDatabase();
4669
+ try {
4670
+ const updated = updateInvoiceStatus(db, id, body.status);
4671
+ if (!updated) {
4672
+ return json({ error: "Invoice not found" }, 404);
4673
+ }
4674
+ return json(updated);
4675
+ } finally {
4676
+ db.close();
4677
+ }
4678
+ }
4679
+ return json({ error: "Not found" }, 404);
4680
+ },
4681
+ error(error) {
4682
+ if (error instanceof exports_external.ZodError) {
4683
+ return json({ error: "Validation error", details: error.issues }, 400);
4684
+ }
4685
+ if (error instanceof Error) {
4686
+ return json({ error: error.message }, 400);
4687
+ }
4688
+ return json({ error: "Unknown error" }, 500);
4689
+ }
4690
+ });
4691
+ console.log(`invoices server running on http://localhost:${server.port}`);