@sushant-kum/ccstatus 0.0.0-stage → 0.1.0

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