@hasna/switcher 0.2.10 → 0.2.12

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