@hasna/machines 0.0.15 → 0.0.17

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