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