@org-dashboard/cli 0.0.1-beta.3

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