aieracard 0.1.0

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