@unson/brainbase-mcp 0.44.0 → 0.44.1

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