@jtl-software/cloud-apps-core 0.0.0-dev.000756e

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 (36) hide show
  1. package/README.md +227 -0
  2. package/dist/AppBridge.d.ts +17 -0
  3. package/dist/AppBridge.spec.d.ts +1 -0
  4. package/dist/capabilities/event/AppBridgeEventCapability.d.ts +10 -0
  5. package/dist/capabilities/event/AppBridgeEventCapability.spec.d.ts +1 -0
  6. package/dist/capabilities/event/index.d.ts +2 -0
  7. package/dist/capabilities/event/types/EventListener.d.ts +2 -0
  8. package/dist/capabilities/event/types/EventObject.d.ts +13 -0
  9. package/dist/capabilities/event/types/index.d.ts +2 -0
  10. package/dist/capabilities/index.d.ts +2 -0
  11. package/dist/capabilities/method/AppBridgeMethodCapability.d.ts +18 -0
  12. package/dist/capabilities/method/AppBridgeMethodCapability.spec.d.ts +1 -0
  13. package/dist/capabilities/method/index.d.ts +1 -0
  14. package/dist/capabilities/method/types/MethodCallBody.d.ts +13 -0
  15. package/dist/capabilities/method/types/index.d.ts +1 -0
  16. package/dist/core/AppBridgeMessagePort.d.ts +11 -0
  17. package/dist/core/AppBridgeMessagePort.spec.d.ts +1 -0
  18. package/dist/core/abstractions/AppBridgeCapability.d.ts +9 -0
  19. package/dist/core/abstractions/AppBridgeInfrastructure.d.ts +9 -0
  20. package/dist/core/abstractions/IAppBridgeCapability.d.ts +2 -0
  21. package/dist/core/abstractions/index.d.ts +3 -0
  22. package/dist/core/index.d.ts +3 -0
  23. package/dist/core/types/ChannelMessage.d.ts +19 -0
  24. package/dist/core/types/ChannelMessageHandler.d.ts +3 -0
  25. package/dist/core/types/Disposer.d.ts +2 -0
  26. package/dist/core/types/IMessageLookup.d.ts +6 -0
  27. package/dist/core/types/MessageType.d.ts +4 -0
  28. package/dist/core/types/SendAppBridgeMessageOptions.d.ts +8 -0
  29. package/dist/core/types/index.d.ts +6 -0
  30. package/dist/factories/createAppBridge.d.ts +2 -0
  31. package/dist/factories/createAppBridge.spec.d.ts +1 -0
  32. package/dist/factories/index.d.ts +1 -0
  33. package/dist/main.d.ts +4 -0
  34. package/dist/main.js +3872 -0
  35. package/dist/main.js.map +1 -0
  36. package/package.json +44 -0
package/dist/main.js ADDED
@@ -0,0 +1,3872 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+ var util;
5
+ (function(util2) {
6
+ util2.assertEqual = (_) => {
7
+ };
8
+ function assertIs(_arg) {
9
+ }
10
+ util2.assertIs = assertIs;
11
+ function assertNever(_x) {
12
+ throw new Error();
13
+ }
14
+ util2.assertNever = assertNever;
15
+ util2.arrayToEnum = (items) => {
16
+ const obj = {};
17
+ for (const item of items) {
18
+ obj[item] = item;
19
+ }
20
+ return obj;
21
+ };
22
+ util2.getValidEnumValues = (obj) => {
23
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
24
+ const filtered = {};
25
+ for (const k of validKeys) {
26
+ filtered[k] = obj[k];
27
+ }
28
+ return util2.objectValues(filtered);
29
+ };
30
+ util2.objectValues = (obj) => {
31
+ return util2.objectKeys(obj).map(function(e) {
32
+ return obj[e];
33
+ });
34
+ };
35
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
36
+ const keys = [];
37
+ for (const key in object) {
38
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
39
+ keys.push(key);
40
+ }
41
+ }
42
+ return keys;
43
+ };
44
+ util2.find = (arr, checker) => {
45
+ for (const item of arr) {
46
+ if (checker(item))
47
+ return item;
48
+ }
49
+ return void 0;
50
+ };
51
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
52
+ function joinValues(array, separator = " | ") {
53
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
54
+ }
55
+ util2.joinValues = joinValues;
56
+ util2.jsonStringifyReplacer = (_, value) => {
57
+ if (typeof value === "bigint") {
58
+ return value.toString();
59
+ }
60
+ return value;
61
+ };
62
+ })(util || (util = {}));
63
+ var objectUtil;
64
+ (function(objectUtil2) {
65
+ objectUtil2.mergeShapes = (first, second) => {
66
+ return {
67
+ ...first,
68
+ ...second
69
+ // second overwrites first
70
+ };
71
+ };
72
+ })(objectUtil || (objectUtil = {}));
73
+ const ZodParsedType = util.arrayToEnum([
74
+ "string",
75
+ "nan",
76
+ "number",
77
+ "integer",
78
+ "float",
79
+ "boolean",
80
+ "date",
81
+ "bigint",
82
+ "symbol",
83
+ "function",
84
+ "undefined",
85
+ "null",
86
+ "array",
87
+ "object",
88
+ "unknown",
89
+ "promise",
90
+ "void",
91
+ "never",
92
+ "map",
93
+ "set"
94
+ ]);
95
+ const getParsedType = (data) => {
96
+ const t = typeof data;
97
+ switch (t) {
98
+ case "undefined":
99
+ return ZodParsedType.undefined;
100
+ case "string":
101
+ return ZodParsedType.string;
102
+ case "number":
103
+ return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
104
+ case "boolean":
105
+ return ZodParsedType.boolean;
106
+ case "function":
107
+ return ZodParsedType.function;
108
+ case "bigint":
109
+ return ZodParsedType.bigint;
110
+ case "symbol":
111
+ return ZodParsedType.symbol;
112
+ case "object":
113
+ if (Array.isArray(data)) {
114
+ return ZodParsedType.array;
115
+ }
116
+ if (data === null) {
117
+ return ZodParsedType.null;
118
+ }
119
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
120
+ return ZodParsedType.promise;
121
+ }
122
+ if (typeof Map !== "undefined" && data instanceof Map) {
123
+ return ZodParsedType.map;
124
+ }
125
+ if (typeof Set !== "undefined" && data instanceof Set) {
126
+ return ZodParsedType.set;
127
+ }
128
+ if (typeof Date !== "undefined" && data instanceof Date) {
129
+ return ZodParsedType.date;
130
+ }
131
+ return ZodParsedType.object;
132
+ default:
133
+ return ZodParsedType.unknown;
134
+ }
135
+ };
136
+ const ZodIssueCode = util.arrayToEnum([
137
+ "invalid_type",
138
+ "invalid_literal",
139
+ "custom",
140
+ "invalid_union",
141
+ "invalid_union_discriminator",
142
+ "invalid_enum_value",
143
+ "unrecognized_keys",
144
+ "invalid_arguments",
145
+ "invalid_return_type",
146
+ "invalid_date",
147
+ "invalid_string",
148
+ "too_small",
149
+ "too_big",
150
+ "invalid_intersection_types",
151
+ "not_multiple_of",
152
+ "not_finite"
153
+ ]);
154
+ class ZodError extends Error {
155
+ get errors() {
156
+ return this.issues;
157
+ }
158
+ constructor(issues) {
159
+ super();
160
+ this.issues = [];
161
+ this.addIssue = (sub) => {
162
+ this.issues = [...this.issues, sub];
163
+ };
164
+ this.addIssues = (subs = []) => {
165
+ this.issues = [...this.issues, ...subs];
166
+ };
167
+ const actualProto = new.target.prototype;
168
+ if (Object.setPrototypeOf) {
169
+ Object.setPrototypeOf(this, actualProto);
170
+ } else {
171
+ this.__proto__ = actualProto;
172
+ }
173
+ this.name = "ZodError";
174
+ this.issues = issues;
175
+ }
176
+ format(_mapper) {
177
+ const mapper = _mapper || function(issue) {
178
+ return issue.message;
179
+ };
180
+ const fieldErrors = { _errors: [] };
181
+ const processError = (error) => {
182
+ for (const issue of error.issues) {
183
+ if (issue.code === "invalid_union") {
184
+ issue.unionErrors.map(processError);
185
+ } else if (issue.code === "invalid_return_type") {
186
+ processError(issue.returnTypeError);
187
+ } else if (issue.code === "invalid_arguments") {
188
+ processError(issue.argumentsError);
189
+ } else if (issue.path.length === 0) {
190
+ fieldErrors._errors.push(mapper(issue));
191
+ } else {
192
+ let curr = fieldErrors;
193
+ let i = 0;
194
+ while (i < issue.path.length) {
195
+ const el = issue.path[i];
196
+ const terminal = i === issue.path.length - 1;
197
+ if (!terminal) {
198
+ curr[el] = curr[el] || { _errors: [] };
199
+ } else {
200
+ curr[el] = curr[el] || { _errors: [] };
201
+ curr[el]._errors.push(mapper(issue));
202
+ }
203
+ curr = curr[el];
204
+ i++;
205
+ }
206
+ }
207
+ }
208
+ };
209
+ processError(this);
210
+ return fieldErrors;
211
+ }
212
+ static assert(value) {
213
+ if (!(value instanceof ZodError)) {
214
+ throw new Error(`Not a ZodError: ${value}`);
215
+ }
216
+ }
217
+ toString() {
218
+ return this.message;
219
+ }
220
+ get message() {
221
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
222
+ }
223
+ get isEmpty() {
224
+ return this.issues.length === 0;
225
+ }
226
+ flatten(mapper = (issue) => issue.message) {
227
+ const fieldErrors = {};
228
+ const formErrors = [];
229
+ for (const sub of this.issues) {
230
+ if (sub.path.length > 0) {
231
+ const firstEl = sub.path[0];
232
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
233
+ fieldErrors[firstEl].push(mapper(sub));
234
+ } else {
235
+ formErrors.push(mapper(sub));
236
+ }
237
+ }
238
+ return { formErrors, fieldErrors };
239
+ }
240
+ get formErrors() {
241
+ return this.flatten();
242
+ }
243
+ }
244
+ ZodError.create = (issues) => {
245
+ const error = new ZodError(issues);
246
+ return error;
247
+ };
248
+ const errorMap = (issue, _ctx) => {
249
+ let message;
250
+ switch (issue.code) {
251
+ case ZodIssueCode.invalid_type:
252
+ if (issue.received === ZodParsedType.undefined) {
253
+ message = "Required";
254
+ } else {
255
+ message = `Expected ${issue.expected}, received ${issue.received}`;
256
+ }
257
+ break;
258
+ case ZodIssueCode.invalid_literal:
259
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
260
+ break;
261
+ case ZodIssueCode.unrecognized_keys:
262
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
263
+ break;
264
+ case ZodIssueCode.invalid_union:
265
+ message = `Invalid input`;
266
+ break;
267
+ case ZodIssueCode.invalid_union_discriminator:
268
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
269
+ break;
270
+ case ZodIssueCode.invalid_enum_value:
271
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
272
+ break;
273
+ case ZodIssueCode.invalid_arguments:
274
+ message = `Invalid function arguments`;
275
+ break;
276
+ case ZodIssueCode.invalid_return_type:
277
+ message = `Invalid function return type`;
278
+ break;
279
+ case ZodIssueCode.invalid_date:
280
+ message = `Invalid date`;
281
+ break;
282
+ case ZodIssueCode.invalid_string:
283
+ if (typeof issue.validation === "object") {
284
+ if ("includes" in issue.validation) {
285
+ message = `Invalid input: must include "${issue.validation.includes}"`;
286
+ if (typeof issue.validation.position === "number") {
287
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
288
+ }
289
+ } else if ("startsWith" in issue.validation) {
290
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
291
+ } else if ("endsWith" in issue.validation) {
292
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
293
+ } else {
294
+ util.assertNever(issue.validation);
295
+ }
296
+ } else if (issue.validation !== "regex") {
297
+ message = `Invalid ${issue.validation}`;
298
+ } else {
299
+ message = "Invalid";
300
+ }
301
+ break;
302
+ case ZodIssueCode.too_small:
303
+ if (issue.type === "array")
304
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
305
+ else if (issue.type === "string")
306
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
307
+ else if (issue.type === "number")
308
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
309
+ else if (issue.type === "bigint")
310
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
311
+ else if (issue.type === "date")
312
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
313
+ else
314
+ message = "Invalid input";
315
+ break;
316
+ case ZodIssueCode.too_big:
317
+ if (issue.type === "array")
318
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
319
+ else if (issue.type === "string")
320
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
321
+ else if (issue.type === "number")
322
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
323
+ else if (issue.type === "bigint")
324
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
325
+ else if (issue.type === "date")
326
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
327
+ else
328
+ message = "Invalid input";
329
+ break;
330
+ case ZodIssueCode.custom:
331
+ message = `Invalid input`;
332
+ break;
333
+ case ZodIssueCode.invalid_intersection_types:
334
+ message = `Intersection results could not be merged`;
335
+ break;
336
+ case ZodIssueCode.not_multiple_of:
337
+ message = `Number must be a multiple of ${issue.multipleOf}`;
338
+ break;
339
+ case ZodIssueCode.not_finite:
340
+ message = "Number must be finite";
341
+ break;
342
+ default:
343
+ message = _ctx.defaultError;
344
+ util.assertNever(issue);
345
+ }
346
+ return { message };
347
+ };
348
+ let overrideErrorMap = errorMap;
349
+ function getErrorMap() {
350
+ return overrideErrorMap;
351
+ }
352
+ const makeIssue = (params) => {
353
+ const { data, path, errorMaps, issueData } = params;
354
+ const fullPath = [...path, ...issueData.path || []];
355
+ const fullIssue = {
356
+ ...issueData,
357
+ path: fullPath
358
+ };
359
+ if (issueData.message !== void 0) {
360
+ return {
361
+ ...issueData,
362
+ path: fullPath,
363
+ message: issueData.message
364
+ };
365
+ }
366
+ let errorMessage = "";
367
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
368
+ for (const map of maps) {
369
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
370
+ }
371
+ return {
372
+ ...issueData,
373
+ path: fullPath,
374
+ message: errorMessage
375
+ };
376
+ };
377
+ function addIssueToContext(ctx, issueData) {
378
+ const overrideMap = getErrorMap();
379
+ const issue = makeIssue({
380
+ issueData,
381
+ data: ctx.data,
382
+ path: ctx.path,
383
+ errorMaps: [
384
+ ctx.common.contextualErrorMap,
385
+ // contextual error map is first priority
386
+ ctx.schemaErrorMap,
387
+ // then schema-bound map if available
388
+ overrideMap,
389
+ // then global override map
390
+ overrideMap === errorMap ? void 0 : errorMap
391
+ // then global default map
392
+ ].filter((x) => !!x)
393
+ });
394
+ ctx.common.issues.push(issue);
395
+ }
396
+ class ParseStatus {
397
+ constructor() {
398
+ this.value = "valid";
399
+ }
400
+ dirty() {
401
+ if (this.value === "valid")
402
+ this.value = "dirty";
403
+ }
404
+ abort() {
405
+ if (this.value !== "aborted")
406
+ this.value = "aborted";
407
+ }
408
+ static mergeArray(status, results) {
409
+ const arrayValue = [];
410
+ for (const s of results) {
411
+ if (s.status === "aborted")
412
+ return INVALID;
413
+ if (s.status === "dirty")
414
+ status.dirty();
415
+ arrayValue.push(s.value);
416
+ }
417
+ return { status: status.value, value: arrayValue };
418
+ }
419
+ static async mergeObjectAsync(status, pairs) {
420
+ const syncPairs = [];
421
+ for (const pair of pairs) {
422
+ const key = await pair.key;
423
+ const value = await pair.value;
424
+ syncPairs.push({
425
+ key,
426
+ value
427
+ });
428
+ }
429
+ return ParseStatus.mergeObjectSync(status, syncPairs);
430
+ }
431
+ static mergeObjectSync(status, pairs) {
432
+ const finalObject = {};
433
+ for (const pair of pairs) {
434
+ const { key, value } = pair;
435
+ if (key.status === "aborted")
436
+ return INVALID;
437
+ if (value.status === "aborted")
438
+ return INVALID;
439
+ if (key.status === "dirty")
440
+ status.dirty();
441
+ if (value.status === "dirty")
442
+ status.dirty();
443
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
444
+ finalObject[key.value] = value.value;
445
+ }
446
+ }
447
+ return { status: status.value, value: finalObject };
448
+ }
449
+ }
450
+ const INVALID = Object.freeze({
451
+ status: "aborted"
452
+ });
453
+ const DIRTY = (value) => ({ status: "dirty", value });
454
+ const OK = (value) => ({ status: "valid", value });
455
+ const isAborted = (x) => x.status === "aborted";
456
+ const isDirty = (x) => x.status === "dirty";
457
+ const isValid = (x) => x.status === "valid";
458
+ const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
459
+ var errorUtil;
460
+ (function(errorUtil2) {
461
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
462
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message == null ? void 0 : message.message;
463
+ })(errorUtil || (errorUtil = {}));
464
+ class ParseInputLazyPath {
465
+ constructor(parent, value, path, key) {
466
+ this._cachedPath = [];
467
+ this.parent = parent;
468
+ this.data = value;
469
+ this._path = path;
470
+ this._key = key;
471
+ }
472
+ get path() {
473
+ if (!this._cachedPath.length) {
474
+ if (Array.isArray(this._key)) {
475
+ this._cachedPath.push(...this._path, ...this._key);
476
+ } else {
477
+ this._cachedPath.push(...this._path, this._key);
478
+ }
479
+ }
480
+ return this._cachedPath;
481
+ }
482
+ }
483
+ const handleResult = (ctx, result) => {
484
+ if (isValid(result)) {
485
+ return { success: true, data: result.value };
486
+ } else {
487
+ if (!ctx.common.issues.length) {
488
+ throw new Error("Validation failed but no issues detected.");
489
+ }
490
+ return {
491
+ success: false,
492
+ get error() {
493
+ if (this._error)
494
+ return this._error;
495
+ const error = new ZodError(ctx.common.issues);
496
+ this._error = error;
497
+ return this._error;
498
+ }
499
+ };
500
+ }
501
+ };
502
+ function processCreateParams(params) {
503
+ if (!params)
504
+ return {};
505
+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
506
+ if (errorMap2 && (invalid_type_error || required_error)) {
507
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
508
+ }
509
+ if (errorMap2)
510
+ return { errorMap: errorMap2, description };
511
+ const customMap = (iss, ctx) => {
512
+ const { message } = params;
513
+ if (iss.code === "invalid_enum_value") {
514
+ return { message: message ?? ctx.defaultError };
515
+ }
516
+ if (typeof ctx.data === "undefined") {
517
+ return { message: message ?? required_error ?? ctx.defaultError };
518
+ }
519
+ if (iss.code !== "invalid_type")
520
+ return { message: ctx.defaultError };
521
+ return { message: message ?? invalid_type_error ?? ctx.defaultError };
522
+ };
523
+ return { errorMap: customMap, description };
524
+ }
525
+ class ZodType {
526
+ get description() {
527
+ return this._def.description;
528
+ }
529
+ _getType(input) {
530
+ return getParsedType(input.data);
531
+ }
532
+ _getOrReturnCtx(input, ctx) {
533
+ return ctx || {
534
+ common: input.parent.common,
535
+ data: input.data,
536
+ parsedType: getParsedType(input.data),
537
+ schemaErrorMap: this._def.errorMap,
538
+ path: input.path,
539
+ parent: input.parent
540
+ };
541
+ }
542
+ _processInputParams(input) {
543
+ return {
544
+ status: new ParseStatus(),
545
+ ctx: {
546
+ common: input.parent.common,
547
+ data: input.data,
548
+ parsedType: getParsedType(input.data),
549
+ schemaErrorMap: this._def.errorMap,
550
+ path: input.path,
551
+ parent: input.parent
552
+ }
553
+ };
554
+ }
555
+ _parseSync(input) {
556
+ const result = this._parse(input);
557
+ if (isAsync(result)) {
558
+ throw new Error("Synchronous parse encountered promise.");
559
+ }
560
+ return result;
561
+ }
562
+ _parseAsync(input) {
563
+ const result = this._parse(input);
564
+ return Promise.resolve(result);
565
+ }
566
+ parse(data, params) {
567
+ const result = this.safeParse(data, params);
568
+ if (result.success)
569
+ return result.data;
570
+ throw result.error;
571
+ }
572
+ safeParse(data, params) {
573
+ const ctx = {
574
+ common: {
575
+ issues: [],
576
+ async: (params == null ? void 0 : params.async) ?? false,
577
+ contextualErrorMap: params == null ? void 0 : params.errorMap
578
+ },
579
+ path: (params == null ? void 0 : params.path) || [],
580
+ schemaErrorMap: this._def.errorMap,
581
+ parent: null,
582
+ data,
583
+ parsedType: getParsedType(data)
584
+ };
585
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
586
+ return handleResult(ctx, result);
587
+ }
588
+ "~validate"(data) {
589
+ var _a, _b;
590
+ const ctx = {
591
+ common: {
592
+ issues: [],
593
+ async: !!this["~standard"].async
594
+ },
595
+ path: [],
596
+ schemaErrorMap: this._def.errorMap,
597
+ parent: null,
598
+ data,
599
+ parsedType: getParsedType(data)
600
+ };
601
+ if (!this["~standard"].async) {
602
+ try {
603
+ const result = this._parseSync({ data, path: [], parent: ctx });
604
+ return isValid(result) ? {
605
+ value: result.value
606
+ } : {
607
+ issues: ctx.common.issues
608
+ };
609
+ } catch (err) {
610
+ if ((_b = (_a = err == null ? void 0 : err.message) == null ? void 0 : _a.toLowerCase()) == null ? void 0 : _b.includes("encountered")) {
611
+ this["~standard"].async = true;
612
+ }
613
+ ctx.common = {
614
+ issues: [],
615
+ async: true
616
+ };
617
+ }
618
+ }
619
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
620
+ value: result.value
621
+ } : {
622
+ issues: ctx.common.issues
623
+ });
624
+ }
625
+ async parseAsync(data, params) {
626
+ const result = await this.safeParseAsync(data, params);
627
+ if (result.success)
628
+ return result.data;
629
+ throw result.error;
630
+ }
631
+ async safeParseAsync(data, params) {
632
+ const ctx = {
633
+ common: {
634
+ issues: [],
635
+ contextualErrorMap: params == null ? void 0 : params.errorMap,
636
+ async: true
637
+ },
638
+ path: (params == null ? void 0 : params.path) || [],
639
+ schemaErrorMap: this._def.errorMap,
640
+ parent: null,
641
+ data,
642
+ parsedType: getParsedType(data)
643
+ };
644
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
645
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
646
+ return handleResult(ctx, result);
647
+ }
648
+ refine(check, message) {
649
+ const getIssueProperties = (val) => {
650
+ if (typeof message === "string" || typeof message === "undefined") {
651
+ return { message };
652
+ } else if (typeof message === "function") {
653
+ return message(val);
654
+ } else {
655
+ return message;
656
+ }
657
+ };
658
+ return this._refinement((val, ctx) => {
659
+ const result = check(val);
660
+ const setError = () => ctx.addIssue({
661
+ code: ZodIssueCode.custom,
662
+ ...getIssueProperties(val)
663
+ });
664
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
665
+ return result.then((data) => {
666
+ if (!data) {
667
+ setError();
668
+ return false;
669
+ } else {
670
+ return true;
671
+ }
672
+ });
673
+ }
674
+ if (!result) {
675
+ setError();
676
+ return false;
677
+ } else {
678
+ return true;
679
+ }
680
+ });
681
+ }
682
+ refinement(check, refinementData) {
683
+ return this._refinement((val, ctx) => {
684
+ if (!check(val)) {
685
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
686
+ return false;
687
+ } else {
688
+ return true;
689
+ }
690
+ });
691
+ }
692
+ _refinement(refinement) {
693
+ return new ZodEffects({
694
+ schema: this,
695
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
696
+ effect: { type: "refinement", refinement }
697
+ });
698
+ }
699
+ superRefine(refinement) {
700
+ return this._refinement(refinement);
701
+ }
702
+ constructor(def) {
703
+ this.spa = this.safeParseAsync;
704
+ this._def = def;
705
+ this.parse = this.parse.bind(this);
706
+ this.safeParse = this.safeParse.bind(this);
707
+ this.parseAsync = this.parseAsync.bind(this);
708
+ this.safeParseAsync = this.safeParseAsync.bind(this);
709
+ this.spa = this.spa.bind(this);
710
+ this.refine = this.refine.bind(this);
711
+ this.refinement = this.refinement.bind(this);
712
+ this.superRefine = this.superRefine.bind(this);
713
+ this.optional = this.optional.bind(this);
714
+ this.nullable = this.nullable.bind(this);
715
+ this.nullish = this.nullish.bind(this);
716
+ this.array = this.array.bind(this);
717
+ this.promise = this.promise.bind(this);
718
+ this.or = this.or.bind(this);
719
+ this.and = this.and.bind(this);
720
+ this.transform = this.transform.bind(this);
721
+ this.brand = this.brand.bind(this);
722
+ this.default = this.default.bind(this);
723
+ this.catch = this.catch.bind(this);
724
+ this.describe = this.describe.bind(this);
725
+ this.pipe = this.pipe.bind(this);
726
+ this.readonly = this.readonly.bind(this);
727
+ this.isNullable = this.isNullable.bind(this);
728
+ this.isOptional = this.isOptional.bind(this);
729
+ this["~standard"] = {
730
+ version: 1,
731
+ vendor: "zod",
732
+ validate: (data) => this["~validate"](data)
733
+ };
734
+ }
735
+ optional() {
736
+ return ZodOptional.create(this, this._def);
737
+ }
738
+ nullable() {
739
+ return ZodNullable.create(this, this._def);
740
+ }
741
+ nullish() {
742
+ return this.nullable().optional();
743
+ }
744
+ array() {
745
+ return ZodArray.create(this);
746
+ }
747
+ promise() {
748
+ return ZodPromise.create(this, this._def);
749
+ }
750
+ or(option) {
751
+ return ZodUnion.create([this, option], this._def);
752
+ }
753
+ and(incoming) {
754
+ return ZodIntersection.create(this, incoming, this._def);
755
+ }
756
+ transform(transform) {
757
+ return new ZodEffects({
758
+ ...processCreateParams(this._def),
759
+ schema: this,
760
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
761
+ effect: { type: "transform", transform }
762
+ });
763
+ }
764
+ default(def) {
765
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
766
+ return new ZodDefault({
767
+ ...processCreateParams(this._def),
768
+ innerType: this,
769
+ defaultValue: defaultValueFunc,
770
+ typeName: ZodFirstPartyTypeKind.ZodDefault
771
+ });
772
+ }
773
+ brand() {
774
+ return new ZodBranded({
775
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
776
+ type: this,
777
+ ...processCreateParams(this._def)
778
+ });
779
+ }
780
+ catch(def) {
781
+ const catchValueFunc = typeof def === "function" ? def : () => def;
782
+ return new ZodCatch({
783
+ ...processCreateParams(this._def),
784
+ innerType: this,
785
+ catchValue: catchValueFunc,
786
+ typeName: ZodFirstPartyTypeKind.ZodCatch
787
+ });
788
+ }
789
+ describe(description) {
790
+ const This = this.constructor;
791
+ return new This({
792
+ ...this._def,
793
+ description
794
+ });
795
+ }
796
+ pipe(target) {
797
+ return ZodPipeline.create(this, target);
798
+ }
799
+ readonly() {
800
+ return ZodReadonly.create(this);
801
+ }
802
+ isOptional() {
803
+ return this.safeParse(void 0).success;
804
+ }
805
+ isNullable() {
806
+ return this.safeParse(null).success;
807
+ }
808
+ }
809
+ const cuidRegex = /^c[^\s-]{8,}$/i;
810
+ const cuid2Regex = /^[0-9a-z]+$/;
811
+ const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
812
+ const 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;
813
+ const nanoidRegex = /^[a-z0-9_-]{21}$/i;
814
+ const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
815
+ const 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)?)??$/;
816
+ const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
817
+ const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
818
+ let emojiRegex;
819
+ const 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])$/;
820
+ const 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])$/;
821
+ const 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]))$/;
822
+ const 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])$/;
823
+ const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
824
+ const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
825
+ const 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])))`;
826
+ const dateRegex = new RegExp(`^${dateRegexSource}$`);
827
+ function timeRegexSource(args) {
828
+ let secondsRegexSource = `[0-5]\\d`;
829
+ if (args.precision) {
830
+ secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
831
+ } else if (args.precision == null) {
832
+ secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
833
+ }
834
+ const secondsQuantifier = args.precision ? "+" : "?";
835
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
836
+ }
837
+ function timeRegex(args) {
838
+ return new RegExp(`^${timeRegexSource(args)}$`);
839
+ }
840
+ function datetimeRegex(args) {
841
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
842
+ const opts = [];
843
+ opts.push(args.local ? `Z?` : `Z`);
844
+ if (args.offset)
845
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
846
+ regex = `${regex}(${opts.join("|")})`;
847
+ return new RegExp(`^${regex}$`);
848
+ }
849
+ function isValidIP(ip, version) {
850
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
851
+ return true;
852
+ }
853
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
854
+ return true;
855
+ }
856
+ return false;
857
+ }
858
+ function isValidJWT(jwt, alg) {
859
+ if (!jwtRegex.test(jwt))
860
+ return false;
861
+ try {
862
+ const [header] = jwt.split(".");
863
+ if (!header)
864
+ return false;
865
+ const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
866
+ const decoded = JSON.parse(atob(base64));
867
+ if (typeof decoded !== "object" || decoded === null)
868
+ return false;
869
+ if ("typ" in decoded && (decoded == null ? void 0 : decoded.typ) !== "JWT")
870
+ return false;
871
+ if (!decoded.alg)
872
+ return false;
873
+ if (alg && decoded.alg !== alg)
874
+ return false;
875
+ return true;
876
+ } catch {
877
+ return false;
878
+ }
879
+ }
880
+ function isValidCidr(ip, version) {
881
+ if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
882
+ return true;
883
+ }
884
+ if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
885
+ return true;
886
+ }
887
+ return false;
888
+ }
889
+ class ZodString extends ZodType {
890
+ _parse(input) {
891
+ if (this._def.coerce) {
892
+ input.data = String(input.data);
893
+ }
894
+ const parsedType = this._getType(input);
895
+ if (parsedType !== ZodParsedType.string) {
896
+ const ctx2 = this._getOrReturnCtx(input);
897
+ addIssueToContext(ctx2, {
898
+ code: ZodIssueCode.invalid_type,
899
+ expected: ZodParsedType.string,
900
+ received: ctx2.parsedType
901
+ });
902
+ return INVALID;
903
+ }
904
+ const status = new ParseStatus();
905
+ let ctx = void 0;
906
+ for (const check of this._def.checks) {
907
+ if (check.kind === "min") {
908
+ if (input.data.length < check.value) {
909
+ ctx = this._getOrReturnCtx(input, ctx);
910
+ addIssueToContext(ctx, {
911
+ code: ZodIssueCode.too_small,
912
+ minimum: check.value,
913
+ type: "string",
914
+ inclusive: true,
915
+ exact: false,
916
+ message: check.message
917
+ });
918
+ status.dirty();
919
+ }
920
+ } else if (check.kind === "max") {
921
+ if (input.data.length > check.value) {
922
+ ctx = this._getOrReturnCtx(input, ctx);
923
+ addIssueToContext(ctx, {
924
+ code: ZodIssueCode.too_big,
925
+ maximum: check.value,
926
+ type: "string",
927
+ inclusive: true,
928
+ exact: false,
929
+ message: check.message
930
+ });
931
+ status.dirty();
932
+ }
933
+ } else if (check.kind === "length") {
934
+ const tooBig = input.data.length > check.value;
935
+ const tooSmall = input.data.length < check.value;
936
+ if (tooBig || tooSmall) {
937
+ ctx = this._getOrReturnCtx(input, ctx);
938
+ if (tooBig) {
939
+ addIssueToContext(ctx, {
940
+ code: ZodIssueCode.too_big,
941
+ maximum: check.value,
942
+ type: "string",
943
+ inclusive: true,
944
+ exact: true,
945
+ message: check.message
946
+ });
947
+ } else if (tooSmall) {
948
+ addIssueToContext(ctx, {
949
+ code: ZodIssueCode.too_small,
950
+ minimum: check.value,
951
+ type: "string",
952
+ inclusive: true,
953
+ exact: true,
954
+ message: check.message
955
+ });
956
+ }
957
+ status.dirty();
958
+ }
959
+ } else if (check.kind === "email") {
960
+ if (!emailRegex.test(input.data)) {
961
+ ctx = this._getOrReturnCtx(input, ctx);
962
+ addIssueToContext(ctx, {
963
+ validation: "email",
964
+ code: ZodIssueCode.invalid_string,
965
+ message: check.message
966
+ });
967
+ status.dirty();
968
+ }
969
+ } else if (check.kind === "emoji") {
970
+ if (!emojiRegex) {
971
+ emojiRegex = new RegExp(_emojiRegex, "u");
972
+ }
973
+ if (!emojiRegex.test(input.data)) {
974
+ ctx = this._getOrReturnCtx(input, ctx);
975
+ addIssueToContext(ctx, {
976
+ validation: "emoji",
977
+ code: ZodIssueCode.invalid_string,
978
+ message: check.message
979
+ });
980
+ status.dirty();
981
+ }
982
+ } else if (check.kind === "uuid") {
983
+ if (!uuidRegex.test(input.data)) {
984
+ ctx = this._getOrReturnCtx(input, ctx);
985
+ addIssueToContext(ctx, {
986
+ validation: "uuid",
987
+ code: ZodIssueCode.invalid_string,
988
+ message: check.message
989
+ });
990
+ status.dirty();
991
+ }
992
+ } else if (check.kind === "nanoid") {
993
+ if (!nanoidRegex.test(input.data)) {
994
+ ctx = this._getOrReturnCtx(input, ctx);
995
+ addIssueToContext(ctx, {
996
+ validation: "nanoid",
997
+ code: ZodIssueCode.invalid_string,
998
+ message: check.message
999
+ });
1000
+ status.dirty();
1001
+ }
1002
+ } else if (check.kind === "cuid") {
1003
+ if (!cuidRegex.test(input.data)) {
1004
+ ctx = this._getOrReturnCtx(input, ctx);
1005
+ addIssueToContext(ctx, {
1006
+ validation: "cuid",
1007
+ code: ZodIssueCode.invalid_string,
1008
+ message: check.message
1009
+ });
1010
+ status.dirty();
1011
+ }
1012
+ } else if (check.kind === "cuid2") {
1013
+ if (!cuid2Regex.test(input.data)) {
1014
+ ctx = this._getOrReturnCtx(input, ctx);
1015
+ addIssueToContext(ctx, {
1016
+ validation: "cuid2",
1017
+ code: ZodIssueCode.invalid_string,
1018
+ message: check.message
1019
+ });
1020
+ status.dirty();
1021
+ }
1022
+ } else if (check.kind === "ulid") {
1023
+ if (!ulidRegex.test(input.data)) {
1024
+ ctx = this._getOrReturnCtx(input, ctx);
1025
+ addIssueToContext(ctx, {
1026
+ validation: "ulid",
1027
+ code: ZodIssueCode.invalid_string,
1028
+ message: check.message
1029
+ });
1030
+ status.dirty();
1031
+ }
1032
+ } else if (check.kind === "url") {
1033
+ try {
1034
+ new URL(input.data);
1035
+ } catch {
1036
+ ctx = this._getOrReturnCtx(input, ctx);
1037
+ addIssueToContext(ctx, {
1038
+ validation: "url",
1039
+ code: ZodIssueCode.invalid_string,
1040
+ message: check.message
1041
+ });
1042
+ status.dirty();
1043
+ }
1044
+ } else if (check.kind === "regex") {
1045
+ check.regex.lastIndex = 0;
1046
+ const testResult = check.regex.test(input.data);
1047
+ if (!testResult) {
1048
+ ctx = this._getOrReturnCtx(input, ctx);
1049
+ addIssueToContext(ctx, {
1050
+ validation: "regex",
1051
+ code: ZodIssueCode.invalid_string,
1052
+ message: check.message
1053
+ });
1054
+ status.dirty();
1055
+ }
1056
+ } else if (check.kind === "trim") {
1057
+ input.data = input.data.trim();
1058
+ } else if (check.kind === "includes") {
1059
+ if (!input.data.includes(check.value, check.position)) {
1060
+ ctx = this._getOrReturnCtx(input, ctx);
1061
+ addIssueToContext(ctx, {
1062
+ code: ZodIssueCode.invalid_string,
1063
+ validation: { includes: check.value, position: check.position },
1064
+ message: check.message
1065
+ });
1066
+ status.dirty();
1067
+ }
1068
+ } else if (check.kind === "toLowerCase") {
1069
+ input.data = input.data.toLowerCase();
1070
+ } else if (check.kind === "toUpperCase") {
1071
+ input.data = input.data.toUpperCase();
1072
+ } else if (check.kind === "startsWith") {
1073
+ if (!input.data.startsWith(check.value)) {
1074
+ ctx = this._getOrReturnCtx(input, ctx);
1075
+ addIssueToContext(ctx, {
1076
+ code: ZodIssueCode.invalid_string,
1077
+ validation: { startsWith: check.value },
1078
+ message: check.message
1079
+ });
1080
+ status.dirty();
1081
+ }
1082
+ } else if (check.kind === "endsWith") {
1083
+ if (!input.data.endsWith(check.value)) {
1084
+ ctx = this._getOrReturnCtx(input, ctx);
1085
+ addIssueToContext(ctx, {
1086
+ code: ZodIssueCode.invalid_string,
1087
+ validation: { endsWith: check.value },
1088
+ message: check.message
1089
+ });
1090
+ status.dirty();
1091
+ }
1092
+ } else if (check.kind === "datetime") {
1093
+ const regex = datetimeRegex(check);
1094
+ if (!regex.test(input.data)) {
1095
+ ctx = this._getOrReturnCtx(input, ctx);
1096
+ addIssueToContext(ctx, {
1097
+ code: ZodIssueCode.invalid_string,
1098
+ validation: "datetime",
1099
+ message: check.message
1100
+ });
1101
+ status.dirty();
1102
+ }
1103
+ } else if (check.kind === "date") {
1104
+ const regex = dateRegex;
1105
+ if (!regex.test(input.data)) {
1106
+ ctx = this._getOrReturnCtx(input, ctx);
1107
+ addIssueToContext(ctx, {
1108
+ code: ZodIssueCode.invalid_string,
1109
+ validation: "date",
1110
+ message: check.message
1111
+ });
1112
+ status.dirty();
1113
+ }
1114
+ } else if (check.kind === "time") {
1115
+ const regex = timeRegex(check);
1116
+ if (!regex.test(input.data)) {
1117
+ ctx = this._getOrReturnCtx(input, ctx);
1118
+ addIssueToContext(ctx, {
1119
+ code: ZodIssueCode.invalid_string,
1120
+ validation: "time",
1121
+ message: check.message
1122
+ });
1123
+ status.dirty();
1124
+ }
1125
+ } else if (check.kind === "duration") {
1126
+ if (!durationRegex.test(input.data)) {
1127
+ ctx = this._getOrReturnCtx(input, ctx);
1128
+ addIssueToContext(ctx, {
1129
+ validation: "duration",
1130
+ code: ZodIssueCode.invalid_string,
1131
+ message: check.message
1132
+ });
1133
+ status.dirty();
1134
+ }
1135
+ } else if (check.kind === "ip") {
1136
+ if (!isValidIP(input.data, check.version)) {
1137
+ ctx = this._getOrReturnCtx(input, ctx);
1138
+ addIssueToContext(ctx, {
1139
+ validation: "ip",
1140
+ code: ZodIssueCode.invalid_string,
1141
+ message: check.message
1142
+ });
1143
+ status.dirty();
1144
+ }
1145
+ } else if (check.kind === "jwt") {
1146
+ if (!isValidJWT(input.data, check.alg)) {
1147
+ ctx = this._getOrReturnCtx(input, ctx);
1148
+ addIssueToContext(ctx, {
1149
+ validation: "jwt",
1150
+ code: ZodIssueCode.invalid_string,
1151
+ message: check.message
1152
+ });
1153
+ status.dirty();
1154
+ }
1155
+ } else if (check.kind === "cidr") {
1156
+ if (!isValidCidr(input.data, check.version)) {
1157
+ ctx = this._getOrReturnCtx(input, ctx);
1158
+ addIssueToContext(ctx, {
1159
+ validation: "cidr",
1160
+ code: ZodIssueCode.invalid_string,
1161
+ message: check.message
1162
+ });
1163
+ status.dirty();
1164
+ }
1165
+ } else if (check.kind === "base64") {
1166
+ if (!base64Regex.test(input.data)) {
1167
+ ctx = this._getOrReturnCtx(input, ctx);
1168
+ addIssueToContext(ctx, {
1169
+ validation: "base64",
1170
+ code: ZodIssueCode.invalid_string,
1171
+ message: check.message
1172
+ });
1173
+ status.dirty();
1174
+ }
1175
+ } else if (check.kind === "base64url") {
1176
+ if (!base64urlRegex.test(input.data)) {
1177
+ ctx = this._getOrReturnCtx(input, ctx);
1178
+ addIssueToContext(ctx, {
1179
+ validation: "base64url",
1180
+ code: ZodIssueCode.invalid_string,
1181
+ message: check.message
1182
+ });
1183
+ status.dirty();
1184
+ }
1185
+ } else {
1186
+ util.assertNever(check);
1187
+ }
1188
+ }
1189
+ return { status: status.value, value: input.data };
1190
+ }
1191
+ _regex(regex, validation, message) {
1192
+ return this.refinement((data) => regex.test(data), {
1193
+ validation,
1194
+ code: ZodIssueCode.invalid_string,
1195
+ ...errorUtil.errToObj(message)
1196
+ });
1197
+ }
1198
+ _addCheck(check) {
1199
+ return new ZodString({
1200
+ ...this._def,
1201
+ checks: [...this._def.checks, check]
1202
+ });
1203
+ }
1204
+ email(message) {
1205
+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
1206
+ }
1207
+ url(message) {
1208
+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
1209
+ }
1210
+ emoji(message) {
1211
+ return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
1212
+ }
1213
+ uuid(message) {
1214
+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1215
+ }
1216
+ nanoid(message) {
1217
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1218
+ }
1219
+ cuid(message) {
1220
+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1221
+ }
1222
+ cuid2(message) {
1223
+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
1224
+ }
1225
+ ulid(message) {
1226
+ return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1227
+ }
1228
+ base64(message) {
1229
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1230
+ }
1231
+ base64url(message) {
1232
+ return this._addCheck({
1233
+ kind: "base64url",
1234
+ ...errorUtil.errToObj(message)
1235
+ });
1236
+ }
1237
+ jwt(options) {
1238
+ return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
1239
+ }
1240
+ ip(options) {
1241
+ return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1242
+ }
1243
+ cidr(options) {
1244
+ return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
1245
+ }
1246
+ datetime(options) {
1247
+ if (typeof options === "string") {
1248
+ return this._addCheck({
1249
+ kind: "datetime",
1250
+ precision: null,
1251
+ offset: false,
1252
+ local: false,
1253
+ message: options
1254
+ });
1255
+ }
1256
+ return this._addCheck({
1257
+ kind: "datetime",
1258
+ precision: typeof (options == null ? void 0 : options.precision) === "undefined" ? null : options == null ? void 0 : options.precision,
1259
+ offset: (options == null ? void 0 : options.offset) ?? false,
1260
+ local: (options == null ? void 0 : options.local) ?? false,
1261
+ ...errorUtil.errToObj(options == null ? void 0 : options.message)
1262
+ });
1263
+ }
1264
+ date(message) {
1265
+ return this._addCheck({ kind: "date", message });
1266
+ }
1267
+ time(options) {
1268
+ if (typeof options === "string") {
1269
+ return this._addCheck({
1270
+ kind: "time",
1271
+ precision: null,
1272
+ message: options
1273
+ });
1274
+ }
1275
+ return this._addCheck({
1276
+ kind: "time",
1277
+ precision: typeof (options == null ? void 0 : options.precision) === "undefined" ? null : options == null ? void 0 : options.precision,
1278
+ ...errorUtil.errToObj(options == null ? void 0 : options.message)
1279
+ });
1280
+ }
1281
+ duration(message) {
1282
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
1283
+ }
1284
+ regex(regex, message) {
1285
+ return this._addCheck({
1286
+ kind: "regex",
1287
+ regex,
1288
+ ...errorUtil.errToObj(message)
1289
+ });
1290
+ }
1291
+ includes(value, options) {
1292
+ return this._addCheck({
1293
+ kind: "includes",
1294
+ value,
1295
+ position: options == null ? void 0 : options.position,
1296
+ ...errorUtil.errToObj(options == null ? void 0 : options.message)
1297
+ });
1298
+ }
1299
+ startsWith(value, message) {
1300
+ return this._addCheck({
1301
+ kind: "startsWith",
1302
+ value,
1303
+ ...errorUtil.errToObj(message)
1304
+ });
1305
+ }
1306
+ endsWith(value, message) {
1307
+ return this._addCheck({
1308
+ kind: "endsWith",
1309
+ value,
1310
+ ...errorUtil.errToObj(message)
1311
+ });
1312
+ }
1313
+ min(minLength, message) {
1314
+ return this._addCheck({
1315
+ kind: "min",
1316
+ value: minLength,
1317
+ ...errorUtil.errToObj(message)
1318
+ });
1319
+ }
1320
+ max(maxLength, message) {
1321
+ return this._addCheck({
1322
+ kind: "max",
1323
+ value: maxLength,
1324
+ ...errorUtil.errToObj(message)
1325
+ });
1326
+ }
1327
+ length(len, message) {
1328
+ return this._addCheck({
1329
+ kind: "length",
1330
+ value: len,
1331
+ ...errorUtil.errToObj(message)
1332
+ });
1333
+ }
1334
+ /**
1335
+ * Equivalent to `.min(1)`
1336
+ */
1337
+ nonempty(message) {
1338
+ return this.min(1, errorUtil.errToObj(message));
1339
+ }
1340
+ trim() {
1341
+ return new ZodString({
1342
+ ...this._def,
1343
+ checks: [...this._def.checks, { kind: "trim" }]
1344
+ });
1345
+ }
1346
+ toLowerCase() {
1347
+ return new ZodString({
1348
+ ...this._def,
1349
+ checks: [...this._def.checks, { kind: "toLowerCase" }]
1350
+ });
1351
+ }
1352
+ toUpperCase() {
1353
+ return new ZodString({
1354
+ ...this._def,
1355
+ checks: [...this._def.checks, { kind: "toUpperCase" }]
1356
+ });
1357
+ }
1358
+ get isDatetime() {
1359
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
1360
+ }
1361
+ get isDate() {
1362
+ return !!this._def.checks.find((ch) => ch.kind === "date");
1363
+ }
1364
+ get isTime() {
1365
+ return !!this._def.checks.find((ch) => ch.kind === "time");
1366
+ }
1367
+ get isDuration() {
1368
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
1369
+ }
1370
+ get isEmail() {
1371
+ return !!this._def.checks.find((ch) => ch.kind === "email");
1372
+ }
1373
+ get isURL() {
1374
+ return !!this._def.checks.find((ch) => ch.kind === "url");
1375
+ }
1376
+ get isEmoji() {
1377
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
1378
+ }
1379
+ get isUUID() {
1380
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
1381
+ }
1382
+ get isNANOID() {
1383
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1384
+ }
1385
+ get isCUID() {
1386
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
1387
+ }
1388
+ get isCUID2() {
1389
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1390
+ }
1391
+ get isULID() {
1392
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
1393
+ }
1394
+ get isIP() {
1395
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
1396
+ }
1397
+ get isCIDR() {
1398
+ return !!this._def.checks.find((ch) => ch.kind === "cidr");
1399
+ }
1400
+ get isBase64() {
1401
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
1402
+ }
1403
+ get isBase64url() {
1404
+ return !!this._def.checks.find((ch) => ch.kind === "base64url");
1405
+ }
1406
+ get minLength() {
1407
+ let min = null;
1408
+ for (const ch of this._def.checks) {
1409
+ if (ch.kind === "min") {
1410
+ if (min === null || ch.value > min)
1411
+ min = ch.value;
1412
+ }
1413
+ }
1414
+ return min;
1415
+ }
1416
+ get maxLength() {
1417
+ let max = null;
1418
+ for (const ch of this._def.checks) {
1419
+ if (ch.kind === "max") {
1420
+ if (max === null || ch.value < max)
1421
+ max = ch.value;
1422
+ }
1423
+ }
1424
+ return max;
1425
+ }
1426
+ }
1427
+ ZodString.create = (params) => {
1428
+ return new ZodString({
1429
+ checks: [],
1430
+ typeName: ZodFirstPartyTypeKind.ZodString,
1431
+ coerce: (params == null ? void 0 : params.coerce) ?? false,
1432
+ ...processCreateParams(params)
1433
+ });
1434
+ };
1435
+ function floatSafeRemainder(val, step) {
1436
+ const valDecCount = (val.toString().split(".")[1] || "").length;
1437
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
1438
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1439
+ const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
1440
+ const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
1441
+ return valInt % stepInt / 10 ** decCount;
1442
+ }
1443
+ class ZodNumber extends ZodType {
1444
+ constructor() {
1445
+ super(...arguments);
1446
+ this.min = this.gte;
1447
+ this.max = this.lte;
1448
+ this.step = this.multipleOf;
1449
+ }
1450
+ _parse(input) {
1451
+ if (this._def.coerce) {
1452
+ input.data = Number(input.data);
1453
+ }
1454
+ const parsedType = this._getType(input);
1455
+ if (parsedType !== ZodParsedType.number) {
1456
+ const ctx2 = this._getOrReturnCtx(input);
1457
+ addIssueToContext(ctx2, {
1458
+ code: ZodIssueCode.invalid_type,
1459
+ expected: ZodParsedType.number,
1460
+ received: ctx2.parsedType
1461
+ });
1462
+ return INVALID;
1463
+ }
1464
+ let ctx = void 0;
1465
+ const status = new ParseStatus();
1466
+ for (const check of this._def.checks) {
1467
+ if (check.kind === "int") {
1468
+ if (!util.isInteger(input.data)) {
1469
+ ctx = this._getOrReturnCtx(input, ctx);
1470
+ addIssueToContext(ctx, {
1471
+ code: ZodIssueCode.invalid_type,
1472
+ expected: "integer",
1473
+ received: "float",
1474
+ message: check.message
1475
+ });
1476
+ status.dirty();
1477
+ }
1478
+ } else if (check.kind === "min") {
1479
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1480
+ if (tooSmall) {
1481
+ ctx = this._getOrReturnCtx(input, ctx);
1482
+ addIssueToContext(ctx, {
1483
+ code: ZodIssueCode.too_small,
1484
+ minimum: check.value,
1485
+ type: "number",
1486
+ inclusive: check.inclusive,
1487
+ exact: false,
1488
+ message: check.message
1489
+ });
1490
+ status.dirty();
1491
+ }
1492
+ } else if (check.kind === "max") {
1493
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1494
+ if (tooBig) {
1495
+ ctx = this._getOrReturnCtx(input, ctx);
1496
+ addIssueToContext(ctx, {
1497
+ code: ZodIssueCode.too_big,
1498
+ maximum: check.value,
1499
+ type: "number",
1500
+ inclusive: check.inclusive,
1501
+ exact: false,
1502
+ message: check.message
1503
+ });
1504
+ status.dirty();
1505
+ }
1506
+ } else if (check.kind === "multipleOf") {
1507
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
1508
+ ctx = this._getOrReturnCtx(input, ctx);
1509
+ addIssueToContext(ctx, {
1510
+ code: ZodIssueCode.not_multiple_of,
1511
+ multipleOf: check.value,
1512
+ message: check.message
1513
+ });
1514
+ status.dirty();
1515
+ }
1516
+ } else if (check.kind === "finite") {
1517
+ if (!Number.isFinite(input.data)) {
1518
+ ctx = this._getOrReturnCtx(input, ctx);
1519
+ addIssueToContext(ctx, {
1520
+ code: ZodIssueCode.not_finite,
1521
+ message: check.message
1522
+ });
1523
+ status.dirty();
1524
+ }
1525
+ } else {
1526
+ util.assertNever(check);
1527
+ }
1528
+ }
1529
+ return { status: status.value, value: input.data };
1530
+ }
1531
+ gte(value, message) {
1532
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1533
+ }
1534
+ gt(value, message) {
1535
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1536
+ }
1537
+ lte(value, message) {
1538
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1539
+ }
1540
+ lt(value, message) {
1541
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1542
+ }
1543
+ setLimit(kind, value, inclusive, message) {
1544
+ return new ZodNumber({
1545
+ ...this._def,
1546
+ checks: [
1547
+ ...this._def.checks,
1548
+ {
1549
+ kind,
1550
+ value,
1551
+ inclusive,
1552
+ message: errorUtil.toString(message)
1553
+ }
1554
+ ]
1555
+ });
1556
+ }
1557
+ _addCheck(check) {
1558
+ return new ZodNumber({
1559
+ ...this._def,
1560
+ checks: [...this._def.checks, check]
1561
+ });
1562
+ }
1563
+ int(message) {
1564
+ return this._addCheck({
1565
+ kind: "int",
1566
+ message: errorUtil.toString(message)
1567
+ });
1568
+ }
1569
+ positive(message) {
1570
+ return this._addCheck({
1571
+ kind: "min",
1572
+ value: 0,
1573
+ inclusive: false,
1574
+ message: errorUtil.toString(message)
1575
+ });
1576
+ }
1577
+ negative(message) {
1578
+ return this._addCheck({
1579
+ kind: "max",
1580
+ value: 0,
1581
+ inclusive: false,
1582
+ message: errorUtil.toString(message)
1583
+ });
1584
+ }
1585
+ nonpositive(message) {
1586
+ return this._addCheck({
1587
+ kind: "max",
1588
+ value: 0,
1589
+ inclusive: true,
1590
+ message: errorUtil.toString(message)
1591
+ });
1592
+ }
1593
+ nonnegative(message) {
1594
+ return this._addCheck({
1595
+ kind: "min",
1596
+ value: 0,
1597
+ inclusive: true,
1598
+ message: errorUtil.toString(message)
1599
+ });
1600
+ }
1601
+ multipleOf(value, message) {
1602
+ return this._addCheck({
1603
+ kind: "multipleOf",
1604
+ value,
1605
+ message: errorUtil.toString(message)
1606
+ });
1607
+ }
1608
+ finite(message) {
1609
+ return this._addCheck({
1610
+ kind: "finite",
1611
+ message: errorUtil.toString(message)
1612
+ });
1613
+ }
1614
+ safe(message) {
1615
+ return this._addCheck({
1616
+ kind: "min",
1617
+ inclusive: true,
1618
+ value: Number.MIN_SAFE_INTEGER,
1619
+ message: errorUtil.toString(message)
1620
+ })._addCheck({
1621
+ kind: "max",
1622
+ inclusive: true,
1623
+ value: Number.MAX_SAFE_INTEGER,
1624
+ message: errorUtil.toString(message)
1625
+ });
1626
+ }
1627
+ get minValue() {
1628
+ let min = null;
1629
+ for (const ch of this._def.checks) {
1630
+ if (ch.kind === "min") {
1631
+ if (min === null || ch.value > min)
1632
+ min = ch.value;
1633
+ }
1634
+ }
1635
+ return min;
1636
+ }
1637
+ get maxValue() {
1638
+ let max = null;
1639
+ for (const ch of this._def.checks) {
1640
+ if (ch.kind === "max") {
1641
+ if (max === null || ch.value < max)
1642
+ max = ch.value;
1643
+ }
1644
+ }
1645
+ return max;
1646
+ }
1647
+ get isInt() {
1648
+ return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
1649
+ }
1650
+ get isFinite() {
1651
+ let max = null;
1652
+ let min = null;
1653
+ for (const ch of this._def.checks) {
1654
+ if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
1655
+ return true;
1656
+ } else if (ch.kind === "min") {
1657
+ if (min === null || ch.value > min)
1658
+ min = ch.value;
1659
+ } else if (ch.kind === "max") {
1660
+ if (max === null || ch.value < max)
1661
+ max = ch.value;
1662
+ }
1663
+ }
1664
+ return Number.isFinite(min) && Number.isFinite(max);
1665
+ }
1666
+ }
1667
+ ZodNumber.create = (params) => {
1668
+ return new ZodNumber({
1669
+ checks: [],
1670
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
1671
+ coerce: (params == null ? void 0 : params.coerce) || false,
1672
+ ...processCreateParams(params)
1673
+ });
1674
+ };
1675
+ class ZodBigInt extends ZodType {
1676
+ constructor() {
1677
+ super(...arguments);
1678
+ this.min = this.gte;
1679
+ this.max = this.lte;
1680
+ }
1681
+ _parse(input) {
1682
+ if (this._def.coerce) {
1683
+ try {
1684
+ input.data = BigInt(input.data);
1685
+ } catch {
1686
+ return this._getInvalidInput(input);
1687
+ }
1688
+ }
1689
+ const parsedType = this._getType(input);
1690
+ if (parsedType !== ZodParsedType.bigint) {
1691
+ return this._getInvalidInput(input);
1692
+ }
1693
+ let ctx = void 0;
1694
+ const status = new ParseStatus();
1695
+ for (const check of this._def.checks) {
1696
+ if (check.kind === "min") {
1697
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1698
+ if (tooSmall) {
1699
+ ctx = this._getOrReturnCtx(input, ctx);
1700
+ addIssueToContext(ctx, {
1701
+ code: ZodIssueCode.too_small,
1702
+ type: "bigint",
1703
+ minimum: check.value,
1704
+ inclusive: check.inclusive,
1705
+ message: check.message
1706
+ });
1707
+ status.dirty();
1708
+ }
1709
+ } else if (check.kind === "max") {
1710
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1711
+ if (tooBig) {
1712
+ ctx = this._getOrReturnCtx(input, ctx);
1713
+ addIssueToContext(ctx, {
1714
+ code: ZodIssueCode.too_big,
1715
+ type: "bigint",
1716
+ maximum: check.value,
1717
+ inclusive: check.inclusive,
1718
+ message: check.message
1719
+ });
1720
+ status.dirty();
1721
+ }
1722
+ } else if (check.kind === "multipleOf") {
1723
+ if (input.data % check.value !== BigInt(0)) {
1724
+ ctx = this._getOrReturnCtx(input, ctx);
1725
+ addIssueToContext(ctx, {
1726
+ code: ZodIssueCode.not_multiple_of,
1727
+ multipleOf: check.value,
1728
+ message: check.message
1729
+ });
1730
+ status.dirty();
1731
+ }
1732
+ } else {
1733
+ util.assertNever(check);
1734
+ }
1735
+ }
1736
+ return { status: status.value, value: input.data };
1737
+ }
1738
+ _getInvalidInput(input) {
1739
+ const ctx = this._getOrReturnCtx(input);
1740
+ addIssueToContext(ctx, {
1741
+ code: ZodIssueCode.invalid_type,
1742
+ expected: ZodParsedType.bigint,
1743
+ received: ctx.parsedType
1744
+ });
1745
+ return INVALID;
1746
+ }
1747
+ gte(value, message) {
1748
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1749
+ }
1750
+ gt(value, message) {
1751
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1752
+ }
1753
+ lte(value, message) {
1754
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1755
+ }
1756
+ lt(value, message) {
1757
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1758
+ }
1759
+ setLimit(kind, value, inclusive, message) {
1760
+ return new ZodBigInt({
1761
+ ...this._def,
1762
+ checks: [
1763
+ ...this._def.checks,
1764
+ {
1765
+ kind,
1766
+ value,
1767
+ inclusive,
1768
+ message: errorUtil.toString(message)
1769
+ }
1770
+ ]
1771
+ });
1772
+ }
1773
+ _addCheck(check) {
1774
+ return new ZodBigInt({
1775
+ ...this._def,
1776
+ checks: [...this._def.checks, check]
1777
+ });
1778
+ }
1779
+ positive(message) {
1780
+ return this._addCheck({
1781
+ kind: "min",
1782
+ value: BigInt(0),
1783
+ inclusive: false,
1784
+ message: errorUtil.toString(message)
1785
+ });
1786
+ }
1787
+ negative(message) {
1788
+ return this._addCheck({
1789
+ kind: "max",
1790
+ value: BigInt(0),
1791
+ inclusive: false,
1792
+ message: errorUtil.toString(message)
1793
+ });
1794
+ }
1795
+ nonpositive(message) {
1796
+ return this._addCheck({
1797
+ kind: "max",
1798
+ value: BigInt(0),
1799
+ inclusive: true,
1800
+ message: errorUtil.toString(message)
1801
+ });
1802
+ }
1803
+ nonnegative(message) {
1804
+ return this._addCheck({
1805
+ kind: "min",
1806
+ value: BigInt(0),
1807
+ inclusive: true,
1808
+ message: errorUtil.toString(message)
1809
+ });
1810
+ }
1811
+ multipleOf(value, message) {
1812
+ return this._addCheck({
1813
+ kind: "multipleOf",
1814
+ value,
1815
+ message: errorUtil.toString(message)
1816
+ });
1817
+ }
1818
+ get minValue() {
1819
+ let min = null;
1820
+ for (const ch of this._def.checks) {
1821
+ if (ch.kind === "min") {
1822
+ if (min === null || ch.value > min)
1823
+ min = ch.value;
1824
+ }
1825
+ }
1826
+ return min;
1827
+ }
1828
+ get maxValue() {
1829
+ let max = null;
1830
+ for (const ch of this._def.checks) {
1831
+ if (ch.kind === "max") {
1832
+ if (max === null || ch.value < max)
1833
+ max = ch.value;
1834
+ }
1835
+ }
1836
+ return max;
1837
+ }
1838
+ }
1839
+ ZodBigInt.create = (params) => {
1840
+ return new ZodBigInt({
1841
+ checks: [],
1842
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
1843
+ coerce: (params == null ? void 0 : params.coerce) ?? false,
1844
+ ...processCreateParams(params)
1845
+ });
1846
+ };
1847
+ class ZodBoolean extends ZodType {
1848
+ _parse(input) {
1849
+ if (this._def.coerce) {
1850
+ input.data = Boolean(input.data);
1851
+ }
1852
+ const parsedType = this._getType(input);
1853
+ if (parsedType !== ZodParsedType.boolean) {
1854
+ const ctx = this._getOrReturnCtx(input);
1855
+ addIssueToContext(ctx, {
1856
+ code: ZodIssueCode.invalid_type,
1857
+ expected: ZodParsedType.boolean,
1858
+ received: ctx.parsedType
1859
+ });
1860
+ return INVALID;
1861
+ }
1862
+ return OK(input.data);
1863
+ }
1864
+ }
1865
+ ZodBoolean.create = (params) => {
1866
+ return new ZodBoolean({
1867
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
1868
+ coerce: (params == null ? void 0 : params.coerce) || false,
1869
+ ...processCreateParams(params)
1870
+ });
1871
+ };
1872
+ class ZodDate extends ZodType {
1873
+ _parse(input) {
1874
+ if (this._def.coerce) {
1875
+ input.data = new Date(input.data);
1876
+ }
1877
+ const parsedType = this._getType(input);
1878
+ if (parsedType !== ZodParsedType.date) {
1879
+ const ctx2 = this._getOrReturnCtx(input);
1880
+ addIssueToContext(ctx2, {
1881
+ code: ZodIssueCode.invalid_type,
1882
+ expected: ZodParsedType.date,
1883
+ received: ctx2.parsedType
1884
+ });
1885
+ return INVALID;
1886
+ }
1887
+ if (Number.isNaN(input.data.getTime())) {
1888
+ const ctx2 = this._getOrReturnCtx(input);
1889
+ addIssueToContext(ctx2, {
1890
+ code: ZodIssueCode.invalid_date
1891
+ });
1892
+ return INVALID;
1893
+ }
1894
+ const status = new ParseStatus();
1895
+ let ctx = void 0;
1896
+ for (const check of this._def.checks) {
1897
+ if (check.kind === "min") {
1898
+ if (input.data.getTime() < check.value) {
1899
+ ctx = this._getOrReturnCtx(input, ctx);
1900
+ addIssueToContext(ctx, {
1901
+ code: ZodIssueCode.too_small,
1902
+ message: check.message,
1903
+ inclusive: true,
1904
+ exact: false,
1905
+ minimum: check.value,
1906
+ type: "date"
1907
+ });
1908
+ status.dirty();
1909
+ }
1910
+ } else if (check.kind === "max") {
1911
+ if (input.data.getTime() > check.value) {
1912
+ ctx = this._getOrReturnCtx(input, ctx);
1913
+ addIssueToContext(ctx, {
1914
+ code: ZodIssueCode.too_big,
1915
+ message: check.message,
1916
+ inclusive: true,
1917
+ exact: false,
1918
+ maximum: check.value,
1919
+ type: "date"
1920
+ });
1921
+ status.dirty();
1922
+ }
1923
+ } else {
1924
+ util.assertNever(check);
1925
+ }
1926
+ }
1927
+ return {
1928
+ status: status.value,
1929
+ value: new Date(input.data.getTime())
1930
+ };
1931
+ }
1932
+ _addCheck(check) {
1933
+ return new ZodDate({
1934
+ ...this._def,
1935
+ checks: [...this._def.checks, check]
1936
+ });
1937
+ }
1938
+ min(minDate, message) {
1939
+ return this._addCheck({
1940
+ kind: "min",
1941
+ value: minDate.getTime(),
1942
+ message: errorUtil.toString(message)
1943
+ });
1944
+ }
1945
+ max(maxDate, message) {
1946
+ return this._addCheck({
1947
+ kind: "max",
1948
+ value: maxDate.getTime(),
1949
+ message: errorUtil.toString(message)
1950
+ });
1951
+ }
1952
+ get minDate() {
1953
+ let min = null;
1954
+ for (const ch of this._def.checks) {
1955
+ if (ch.kind === "min") {
1956
+ if (min === null || ch.value > min)
1957
+ min = ch.value;
1958
+ }
1959
+ }
1960
+ return min != null ? new Date(min) : null;
1961
+ }
1962
+ get maxDate() {
1963
+ let max = null;
1964
+ for (const ch of this._def.checks) {
1965
+ if (ch.kind === "max") {
1966
+ if (max === null || ch.value < max)
1967
+ max = ch.value;
1968
+ }
1969
+ }
1970
+ return max != null ? new Date(max) : null;
1971
+ }
1972
+ }
1973
+ ZodDate.create = (params) => {
1974
+ return new ZodDate({
1975
+ checks: [],
1976
+ coerce: (params == null ? void 0 : params.coerce) || false,
1977
+ typeName: ZodFirstPartyTypeKind.ZodDate,
1978
+ ...processCreateParams(params)
1979
+ });
1980
+ };
1981
+ class ZodSymbol extends ZodType {
1982
+ _parse(input) {
1983
+ const parsedType = this._getType(input);
1984
+ if (parsedType !== ZodParsedType.symbol) {
1985
+ const ctx = this._getOrReturnCtx(input);
1986
+ addIssueToContext(ctx, {
1987
+ code: ZodIssueCode.invalid_type,
1988
+ expected: ZodParsedType.symbol,
1989
+ received: ctx.parsedType
1990
+ });
1991
+ return INVALID;
1992
+ }
1993
+ return OK(input.data);
1994
+ }
1995
+ }
1996
+ ZodSymbol.create = (params) => {
1997
+ return new ZodSymbol({
1998
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
1999
+ ...processCreateParams(params)
2000
+ });
2001
+ };
2002
+ class ZodUndefined extends ZodType {
2003
+ _parse(input) {
2004
+ const parsedType = this._getType(input);
2005
+ if (parsedType !== ZodParsedType.undefined) {
2006
+ const ctx = this._getOrReturnCtx(input);
2007
+ addIssueToContext(ctx, {
2008
+ code: ZodIssueCode.invalid_type,
2009
+ expected: ZodParsedType.undefined,
2010
+ received: ctx.parsedType
2011
+ });
2012
+ return INVALID;
2013
+ }
2014
+ return OK(input.data);
2015
+ }
2016
+ }
2017
+ ZodUndefined.create = (params) => {
2018
+ return new ZodUndefined({
2019
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
2020
+ ...processCreateParams(params)
2021
+ });
2022
+ };
2023
+ class ZodNull extends ZodType {
2024
+ _parse(input) {
2025
+ const parsedType = this._getType(input);
2026
+ if (parsedType !== ZodParsedType.null) {
2027
+ const ctx = this._getOrReturnCtx(input);
2028
+ addIssueToContext(ctx, {
2029
+ code: ZodIssueCode.invalid_type,
2030
+ expected: ZodParsedType.null,
2031
+ received: ctx.parsedType
2032
+ });
2033
+ return INVALID;
2034
+ }
2035
+ return OK(input.data);
2036
+ }
2037
+ }
2038
+ ZodNull.create = (params) => {
2039
+ return new ZodNull({
2040
+ typeName: ZodFirstPartyTypeKind.ZodNull,
2041
+ ...processCreateParams(params)
2042
+ });
2043
+ };
2044
+ class ZodAny extends ZodType {
2045
+ constructor() {
2046
+ super(...arguments);
2047
+ this._any = true;
2048
+ }
2049
+ _parse(input) {
2050
+ return OK(input.data);
2051
+ }
2052
+ }
2053
+ ZodAny.create = (params) => {
2054
+ return new ZodAny({
2055
+ typeName: ZodFirstPartyTypeKind.ZodAny,
2056
+ ...processCreateParams(params)
2057
+ });
2058
+ };
2059
+ class ZodUnknown extends ZodType {
2060
+ constructor() {
2061
+ super(...arguments);
2062
+ this._unknown = true;
2063
+ }
2064
+ _parse(input) {
2065
+ return OK(input.data);
2066
+ }
2067
+ }
2068
+ ZodUnknown.create = (params) => {
2069
+ return new ZodUnknown({
2070
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
2071
+ ...processCreateParams(params)
2072
+ });
2073
+ };
2074
+ class ZodNever extends ZodType {
2075
+ _parse(input) {
2076
+ const ctx = this._getOrReturnCtx(input);
2077
+ addIssueToContext(ctx, {
2078
+ code: ZodIssueCode.invalid_type,
2079
+ expected: ZodParsedType.never,
2080
+ received: ctx.parsedType
2081
+ });
2082
+ return INVALID;
2083
+ }
2084
+ }
2085
+ ZodNever.create = (params) => {
2086
+ return new ZodNever({
2087
+ typeName: ZodFirstPartyTypeKind.ZodNever,
2088
+ ...processCreateParams(params)
2089
+ });
2090
+ };
2091
+ class ZodVoid extends ZodType {
2092
+ _parse(input) {
2093
+ const parsedType = this._getType(input);
2094
+ if (parsedType !== ZodParsedType.undefined) {
2095
+ const ctx = this._getOrReturnCtx(input);
2096
+ addIssueToContext(ctx, {
2097
+ code: ZodIssueCode.invalid_type,
2098
+ expected: ZodParsedType.void,
2099
+ received: ctx.parsedType
2100
+ });
2101
+ return INVALID;
2102
+ }
2103
+ return OK(input.data);
2104
+ }
2105
+ }
2106
+ ZodVoid.create = (params) => {
2107
+ return new ZodVoid({
2108
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
2109
+ ...processCreateParams(params)
2110
+ });
2111
+ };
2112
+ class ZodArray extends ZodType {
2113
+ _parse(input) {
2114
+ const { ctx, status } = this._processInputParams(input);
2115
+ const def = this._def;
2116
+ if (ctx.parsedType !== ZodParsedType.array) {
2117
+ addIssueToContext(ctx, {
2118
+ code: ZodIssueCode.invalid_type,
2119
+ expected: ZodParsedType.array,
2120
+ received: ctx.parsedType
2121
+ });
2122
+ return INVALID;
2123
+ }
2124
+ if (def.exactLength !== null) {
2125
+ const tooBig = ctx.data.length > def.exactLength.value;
2126
+ const tooSmall = ctx.data.length < def.exactLength.value;
2127
+ if (tooBig || tooSmall) {
2128
+ addIssueToContext(ctx, {
2129
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2130
+ minimum: tooSmall ? def.exactLength.value : void 0,
2131
+ maximum: tooBig ? def.exactLength.value : void 0,
2132
+ type: "array",
2133
+ inclusive: true,
2134
+ exact: true,
2135
+ message: def.exactLength.message
2136
+ });
2137
+ status.dirty();
2138
+ }
2139
+ }
2140
+ if (def.minLength !== null) {
2141
+ if (ctx.data.length < def.minLength.value) {
2142
+ addIssueToContext(ctx, {
2143
+ code: ZodIssueCode.too_small,
2144
+ minimum: def.minLength.value,
2145
+ type: "array",
2146
+ inclusive: true,
2147
+ exact: false,
2148
+ message: def.minLength.message
2149
+ });
2150
+ status.dirty();
2151
+ }
2152
+ }
2153
+ if (def.maxLength !== null) {
2154
+ if (ctx.data.length > def.maxLength.value) {
2155
+ addIssueToContext(ctx, {
2156
+ code: ZodIssueCode.too_big,
2157
+ maximum: def.maxLength.value,
2158
+ type: "array",
2159
+ inclusive: true,
2160
+ exact: false,
2161
+ message: def.maxLength.message
2162
+ });
2163
+ status.dirty();
2164
+ }
2165
+ }
2166
+ if (ctx.common.async) {
2167
+ return Promise.all([...ctx.data].map((item, i) => {
2168
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2169
+ })).then((result2) => {
2170
+ return ParseStatus.mergeArray(status, result2);
2171
+ });
2172
+ }
2173
+ const result = [...ctx.data].map((item, i) => {
2174
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2175
+ });
2176
+ return ParseStatus.mergeArray(status, result);
2177
+ }
2178
+ get element() {
2179
+ return this._def.type;
2180
+ }
2181
+ min(minLength, message) {
2182
+ return new ZodArray({
2183
+ ...this._def,
2184
+ minLength: { value: minLength, message: errorUtil.toString(message) }
2185
+ });
2186
+ }
2187
+ max(maxLength, message) {
2188
+ return new ZodArray({
2189
+ ...this._def,
2190
+ maxLength: { value: maxLength, message: errorUtil.toString(message) }
2191
+ });
2192
+ }
2193
+ length(len, message) {
2194
+ return new ZodArray({
2195
+ ...this._def,
2196
+ exactLength: { value: len, message: errorUtil.toString(message) }
2197
+ });
2198
+ }
2199
+ nonempty(message) {
2200
+ return this.min(1, message);
2201
+ }
2202
+ }
2203
+ ZodArray.create = (schema, params) => {
2204
+ return new ZodArray({
2205
+ type: schema,
2206
+ minLength: null,
2207
+ maxLength: null,
2208
+ exactLength: null,
2209
+ typeName: ZodFirstPartyTypeKind.ZodArray,
2210
+ ...processCreateParams(params)
2211
+ });
2212
+ };
2213
+ function deepPartialify(schema) {
2214
+ if (schema instanceof ZodObject) {
2215
+ const newShape = {};
2216
+ for (const key in schema.shape) {
2217
+ const fieldSchema = schema.shape[key];
2218
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2219
+ }
2220
+ return new ZodObject({
2221
+ ...schema._def,
2222
+ shape: () => newShape
2223
+ });
2224
+ } else if (schema instanceof ZodArray) {
2225
+ return new ZodArray({
2226
+ ...schema._def,
2227
+ type: deepPartialify(schema.element)
2228
+ });
2229
+ } else if (schema instanceof ZodOptional) {
2230
+ return ZodOptional.create(deepPartialify(schema.unwrap()));
2231
+ } else if (schema instanceof ZodNullable) {
2232
+ return ZodNullable.create(deepPartialify(schema.unwrap()));
2233
+ } else if (schema instanceof ZodTuple) {
2234
+ return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2235
+ } else {
2236
+ return schema;
2237
+ }
2238
+ }
2239
+ class ZodObject extends ZodType {
2240
+ constructor() {
2241
+ super(...arguments);
2242
+ this._cached = null;
2243
+ this.nonstrict = this.passthrough;
2244
+ this.augment = this.extend;
2245
+ }
2246
+ _getCached() {
2247
+ if (this._cached !== null)
2248
+ return this._cached;
2249
+ const shape = this._def.shape();
2250
+ const keys = util.objectKeys(shape);
2251
+ this._cached = { shape, keys };
2252
+ return this._cached;
2253
+ }
2254
+ _parse(input) {
2255
+ const parsedType = this._getType(input);
2256
+ if (parsedType !== ZodParsedType.object) {
2257
+ const ctx2 = this._getOrReturnCtx(input);
2258
+ addIssueToContext(ctx2, {
2259
+ code: ZodIssueCode.invalid_type,
2260
+ expected: ZodParsedType.object,
2261
+ received: ctx2.parsedType
2262
+ });
2263
+ return INVALID;
2264
+ }
2265
+ const { status, ctx } = this._processInputParams(input);
2266
+ const { shape, keys: shapeKeys } = this._getCached();
2267
+ const extraKeys = [];
2268
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2269
+ for (const key in ctx.data) {
2270
+ if (!shapeKeys.includes(key)) {
2271
+ extraKeys.push(key);
2272
+ }
2273
+ }
2274
+ }
2275
+ const pairs = [];
2276
+ for (const key of shapeKeys) {
2277
+ const keyValidator = shape[key];
2278
+ const value = ctx.data[key];
2279
+ pairs.push({
2280
+ key: { status: "valid", value: key },
2281
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2282
+ alwaysSet: key in ctx.data
2283
+ });
2284
+ }
2285
+ if (this._def.catchall instanceof ZodNever) {
2286
+ const unknownKeys = this._def.unknownKeys;
2287
+ if (unknownKeys === "passthrough") {
2288
+ for (const key of extraKeys) {
2289
+ pairs.push({
2290
+ key: { status: "valid", value: key },
2291
+ value: { status: "valid", value: ctx.data[key] }
2292
+ });
2293
+ }
2294
+ } else if (unknownKeys === "strict") {
2295
+ if (extraKeys.length > 0) {
2296
+ addIssueToContext(ctx, {
2297
+ code: ZodIssueCode.unrecognized_keys,
2298
+ keys: extraKeys
2299
+ });
2300
+ status.dirty();
2301
+ }
2302
+ } else if (unknownKeys === "strip") ;
2303
+ else {
2304
+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2305
+ }
2306
+ } else {
2307
+ const catchall = this._def.catchall;
2308
+ for (const key of extraKeys) {
2309
+ const value = ctx.data[key];
2310
+ pairs.push({
2311
+ key: { status: "valid", value: key },
2312
+ value: catchall._parse(
2313
+ new ParseInputLazyPath(ctx, value, ctx.path, key)
2314
+ //, ctx.child(key), value, getParsedType(value)
2315
+ ),
2316
+ alwaysSet: key in ctx.data
2317
+ });
2318
+ }
2319
+ }
2320
+ if (ctx.common.async) {
2321
+ return Promise.resolve().then(async () => {
2322
+ const syncPairs = [];
2323
+ for (const pair of pairs) {
2324
+ const key = await pair.key;
2325
+ const value = await pair.value;
2326
+ syncPairs.push({
2327
+ key,
2328
+ value,
2329
+ alwaysSet: pair.alwaysSet
2330
+ });
2331
+ }
2332
+ return syncPairs;
2333
+ }).then((syncPairs) => {
2334
+ return ParseStatus.mergeObjectSync(status, syncPairs);
2335
+ });
2336
+ } else {
2337
+ return ParseStatus.mergeObjectSync(status, pairs);
2338
+ }
2339
+ }
2340
+ get shape() {
2341
+ return this._def.shape();
2342
+ }
2343
+ strict(message) {
2344
+ errorUtil.errToObj;
2345
+ return new ZodObject({
2346
+ ...this._def,
2347
+ unknownKeys: "strict",
2348
+ ...message !== void 0 ? {
2349
+ errorMap: (issue, ctx) => {
2350
+ var _a, _b;
2351
+ const defaultError = ((_b = (_a = this._def).errorMap) == null ? void 0 : _b.call(_a, issue, ctx).message) ?? ctx.defaultError;
2352
+ if (issue.code === "unrecognized_keys")
2353
+ return {
2354
+ message: errorUtil.errToObj(message).message ?? defaultError
2355
+ };
2356
+ return {
2357
+ message: defaultError
2358
+ };
2359
+ }
2360
+ } : {}
2361
+ });
2362
+ }
2363
+ strip() {
2364
+ return new ZodObject({
2365
+ ...this._def,
2366
+ unknownKeys: "strip"
2367
+ });
2368
+ }
2369
+ passthrough() {
2370
+ return new ZodObject({
2371
+ ...this._def,
2372
+ unknownKeys: "passthrough"
2373
+ });
2374
+ }
2375
+ // const AugmentFactory =
2376
+ // <Def extends ZodObjectDef>(def: Def) =>
2377
+ // <Augmentation extends ZodRawShape>(
2378
+ // augmentation: Augmentation
2379
+ // ): ZodObject<
2380
+ // extendShape<ReturnType<Def["shape"]>, Augmentation>,
2381
+ // Def["unknownKeys"],
2382
+ // Def["catchall"]
2383
+ // > => {
2384
+ // return new ZodObject({
2385
+ // ...def,
2386
+ // shape: () => ({
2387
+ // ...def.shape(),
2388
+ // ...augmentation,
2389
+ // }),
2390
+ // }) as any;
2391
+ // };
2392
+ extend(augmentation) {
2393
+ return new ZodObject({
2394
+ ...this._def,
2395
+ shape: () => ({
2396
+ ...this._def.shape(),
2397
+ ...augmentation
2398
+ })
2399
+ });
2400
+ }
2401
+ /**
2402
+ * Prior to zod@1.0.12 there was a bug in the
2403
+ * inferred type of merged objects. Please
2404
+ * upgrade if you are experiencing issues.
2405
+ */
2406
+ merge(merging) {
2407
+ const merged = new ZodObject({
2408
+ unknownKeys: merging._def.unknownKeys,
2409
+ catchall: merging._def.catchall,
2410
+ shape: () => ({
2411
+ ...this._def.shape(),
2412
+ ...merging._def.shape()
2413
+ }),
2414
+ typeName: ZodFirstPartyTypeKind.ZodObject
2415
+ });
2416
+ return merged;
2417
+ }
2418
+ // merge<
2419
+ // Incoming extends AnyZodObject,
2420
+ // Augmentation extends Incoming["shape"],
2421
+ // NewOutput extends {
2422
+ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
2423
+ // ? Augmentation[k]["_output"]
2424
+ // : k extends keyof Output
2425
+ // ? Output[k]
2426
+ // : never;
2427
+ // },
2428
+ // NewInput extends {
2429
+ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
2430
+ // ? Augmentation[k]["_input"]
2431
+ // : k extends keyof Input
2432
+ // ? Input[k]
2433
+ // : never;
2434
+ // }
2435
+ // >(
2436
+ // merging: Incoming
2437
+ // ): ZodObject<
2438
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2439
+ // Incoming["_def"]["unknownKeys"],
2440
+ // Incoming["_def"]["catchall"],
2441
+ // NewOutput,
2442
+ // NewInput
2443
+ // > {
2444
+ // const merged: any = new ZodObject({
2445
+ // unknownKeys: merging._def.unknownKeys,
2446
+ // catchall: merging._def.catchall,
2447
+ // shape: () =>
2448
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2449
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
2450
+ // }) as any;
2451
+ // return merged;
2452
+ // }
2453
+ setKey(key, schema) {
2454
+ return this.augment({ [key]: schema });
2455
+ }
2456
+ // merge<Incoming extends AnyZodObject>(
2457
+ // merging: Incoming
2458
+ // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
2459
+ // ZodObject<
2460
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2461
+ // Incoming["_def"]["unknownKeys"],
2462
+ // Incoming["_def"]["catchall"]
2463
+ // > {
2464
+ // // const mergedShape = objectUtil.mergeShapes(
2465
+ // // this._def.shape(),
2466
+ // // merging._def.shape()
2467
+ // // );
2468
+ // const merged: any = new ZodObject({
2469
+ // unknownKeys: merging._def.unknownKeys,
2470
+ // catchall: merging._def.catchall,
2471
+ // shape: () =>
2472
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2473
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
2474
+ // }) as any;
2475
+ // return merged;
2476
+ // }
2477
+ catchall(index) {
2478
+ return new ZodObject({
2479
+ ...this._def,
2480
+ catchall: index
2481
+ });
2482
+ }
2483
+ pick(mask) {
2484
+ const shape = {};
2485
+ for (const key of util.objectKeys(mask)) {
2486
+ if (mask[key] && this.shape[key]) {
2487
+ shape[key] = this.shape[key];
2488
+ }
2489
+ }
2490
+ return new ZodObject({
2491
+ ...this._def,
2492
+ shape: () => shape
2493
+ });
2494
+ }
2495
+ omit(mask) {
2496
+ const shape = {};
2497
+ for (const key of util.objectKeys(this.shape)) {
2498
+ if (!mask[key]) {
2499
+ shape[key] = this.shape[key];
2500
+ }
2501
+ }
2502
+ return new ZodObject({
2503
+ ...this._def,
2504
+ shape: () => shape
2505
+ });
2506
+ }
2507
+ /**
2508
+ * @deprecated
2509
+ */
2510
+ deepPartial() {
2511
+ return deepPartialify(this);
2512
+ }
2513
+ partial(mask) {
2514
+ const newShape = {};
2515
+ for (const key of util.objectKeys(this.shape)) {
2516
+ const fieldSchema = this.shape[key];
2517
+ if (mask && !mask[key]) {
2518
+ newShape[key] = fieldSchema;
2519
+ } else {
2520
+ newShape[key] = fieldSchema.optional();
2521
+ }
2522
+ }
2523
+ return new ZodObject({
2524
+ ...this._def,
2525
+ shape: () => newShape
2526
+ });
2527
+ }
2528
+ required(mask) {
2529
+ const newShape = {};
2530
+ for (const key of util.objectKeys(this.shape)) {
2531
+ if (mask && !mask[key]) {
2532
+ newShape[key] = this.shape[key];
2533
+ } else {
2534
+ const fieldSchema = this.shape[key];
2535
+ let newField = fieldSchema;
2536
+ while (newField instanceof ZodOptional) {
2537
+ newField = newField._def.innerType;
2538
+ }
2539
+ newShape[key] = newField;
2540
+ }
2541
+ }
2542
+ return new ZodObject({
2543
+ ...this._def,
2544
+ shape: () => newShape
2545
+ });
2546
+ }
2547
+ keyof() {
2548
+ return createZodEnum(util.objectKeys(this.shape));
2549
+ }
2550
+ }
2551
+ ZodObject.create = (shape, params) => {
2552
+ return new ZodObject({
2553
+ shape: () => shape,
2554
+ unknownKeys: "strip",
2555
+ catchall: ZodNever.create(),
2556
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2557
+ ...processCreateParams(params)
2558
+ });
2559
+ };
2560
+ ZodObject.strictCreate = (shape, params) => {
2561
+ return new ZodObject({
2562
+ shape: () => shape,
2563
+ unknownKeys: "strict",
2564
+ catchall: ZodNever.create(),
2565
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2566
+ ...processCreateParams(params)
2567
+ });
2568
+ };
2569
+ ZodObject.lazycreate = (shape, params) => {
2570
+ return new ZodObject({
2571
+ shape,
2572
+ unknownKeys: "strip",
2573
+ catchall: ZodNever.create(),
2574
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2575
+ ...processCreateParams(params)
2576
+ });
2577
+ };
2578
+ class ZodUnion extends ZodType {
2579
+ _parse(input) {
2580
+ const { ctx } = this._processInputParams(input);
2581
+ const options = this._def.options;
2582
+ function handleResults(results) {
2583
+ for (const result of results) {
2584
+ if (result.result.status === "valid") {
2585
+ return result.result;
2586
+ }
2587
+ }
2588
+ for (const result of results) {
2589
+ if (result.result.status === "dirty") {
2590
+ ctx.common.issues.push(...result.ctx.common.issues);
2591
+ return result.result;
2592
+ }
2593
+ }
2594
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
2595
+ addIssueToContext(ctx, {
2596
+ code: ZodIssueCode.invalid_union,
2597
+ unionErrors
2598
+ });
2599
+ return INVALID;
2600
+ }
2601
+ if (ctx.common.async) {
2602
+ return Promise.all(options.map(async (option) => {
2603
+ const childCtx = {
2604
+ ...ctx,
2605
+ common: {
2606
+ ...ctx.common,
2607
+ issues: []
2608
+ },
2609
+ parent: null
2610
+ };
2611
+ return {
2612
+ result: await option._parseAsync({
2613
+ data: ctx.data,
2614
+ path: ctx.path,
2615
+ parent: childCtx
2616
+ }),
2617
+ ctx: childCtx
2618
+ };
2619
+ })).then(handleResults);
2620
+ } else {
2621
+ let dirty = void 0;
2622
+ const issues = [];
2623
+ for (const option of options) {
2624
+ const childCtx = {
2625
+ ...ctx,
2626
+ common: {
2627
+ ...ctx.common,
2628
+ issues: []
2629
+ },
2630
+ parent: null
2631
+ };
2632
+ const result = option._parseSync({
2633
+ data: ctx.data,
2634
+ path: ctx.path,
2635
+ parent: childCtx
2636
+ });
2637
+ if (result.status === "valid") {
2638
+ return result;
2639
+ } else if (result.status === "dirty" && !dirty) {
2640
+ dirty = { result, ctx: childCtx };
2641
+ }
2642
+ if (childCtx.common.issues.length) {
2643
+ issues.push(childCtx.common.issues);
2644
+ }
2645
+ }
2646
+ if (dirty) {
2647
+ ctx.common.issues.push(...dirty.ctx.common.issues);
2648
+ return dirty.result;
2649
+ }
2650
+ const unionErrors = issues.map((issues2) => new ZodError(issues2));
2651
+ addIssueToContext(ctx, {
2652
+ code: ZodIssueCode.invalid_union,
2653
+ unionErrors
2654
+ });
2655
+ return INVALID;
2656
+ }
2657
+ }
2658
+ get options() {
2659
+ return this._def.options;
2660
+ }
2661
+ }
2662
+ ZodUnion.create = (types, params) => {
2663
+ return new ZodUnion({
2664
+ options: types,
2665
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
2666
+ ...processCreateParams(params)
2667
+ });
2668
+ };
2669
+ function mergeValues(a, b) {
2670
+ const aType = getParsedType(a);
2671
+ const bType = getParsedType(b);
2672
+ if (a === b) {
2673
+ return { valid: true, data: a };
2674
+ } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
2675
+ const bKeys = util.objectKeys(b);
2676
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
2677
+ const newObj = { ...a, ...b };
2678
+ for (const key of sharedKeys) {
2679
+ const sharedValue = mergeValues(a[key], b[key]);
2680
+ if (!sharedValue.valid) {
2681
+ return { valid: false };
2682
+ }
2683
+ newObj[key] = sharedValue.data;
2684
+ }
2685
+ return { valid: true, data: newObj };
2686
+ } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
2687
+ if (a.length !== b.length) {
2688
+ return { valid: false };
2689
+ }
2690
+ const newArray = [];
2691
+ for (let index = 0; index < a.length; index++) {
2692
+ const itemA = a[index];
2693
+ const itemB = b[index];
2694
+ const sharedValue = mergeValues(itemA, itemB);
2695
+ if (!sharedValue.valid) {
2696
+ return { valid: false };
2697
+ }
2698
+ newArray.push(sharedValue.data);
2699
+ }
2700
+ return { valid: true, data: newArray };
2701
+ } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
2702
+ return { valid: true, data: a };
2703
+ } else {
2704
+ return { valid: false };
2705
+ }
2706
+ }
2707
+ class ZodIntersection extends ZodType {
2708
+ _parse(input) {
2709
+ const { status, ctx } = this._processInputParams(input);
2710
+ const handleParsed = (parsedLeft, parsedRight) => {
2711
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {
2712
+ return INVALID;
2713
+ }
2714
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
2715
+ if (!merged.valid) {
2716
+ addIssueToContext(ctx, {
2717
+ code: ZodIssueCode.invalid_intersection_types
2718
+ });
2719
+ return INVALID;
2720
+ }
2721
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {
2722
+ status.dirty();
2723
+ }
2724
+ return { status: status.value, value: merged.data };
2725
+ };
2726
+ if (ctx.common.async) {
2727
+ return Promise.all([
2728
+ this._def.left._parseAsync({
2729
+ data: ctx.data,
2730
+ path: ctx.path,
2731
+ parent: ctx
2732
+ }),
2733
+ this._def.right._parseAsync({
2734
+ data: ctx.data,
2735
+ path: ctx.path,
2736
+ parent: ctx
2737
+ })
2738
+ ]).then(([left, right]) => handleParsed(left, right));
2739
+ } else {
2740
+ return handleParsed(this._def.left._parseSync({
2741
+ data: ctx.data,
2742
+ path: ctx.path,
2743
+ parent: ctx
2744
+ }), this._def.right._parseSync({
2745
+ data: ctx.data,
2746
+ path: ctx.path,
2747
+ parent: ctx
2748
+ }));
2749
+ }
2750
+ }
2751
+ }
2752
+ ZodIntersection.create = (left, right, params) => {
2753
+ return new ZodIntersection({
2754
+ left,
2755
+ right,
2756
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
2757
+ ...processCreateParams(params)
2758
+ });
2759
+ };
2760
+ class ZodTuple extends ZodType {
2761
+ _parse(input) {
2762
+ const { status, ctx } = this._processInputParams(input);
2763
+ if (ctx.parsedType !== ZodParsedType.array) {
2764
+ addIssueToContext(ctx, {
2765
+ code: ZodIssueCode.invalid_type,
2766
+ expected: ZodParsedType.array,
2767
+ received: ctx.parsedType
2768
+ });
2769
+ return INVALID;
2770
+ }
2771
+ if (ctx.data.length < this._def.items.length) {
2772
+ addIssueToContext(ctx, {
2773
+ code: ZodIssueCode.too_small,
2774
+ minimum: this._def.items.length,
2775
+ inclusive: true,
2776
+ exact: false,
2777
+ type: "array"
2778
+ });
2779
+ return INVALID;
2780
+ }
2781
+ const rest = this._def.rest;
2782
+ if (!rest && ctx.data.length > this._def.items.length) {
2783
+ addIssueToContext(ctx, {
2784
+ code: ZodIssueCode.too_big,
2785
+ maximum: this._def.items.length,
2786
+ inclusive: true,
2787
+ exact: false,
2788
+ type: "array"
2789
+ });
2790
+ status.dirty();
2791
+ }
2792
+ const items = [...ctx.data].map((item, itemIndex) => {
2793
+ const schema = this._def.items[itemIndex] || this._def.rest;
2794
+ if (!schema)
2795
+ return null;
2796
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
2797
+ }).filter((x) => !!x);
2798
+ if (ctx.common.async) {
2799
+ return Promise.all(items).then((results) => {
2800
+ return ParseStatus.mergeArray(status, results);
2801
+ });
2802
+ } else {
2803
+ return ParseStatus.mergeArray(status, items);
2804
+ }
2805
+ }
2806
+ get items() {
2807
+ return this._def.items;
2808
+ }
2809
+ rest(rest) {
2810
+ return new ZodTuple({
2811
+ ...this._def,
2812
+ rest
2813
+ });
2814
+ }
2815
+ }
2816
+ ZodTuple.create = (schemas, params) => {
2817
+ if (!Array.isArray(schemas)) {
2818
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
2819
+ }
2820
+ return new ZodTuple({
2821
+ items: schemas,
2822
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
2823
+ rest: null,
2824
+ ...processCreateParams(params)
2825
+ });
2826
+ };
2827
+ class ZodMap extends ZodType {
2828
+ get keySchema() {
2829
+ return this._def.keyType;
2830
+ }
2831
+ get valueSchema() {
2832
+ return this._def.valueType;
2833
+ }
2834
+ _parse(input) {
2835
+ const { status, ctx } = this._processInputParams(input);
2836
+ if (ctx.parsedType !== ZodParsedType.map) {
2837
+ addIssueToContext(ctx, {
2838
+ code: ZodIssueCode.invalid_type,
2839
+ expected: ZodParsedType.map,
2840
+ received: ctx.parsedType
2841
+ });
2842
+ return INVALID;
2843
+ }
2844
+ const keyType = this._def.keyType;
2845
+ const valueType = this._def.valueType;
2846
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
2847
+ return {
2848
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
2849
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
2850
+ };
2851
+ });
2852
+ if (ctx.common.async) {
2853
+ const finalMap = /* @__PURE__ */ new Map();
2854
+ return Promise.resolve().then(async () => {
2855
+ for (const pair of pairs) {
2856
+ const key = await pair.key;
2857
+ const value = await pair.value;
2858
+ if (key.status === "aborted" || value.status === "aborted") {
2859
+ return INVALID;
2860
+ }
2861
+ if (key.status === "dirty" || value.status === "dirty") {
2862
+ status.dirty();
2863
+ }
2864
+ finalMap.set(key.value, value.value);
2865
+ }
2866
+ return { status: status.value, value: finalMap };
2867
+ });
2868
+ } else {
2869
+ const finalMap = /* @__PURE__ */ new Map();
2870
+ for (const pair of pairs) {
2871
+ const key = pair.key;
2872
+ const value = pair.value;
2873
+ if (key.status === "aborted" || value.status === "aborted") {
2874
+ return INVALID;
2875
+ }
2876
+ if (key.status === "dirty" || value.status === "dirty") {
2877
+ status.dirty();
2878
+ }
2879
+ finalMap.set(key.value, value.value);
2880
+ }
2881
+ return { status: status.value, value: finalMap };
2882
+ }
2883
+ }
2884
+ }
2885
+ ZodMap.create = (keyType, valueType, params) => {
2886
+ return new ZodMap({
2887
+ valueType,
2888
+ keyType,
2889
+ typeName: ZodFirstPartyTypeKind.ZodMap,
2890
+ ...processCreateParams(params)
2891
+ });
2892
+ };
2893
+ class ZodSet extends ZodType {
2894
+ _parse(input) {
2895
+ const { status, ctx } = this._processInputParams(input);
2896
+ if (ctx.parsedType !== ZodParsedType.set) {
2897
+ addIssueToContext(ctx, {
2898
+ code: ZodIssueCode.invalid_type,
2899
+ expected: ZodParsedType.set,
2900
+ received: ctx.parsedType
2901
+ });
2902
+ return INVALID;
2903
+ }
2904
+ const def = this._def;
2905
+ if (def.minSize !== null) {
2906
+ if (ctx.data.size < def.minSize.value) {
2907
+ addIssueToContext(ctx, {
2908
+ code: ZodIssueCode.too_small,
2909
+ minimum: def.minSize.value,
2910
+ type: "set",
2911
+ inclusive: true,
2912
+ exact: false,
2913
+ message: def.minSize.message
2914
+ });
2915
+ status.dirty();
2916
+ }
2917
+ }
2918
+ if (def.maxSize !== null) {
2919
+ if (ctx.data.size > def.maxSize.value) {
2920
+ addIssueToContext(ctx, {
2921
+ code: ZodIssueCode.too_big,
2922
+ maximum: def.maxSize.value,
2923
+ type: "set",
2924
+ inclusive: true,
2925
+ exact: false,
2926
+ message: def.maxSize.message
2927
+ });
2928
+ status.dirty();
2929
+ }
2930
+ }
2931
+ const valueType = this._def.valueType;
2932
+ function finalizeSet(elements2) {
2933
+ const parsedSet = /* @__PURE__ */ new Set();
2934
+ for (const element of elements2) {
2935
+ if (element.status === "aborted")
2936
+ return INVALID;
2937
+ if (element.status === "dirty")
2938
+ status.dirty();
2939
+ parsedSet.add(element.value);
2940
+ }
2941
+ return { status: status.value, value: parsedSet };
2942
+ }
2943
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
2944
+ if (ctx.common.async) {
2945
+ return Promise.all(elements).then((elements2) => finalizeSet(elements2));
2946
+ } else {
2947
+ return finalizeSet(elements);
2948
+ }
2949
+ }
2950
+ min(minSize, message) {
2951
+ return new ZodSet({
2952
+ ...this._def,
2953
+ minSize: { value: minSize, message: errorUtil.toString(message) }
2954
+ });
2955
+ }
2956
+ max(maxSize, message) {
2957
+ return new ZodSet({
2958
+ ...this._def,
2959
+ maxSize: { value: maxSize, message: errorUtil.toString(message) }
2960
+ });
2961
+ }
2962
+ size(size, message) {
2963
+ return this.min(size, message).max(size, message);
2964
+ }
2965
+ nonempty(message) {
2966
+ return this.min(1, message);
2967
+ }
2968
+ }
2969
+ ZodSet.create = (valueType, params) => {
2970
+ return new ZodSet({
2971
+ valueType,
2972
+ minSize: null,
2973
+ maxSize: null,
2974
+ typeName: ZodFirstPartyTypeKind.ZodSet,
2975
+ ...processCreateParams(params)
2976
+ });
2977
+ };
2978
+ class ZodLazy extends ZodType {
2979
+ get schema() {
2980
+ return this._def.getter();
2981
+ }
2982
+ _parse(input) {
2983
+ const { ctx } = this._processInputParams(input);
2984
+ const lazySchema = this._def.getter();
2985
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
2986
+ }
2987
+ }
2988
+ ZodLazy.create = (getter, params) => {
2989
+ return new ZodLazy({
2990
+ getter,
2991
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
2992
+ ...processCreateParams(params)
2993
+ });
2994
+ };
2995
+ class ZodLiteral extends ZodType {
2996
+ _parse(input) {
2997
+ if (input.data !== this._def.value) {
2998
+ const ctx = this._getOrReturnCtx(input);
2999
+ addIssueToContext(ctx, {
3000
+ received: ctx.data,
3001
+ code: ZodIssueCode.invalid_literal,
3002
+ expected: this._def.value
3003
+ });
3004
+ return INVALID;
3005
+ }
3006
+ return { status: "valid", value: input.data };
3007
+ }
3008
+ get value() {
3009
+ return this._def.value;
3010
+ }
3011
+ }
3012
+ ZodLiteral.create = (value, params) => {
3013
+ return new ZodLiteral({
3014
+ value,
3015
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
3016
+ ...processCreateParams(params)
3017
+ });
3018
+ };
3019
+ function createZodEnum(values, params) {
3020
+ return new ZodEnum({
3021
+ values,
3022
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
3023
+ ...processCreateParams(params)
3024
+ });
3025
+ }
3026
+ class ZodEnum extends ZodType {
3027
+ _parse(input) {
3028
+ if (typeof input.data !== "string") {
3029
+ const ctx = this._getOrReturnCtx(input);
3030
+ const expectedValues = this._def.values;
3031
+ addIssueToContext(ctx, {
3032
+ expected: util.joinValues(expectedValues),
3033
+ received: ctx.parsedType,
3034
+ code: ZodIssueCode.invalid_type
3035
+ });
3036
+ return INVALID;
3037
+ }
3038
+ if (!this._cache) {
3039
+ this._cache = new Set(this._def.values);
3040
+ }
3041
+ if (!this._cache.has(input.data)) {
3042
+ const ctx = this._getOrReturnCtx(input);
3043
+ const expectedValues = this._def.values;
3044
+ addIssueToContext(ctx, {
3045
+ received: ctx.data,
3046
+ code: ZodIssueCode.invalid_enum_value,
3047
+ options: expectedValues
3048
+ });
3049
+ return INVALID;
3050
+ }
3051
+ return OK(input.data);
3052
+ }
3053
+ get options() {
3054
+ return this._def.values;
3055
+ }
3056
+ get enum() {
3057
+ const enumValues = {};
3058
+ for (const val of this._def.values) {
3059
+ enumValues[val] = val;
3060
+ }
3061
+ return enumValues;
3062
+ }
3063
+ get Values() {
3064
+ const enumValues = {};
3065
+ for (const val of this._def.values) {
3066
+ enumValues[val] = val;
3067
+ }
3068
+ return enumValues;
3069
+ }
3070
+ get Enum() {
3071
+ const enumValues = {};
3072
+ for (const val of this._def.values) {
3073
+ enumValues[val] = val;
3074
+ }
3075
+ return enumValues;
3076
+ }
3077
+ extract(values, newDef = this._def) {
3078
+ return ZodEnum.create(values, {
3079
+ ...this._def,
3080
+ ...newDef
3081
+ });
3082
+ }
3083
+ exclude(values, newDef = this._def) {
3084
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3085
+ ...this._def,
3086
+ ...newDef
3087
+ });
3088
+ }
3089
+ }
3090
+ ZodEnum.create = createZodEnum;
3091
+ class ZodNativeEnum extends ZodType {
3092
+ _parse(input) {
3093
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
3094
+ const ctx = this._getOrReturnCtx(input);
3095
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3096
+ const expectedValues = util.objectValues(nativeEnumValues);
3097
+ addIssueToContext(ctx, {
3098
+ expected: util.joinValues(expectedValues),
3099
+ received: ctx.parsedType,
3100
+ code: ZodIssueCode.invalid_type
3101
+ });
3102
+ return INVALID;
3103
+ }
3104
+ if (!this._cache) {
3105
+ this._cache = new Set(util.getValidEnumValues(this._def.values));
3106
+ }
3107
+ if (!this._cache.has(input.data)) {
3108
+ const expectedValues = util.objectValues(nativeEnumValues);
3109
+ addIssueToContext(ctx, {
3110
+ received: ctx.data,
3111
+ code: ZodIssueCode.invalid_enum_value,
3112
+ options: expectedValues
3113
+ });
3114
+ return INVALID;
3115
+ }
3116
+ return OK(input.data);
3117
+ }
3118
+ get enum() {
3119
+ return this._def.values;
3120
+ }
3121
+ }
3122
+ ZodNativeEnum.create = (values, params) => {
3123
+ return new ZodNativeEnum({
3124
+ values,
3125
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3126
+ ...processCreateParams(params)
3127
+ });
3128
+ };
3129
+ class ZodPromise extends ZodType {
3130
+ unwrap() {
3131
+ return this._def.type;
3132
+ }
3133
+ _parse(input) {
3134
+ const { ctx } = this._processInputParams(input);
3135
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3136
+ addIssueToContext(ctx, {
3137
+ code: ZodIssueCode.invalid_type,
3138
+ expected: ZodParsedType.promise,
3139
+ received: ctx.parsedType
3140
+ });
3141
+ return INVALID;
3142
+ }
3143
+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
3144
+ return OK(promisified.then((data) => {
3145
+ return this._def.type.parseAsync(data, {
3146
+ path: ctx.path,
3147
+ errorMap: ctx.common.contextualErrorMap
3148
+ });
3149
+ }));
3150
+ }
3151
+ }
3152
+ ZodPromise.create = (schema, params) => {
3153
+ return new ZodPromise({
3154
+ type: schema,
3155
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
3156
+ ...processCreateParams(params)
3157
+ });
3158
+ };
3159
+ class ZodEffects extends ZodType {
3160
+ innerType() {
3161
+ return this._def.schema;
3162
+ }
3163
+ sourceType() {
3164
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
3165
+ }
3166
+ _parse(input) {
3167
+ const { status, ctx } = this._processInputParams(input);
3168
+ const effect = this._def.effect || null;
3169
+ const checkCtx = {
3170
+ addIssue: (arg) => {
3171
+ addIssueToContext(ctx, arg);
3172
+ if (arg.fatal) {
3173
+ status.abort();
3174
+ } else {
3175
+ status.dirty();
3176
+ }
3177
+ },
3178
+ get path() {
3179
+ return ctx.path;
3180
+ }
3181
+ };
3182
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3183
+ if (effect.type === "preprocess") {
3184
+ const processed = effect.transform(ctx.data, checkCtx);
3185
+ if (ctx.common.async) {
3186
+ return Promise.resolve(processed).then(async (processed2) => {
3187
+ if (status.value === "aborted")
3188
+ return INVALID;
3189
+ const result = await this._def.schema._parseAsync({
3190
+ data: processed2,
3191
+ path: ctx.path,
3192
+ parent: ctx
3193
+ });
3194
+ if (result.status === "aborted")
3195
+ return INVALID;
3196
+ if (result.status === "dirty")
3197
+ return DIRTY(result.value);
3198
+ if (status.value === "dirty")
3199
+ return DIRTY(result.value);
3200
+ return result;
3201
+ });
3202
+ } else {
3203
+ if (status.value === "aborted")
3204
+ return INVALID;
3205
+ const result = this._def.schema._parseSync({
3206
+ data: processed,
3207
+ path: ctx.path,
3208
+ parent: ctx
3209
+ });
3210
+ if (result.status === "aborted")
3211
+ return INVALID;
3212
+ if (result.status === "dirty")
3213
+ return DIRTY(result.value);
3214
+ if (status.value === "dirty")
3215
+ return DIRTY(result.value);
3216
+ return result;
3217
+ }
3218
+ }
3219
+ if (effect.type === "refinement") {
3220
+ const executeRefinement = (acc) => {
3221
+ const result = effect.refinement(acc, checkCtx);
3222
+ if (ctx.common.async) {
3223
+ return Promise.resolve(result);
3224
+ }
3225
+ if (result instanceof Promise) {
3226
+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3227
+ }
3228
+ return acc;
3229
+ };
3230
+ if (ctx.common.async === false) {
3231
+ const inner = this._def.schema._parseSync({
3232
+ data: ctx.data,
3233
+ path: ctx.path,
3234
+ parent: ctx
3235
+ });
3236
+ if (inner.status === "aborted")
3237
+ return INVALID;
3238
+ if (inner.status === "dirty")
3239
+ status.dirty();
3240
+ executeRefinement(inner.value);
3241
+ return { status: status.value, value: inner.value };
3242
+ } else {
3243
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
3244
+ if (inner.status === "aborted")
3245
+ return INVALID;
3246
+ if (inner.status === "dirty")
3247
+ status.dirty();
3248
+ return executeRefinement(inner.value).then(() => {
3249
+ return { status: status.value, value: inner.value };
3250
+ });
3251
+ });
3252
+ }
3253
+ }
3254
+ if (effect.type === "transform") {
3255
+ if (ctx.common.async === false) {
3256
+ const base = this._def.schema._parseSync({
3257
+ data: ctx.data,
3258
+ path: ctx.path,
3259
+ parent: ctx
3260
+ });
3261
+ if (!isValid(base))
3262
+ return INVALID;
3263
+ const result = effect.transform(base.value, checkCtx);
3264
+ if (result instanceof Promise) {
3265
+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3266
+ }
3267
+ return { status: status.value, value: result };
3268
+ } else {
3269
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
3270
+ if (!isValid(base))
3271
+ return INVALID;
3272
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
3273
+ status: status.value,
3274
+ value: result
3275
+ }));
3276
+ });
3277
+ }
3278
+ }
3279
+ util.assertNever(effect);
3280
+ }
3281
+ }
3282
+ ZodEffects.create = (schema, effect, params) => {
3283
+ return new ZodEffects({
3284
+ schema,
3285
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3286
+ effect,
3287
+ ...processCreateParams(params)
3288
+ });
3289
+ };
3290
+ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3291
+ return new ZodEffects({
3292
+ schema,
3293
+ effect: { type: "preprocess", transform: preprocess },
3294
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3295
+ ...processCreateParams(params)
3296
+ });
3297
+ };
3298
+ class ZodOptional extends ZodType {
3299
+ _parse(input) {
3300
+ const parsedType = this._getType(input);
3301
+ if (parsedType === ZodParsedType.undefined) {
3302
+ return OK(void 0);
3303
+ }
3304
+ return this._def.innerType._parse(input);
3305
+ }
3306
+ unwrap() {
3307
+ return this._def.innerType;
3308
+ }
3309
+ }
3310
+ ZodOptional.create = (type, params) => {
3311
+ return new ZodOptional({
3312
+ innerType: type,
3313
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
3314
+ ...processCreateParams(params)
3315
+ });
3316
+ };
3317
+ class ZodNullable extends ZodType {
3318
+ _parse(input) {
3319
+ const parsedType = this._getType(input);
3320
+ if (parsedType === ZodParsedType.null) {
3321
+ return OK(null);
3322
+ }
3323
+ return this._def.innerType._parse(input);
3324
+ }
3325
+ unwrap() {
3326
+ return this._def.innerType;
3327
+ }
3328
+ }
3329
+ ZodNullable.create = (type, params) => {
3330
+ return new ZodNullable({
3331
+ innerType: type,
3332
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
3333
+ ...processCreateParams(params)
3334
+ });
3335
+ };
3336
+ class ZodDefault extends ZodType {
3337
+ _parse(input) {
3338
+ const { ctx } = this._processInputParams(input);
3339
+ let data = ctx.data;
3340
+ if (ctx.parsedType === ZodParsedType.undefined) {
3341
+ data = this._def.defaultValue();
3342
+ }
3343
+ return this._def.innerType._parse({
3344
+ data,
3345
+ path: ctx.path,
3346
+ parent: ctx
3347
+ });
3348
+ }
3349
+ removeDefault() {
3350
+ return this._def.innerType;
3351
+ }
3352
+ }
3353
+ ZodDefault.create = (type, params) => {
3354
+ return new ZodDefault({
3355
+ innerType: type,
3356
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
3357
+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,
3358
+ ...processCreateParams(params)
3359
+ });
3360
+ };
3361
+ class ZodCatch extends ZodType {
3362
+ _parse(input) {
3363
+ const { ctx } = this._processInputParams(input);
3364
+ const newCtx = {
3365
+ ...ctx,
3366
+ common: {
3367
+ ...ctx.common,
3368
+ issues: []
3369
+ }
3370
+ };
3371
+ const result = this._def.innerType._parse({
3372
+ data: newCtx.data,
3373
+ path: newCtx.path,
3374
+ parent: {
3375
+ ...newCtx
3376
+ }
3377
+ });
3378
+ if (isAsync(result)) {
3379
+ return result.then((result2) => {
3380
+ return {
3381
+ status: "valid",
3382
+ value: result2.status === "valid" ? result2.value : this._def.catchValue({
3383
+ get error() {
3384
+ return new ZodError(newCtx.common.issues);
3385
+ },
3386
+ input: newCtx.data
3387
+ })
3388
+ };
3389
+ });
3390
+ } else {
3391
+ return {
3392
+ status: "valid",
3393
+ value: result.status === "valid" ? result.value : this._def.catchValue({
3394
+ get error() {
3395
+ return new ZodError(newCtx.common.issues);
3396
+ },
3397
+ input: newCtx.data
3398
+ })
3399
+ };
3400
+ }
3401
+ }
3402
+ removeCatch() {
3403
+ return this._def.innerType;
3404
+ }
3405
+ }
3406
+ ZodCatch.create = (type, params) => {
3407
+ return new ZodCatch({
3408
+ innerType: type,
3409
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
3410
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
3411
+ ...processCreateParams(params)
3412
+ });
3413
+ };
3414
+ class ZodNaN extends ZodType {
3415
+ _parse(input) {
3416
+ const parsedType = this._getType(input);
3417
+ if (parsedType !== ZodParsedType.nan) {
3418
+ const ctx = this._getOrReturnCtx(input);
3419
+ addIssueToContext(ctx, {
3420
+ code: ZodIssueCode.invalid_type,
3421
+ expected: ZodParsedType.nan,
3422
+ received: ctx.parsedType
3423
+ });
3424
+ return INVALID;
3425
+ }
3426
+ return { status: "valid", value: input.data };
3427
+ }
3428
+ }
3429
+ ZodNaN.create = (params) => {
3430
+ return new ZodNaN({
3431
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
3432
+ ...processCreateParams(params)
3433
+ });
3434
+ };
3435
+ class ZodBranded extends ZodType {
3436
+ _parse(input) {
3437
+ const { ctx } = this._processInputParams(input);
3438
+ const data = ctx.data;
3439
+ return this._def.type._parse({
3440
+ data,
3441
+ path: ctx.path,
3442
+ parent: ctx
3443
+ });
3444
+ }
3445
+ unwrap() {
3446
+ return this._def.type;
3447
+ }
3448
+ }
3449
+ class ZodPipeline extends ZodType {
3450
+ _parse(input) {
3451
+ const { status, ctx } = this._processInputParams(input);
3452
+ if (ctx.common.async) {
3453
+ const handleAsync = async () => {
3454
+ const inResult = await this._def.in._parseAsync({
3455
+ data: ctx.data,
3456
+ path: ctx.path,
3457
+ parent: ctx
3458
+ });
3459
+ if (inResult.status === "aborted")
3460
+ return INVALID;
3461
+ if (inResult.status === "dirty") {
3462
+ status.dirty();
3463
+ return DIRTY(inResult.value);
3464
+ } else {
3465
+ return this._def.out._parseAsync({
3466
+ data: inResult.value,
3467
+ path: ctx.path,
3468
+ parent: ctx
3469
+ });
3470
+ }
3471
+ };
3472
+ return handleAsync();
3473
+ } else {
3474
+ const inResult = this._def.in._parseSync({
3475
+ data: ctx.data,
3476
+ path: ctx.path,
3477
+ parent: ctx
3478
+ });
3479
+ if (inResult.status === "aborted")
3480
+ return INVALID;
3481
+ if (inResult.status === "dirty") {
3482
+ status.dirty();
3483
+ return {
3484
+ status: "dirty",
3485
+ value: inResult.value
3486
+ };
3487
+ } else {
3488
+ return this._def.out._parseSync({
3489
+ data: inResult.value,
3490
+ path: ctx.path,
3491
+ parent: ctx
3492
+ });
3493
+ }
3494
+ }
3495
+ }
3496
+ static create(a, b) {
3497
+ return new ZodPipeline({
3498
+ in: a,
3499
+ out: b,
3500
+ typeName: ZodFirstPartyTypeKind.ZodPipeline
3501
+ });
3502
+ }
3503
+ }
3504
+ class ZodReadonly extends ZodType {
3505
+ _parse(input) {
3506
+ const result = this._def.innerType._parse(input);
3507
+ const freeze = (data) => {
3508
+ if (isValid(data)) {
3509
+ data.value = Object.freeze(data.value);
3510
+ }
3511
+ return data;
3512
+ };
3513
+ return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
3514
+ }
3515
+ unwrap() {
3516
+ return this._def.innerType;
3517
+ }
3518
+ }
3519
+ ZodReadonly.create = (type, params) => {
3520
+ return new ZodReadonly({
3521
+ innerType: type,
3522
+ typeName: ZodFirstPartyTypeKind.ZodReadonly,
3523
+ ...processCreateParams(params)
3524
+ });
3525
+ };
3526
+ var ZodFirstPartyTypeKind;
3527
+ (function(ZodFirstPartyTypeKind2) {
3528
+ ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
3529
+ ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
3530
+ ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
3531
+ ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
3532
+ ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
3533
+ ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
3534
+ ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
3535
+ ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
3536
+ ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
3537
+ ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
3538
+ ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
3539
+ ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
3540
+ ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
3541
+ ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
3542
+ ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
3543
+ ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
3544
+ ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
3545
+ ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
3546
+ ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
3547
+ ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
3548
+ ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
3549
+ ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
3550
+ ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
3551
+ ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
3552
+ ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
3553
+ ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
3554
+ ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
3555
+ ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
3556
+ ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
3557
+ ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
3558
+ ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
3559
+ ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
3560
+ ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
3561
+ ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
3562
+ ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
3563
+ ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
3564
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
3565
+ const stringType = ZodString.create;
3566
+ const unknownType = ZodUnknown.create;
3567
+ ZodNever.create;
3568
+ const arrayType = ZodArray.create;
3569
+ const objectType = ZodObject.create;
3570
+ ZodUnion.create;
3571
+ ZodIntersection.create;
3572
+ ZodTuple.create;
3573
+ const enumType = ZodEnum.create;
3574
+ ZodPromise.create;
3575
+ const optionalType = ZodOptional.create;
3576
+ ZodNullable.create;
3577
+ const EventObject = objectType({
3578
+ topic: stringType(),
3579
+ payload: unknownType()
3580
+ });
3581
+ class AppBridgeCapability {
3582
+ constructor(appBridgeMessagePort) {
3583
+ this.appBridgeMessagePort = appBridgeMessagePort;
3584
+ }
3585
+ registerMessageHandler(subject, messageHandler) {
3586
+ this.appBridgeMessagePort.registerMessageHandler(subject, messageHandler.bind(this));
3587
+ }
3588
+ async sendMessage(subject, body, options) {
3589
+ return this.appBridgeMessagePort.sendMessage(subject, body, options);
3590
+ }
3591
+ }
3592
+ class AppBridgeInfrastructure {
3593
+ constructor(appBridgeMessagePort) {
3594
+ this.appBridgeMessagePort = appBridgeMessagePort;
3595
+ }
3596
+ registerCapability(capability) {
3597
+ return new capability(this.appBridgeMessagePort);
3598
+ }
3599
+ }
3600
+ const MessageType = enumType(["HANDSHAKE", "REQUEST", "RESPONSE", "ERROR"]);
3601
+ const ChannelMessage = objectType({
3602
+ id: stringType().min(1, "Message ID must be at least 1 character long"),
3603
+ type: MessageType,
3604
+ subject: stringType().min(1, "Message subject must be at least 1 character long"),
3605
+ body: optionalType(unknownType())
3606
+ });
3607
+ const _AppBridgeMessagePort = class _AppBridgeMessagePort {
3608
+ constructor(messagePort) {
3609
+ // Default timeout for sending messages (30 seconds)
3610
+ // handlers for channel messages the AppBridge can receive
3611
+ __publicField(this, "channelMessageHandlers", /* @__PURE__ */ new Map());
3612
+ // lookup for pending messages sent via the message channel
3613
+ __publicField(this, "_messageLookup", /* @__PURE__ */ new Map());
3614
+ this.messagePort = messagePort;
3615
+ this.messagePort.onmessage = this.handleMessage.bind(this);
3616
+ }
3617
+ sendMessage(subject, body, options) {
3618
+ const { timeout = _AppBridgeMessagePort.DEFAULT_SEND_MESSAGE_TIMEOUT } = options || {};
3619
+ return new Promise((resolve, reject) => {
3620
+ const id = crypto.randomUUID();
3621
+ this._messageLookup.set(id, {
3622
+ promise: { resolve, reject }
3623
+ });
3624
+ const transferObject = {
3625
+ id,
3626
+ type: "REQUEST",
3627
+ subject,
3628
+ body
3629
+ };
3630
+ this.messagePort.postMessage(transferObject);
3631
+ setTimeout(() => reject("App timeout"), timeout);
3632
+ });
3633
+ }
3634
+ registerMessageHandler(subject, handler) {
3635
+ if (this.channelMessageHandlers.has(subject)) {
3636
+ console.warn(`Overriding existing handler for subject: ${subject}`);
3637
+ }
3638
+ this.channelMessageHandlers.set(subject, handler);
3639
+ }
3640
+ async handleMessage(e) {
3641
+ const channelMessage = ChannelMessage.parse(e.data);
3642
+ switch (channelMessage.type) {
3643
+ case "REQUEST":
3644
+ {
3645
+ const handler = this.channelMessageHandlers.get(channelMessage.subject);
3646
+ if (!handler) {
3647
+ console.error(`No handler registered for message subject: ${channelMessage.subject}`);
3648
+ return;
3649
+ }
3650
+ try {
3651
+ const result = await handler(channelMessage);
3652
+ const responseMessage = {
3653
+ ...channelMessage,
3654
+ type: "RESPONSE",
3655
+ body: result
3656
+ };
3657
+ this.messagePort.postMessage(responseMessage);
3658
+ } catch (error) {
3659
+ const errorMessage = {
3660
+ ...channelMessage,
3661
+ type: "ERROR",
3662
+ body: error instanceof Error ? error.message : String(error)
3663
+ };
3664
+ this.messagePort.postMessage(errorMessage);
3665
+ return;
3666
+ }
3667
+ }
3668
+ break;
3669
+ case "RESPONSE":
3670
+ {
3671
+ const requestMessage = this._messageLookup.get(channelMessage.id);
3672
+ if (!requestMessage) {
3673
+ console.error(`No request found for message ID: ${channelMessage.id}`);
3674
+ return;
3675
+ }
3676
+ requestMessage.promise.resolve(channelMessage.body);
3677
+ this._messageLookup.delete(channelMessage.id);
3678
+ }
3679
+ break;
3680
+ case "ERROR":
3681
+ {
3682
+ const requestMessage = this._messageLookup.get(channelMessage.id);
3683
+ if (!requestMessage) {
3684
+ console.error(`No request found for message ID: ${channelMessage.id}`);
3685
+ return;
3686
+ }
3687
+ requestMessage.promise.reject(channelMessage.body);
3688
+ this._messageLookup.delete(channelMessage.id);
3689
+ }
3690
+ break;
3691
+ }
3692
+ }
3693
+ };
3694
+ __publicField(_AppBridgeMessagePort, "DEFAULT_SEND_MESSAGE_TIMEOUT", 30 * 1e3);
3695
+ let AppBridgeMessagePort = _AppBridgeMessagePort;
3696
+ class AppBridgeEventCapability extends AppBridgeCapability {
3697
+ constructor(appBridgeMessagePort) {
3698
+ super(appBridgeMessagePort);
3699
+ __publicField(this, "_eventListeners", {});
3700
+ this.registerMessageHandler("event:publish", this.handlePublishedEvent);
3701
+ }
3702
+ subscribe(topic, callback) {
3703
+ if (!this._eventListeners[topic]) {
3704
+ this._eventListeners[topic] = /* @__PURE__ */ new Set();
3705
+ }
3706
+ if (this._eventListeners[topic].has(callback)) {
3707
+ return () => {
3708
+ this.unsubscribe(topic, callback);
3709
+ };
3710
+ }
3711
+ this._eventListeners[topic].add(callback);
3712
+ return () => {
3713
+ this.unsubscribe(topic, callback);
3714
+ };
3715
+ }
3716
+ unsubscribe(topic, callback) {
3717
+ if (!this._eventListeners[topic]) {
3718
+ return;
3719
+ }
3720
+ this._eventListeners[topic].delete(callback);
3721
+ }
3722
+ async publish(topic, payload) {
3723
+ const eventObject = {
3724
+ topic,
3725
+ payload
3726
+ };
3727
+ return this.sendMessage("event:publish", eventObject);
3728
+ }
3729
+ handlePublishedEvent({ body }) {
3730
+ const event = EventObject.parse(body);
3731
+ const listeners = this._eventListeners[event.topic];
3732
+ listeners == null ? void 0 : listeners.forEach((t) => t(event.payload));
3733
+ }
3734
+ }
3735
+ const MethodCallBody = objectType({
3736
+ methodName: stringType(),
3737
+ args: arrayType(unknownType())
3738
+ });
3739
+ class AppBridgeMethodCapability extends AppBridgeCapability {
3740
+ constructor(appBridgeMessagePort) {
3741
+ super(appBridgeMessagePort);
3742
+ __publicField(this, "_exposedMethods", {});
3743
+ __publicField(this, "_localResponders", {});
3744
+ this.registerMessageHandler("method:call", this.handleMethodCall);
3745
+ }
3746
+ /**
3747
+ * Answer a `call(methodName, ...)` locally instead of sending it to the other side, when the
3748
+ * handler returns a defined value; a returned `undefined` falls through to the remote method.
3749
+ * Lets the bridge serve a locally cached result (e.g. a pushed panel token) without a round-trip,
3750
+ * transparently to the caller. Returns a disposer that removes the responder.
3751
+ */
3752
+ respondLocally(methodName, handler) {
3753
+ this._localResponders[methodName] = handler;
3754
+ return () => {
3755
+ delete this._localResponders[methodName];
3756
+ };
3757
+ }
3758
+ expose(methodName, method) {
3759
+ this._exposedMethods[methodName] = method;
3760
+ return () => {
3761
+ this.removeExposedMethod(methodName);
3762
+ };
3763
+ }
3764
+ removeExposedMethod(methodName) {
3765
+ delete this._exposedMethods[methodName];
3766
+ }
3767
+ isExposed(methodName) {
3768
+ return !!this._exposedMethods[methodName];
3769
+ }
3770
+ async call(methodName, ...args) {
3771
+ const localResponder = this._localResponders[methodName];
3772
+ if (localResponder) {
3773
+ let local = localResponder(...args);
3774
+ if (local instanceof Promise) {
3775
+ local = await local;
3776
+ }
3777
+ if (local !== void 0) {
3778
+ return local;
3779
+ }
3780
+ }
3781
+ return this.sendMessage("method:call", { methodName, args });
3782
+ }
3783
+ async handleMethodCall({ body }) {
3784
+ const methodCallBody = MethodCallBody.parse(body);
3785
+ const method = this._exposedMethods[methodCallBody.methodName];
3786
+ if (!method) {
3787
+ throw new Error(`Method ${methodCallBody.methodName} is not exposed`);
3788
+ }
3789
+ let result = method(...methodCallBody.args);
3790
+ if (result instanceof Promise) {
3791
+ result = await result;
3792
+ }
3793
+ return result;
3794
+ }
3795
+ }
3796
+ const REFRESH_BUFFER_MS = 6e4;
3797
+ class AppBridge extends AppBridgeInfrastructure {
3798
+ constructor(appBridgeMessagePort) {
3799
+ super(appBridgeMessagePort);
3800
+ __publicField(this, "method");
3801
+ __publicField(this, "event");
3802
+ __publicField(this, "cachedAppToken");
3803
+ __publicField(this, "disposers", []);
3804
+ this.method = this.registerCapability(AppBridgeMethodCapability);
3805
+ this.event = this.registerCapability(AppBridgeEventCapability);
3806
+ this.disposers.push(
3807
+ this.event.subscribe("appTokenChanged", (token) => {
3808
+ this.cachedAppToken = { token, expiresAtMs: Date.now() + token.expiresIn * 1e3 };
3809
+ })
3810
+ );
3811
+ this.disposers.push(
3812
+ this.method.respondLocally("getAppToken", () => {
3813
+ if (this.cachedAppToken && this.cachedAppToken.expiresAtMs - Date.now() > REFRESH_BUFFER_MS) {
3814
+ return this.cachedAppToken.token;
3815
+ }
3816
+ return void 0;
3817
+ })
3818
+ );
3819
+ const onWake = () => {
3820
+ if (!document.hidden) {
3821
+ void this.method.call("getAppToken").catch(() => {
3822
+ });
3823
+ }
3824
+ };
3825
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
3826
+ document.addEventListener("visibilitychange", onWake);
3827
+ window.addEventListener("focus", onWake);
3828
+ window.addEventListener("online", onWake);
3829
+ this.disposers.push(() => {
3830
+ document.removeEventListener("visibilitychange", onWake);
3831
+ window.removeEventListener("focus", onWake);
3832
+ window.removeEventListener("online", onWake);
3833
+ });
3834
+ }
3835
+ }
3836
+ /** Removes the panel-token cache subscription and wake listeners. Call when tearing the bridge down. */
3837
+ dispose() {
3838
+ this.disposers.splice(0).forEach((dispose) => dispose());
3839
+ }
3840
+ }
3841
+ function createAppBridge() {
3842
+ return new Promise((resolve) => {
3843
+ const messageChannel = new MessageChannel();
3844
+ const appBridgeMessagePort = new AppBridgeMessagePort(messageChannel.port2);
3845
+ console.debug("[AppBridge] Creating app bridge...");
3846
+ window.parent.postMessage(
3847
+ {
3848
+ type: MessageType.Enum.HANDSHAKE
3849
+ },
3850
+ "*",
3851
+ [messageChannel.port1]
3852
+ );
3853
+ console.debug("[AppBridge] Waiting for handshake from host...");
3854
+ appBridgeMessagePort.registerMessageHandler("lifecycle:handshake", () => {
3855
+ console.debug("[AppBridge] Handshake completed!");
3856
+ resolve(new AppBridge(appBridgeMessagePort));
3857
+ });
3858
+ });
3859
+ }
3860
+ export {
3861
+ AppBridge,
3862
+ AppBridgeCapability,
3863
+ AppBridgeEventCapability,
3864
+ AppBridgeInfrastructure,
3865
+ AppBridgeMessagePort,
3866
+ AppBridgeMethodCapability,
3867
+ ChannelMessage,
3868
+ EventObject,
3869
+ MessageType,
3870
+ createAppBridge
3871
+ };
3872
+ //# sourceMappingURL=main.js.map