@commandgarden/cli 0.1.0

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