@payabli/component-contracts 0.1.0

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.
package/dist/index.js ADDED
@@ -0,0 +1,1721 @@
1
+ const MESSAGE_SOURCE = 'payabli';
2
+ const MESSAGE_VERSION = 1;
3
+
4
+ var _a;
5
+ function $constructor(name, initializer, params) {
6
+ function init(inst, def) {
7
+ if (!inst._zod) {
8
+ Object.defineProperty(inst, "_zod", {
9
+ value: {
10
+ def,
11
+ constr: _,
12
+ traits: new Set(),
13
+ },
14
+ enumerable: false,
15
+ });
16
+ }
17
+ if (inst._zod.traits.has(name)) {
18
+ return;
19
+ }
20
+ inst._zod.traits.add(name);
21
+ initializer(inst, def);
22
+ // support prototype modifications
23
+ const proto = _.prototype;
24
+ const keys = Object.keys(proto);
25
+ for (let i = 0; i < keys.length; i++) {
26
+ const k = keys[i];
27
+ if (!(k in inst)) {
28
+ inst[k] = proto[k].bind(inst);
29
+ }
30
+ }
31
+ }
32
+ // doesn't work if Parent has a constructor with arguments
33
+ const Parent = params?.Parent ?? Object;
34
+ class Definition extends Parent {
35
+ }
36
+ Object.defineProperty(Definition, "name", { value: name });
37
+ function _(def) {
38
+ var _a;
39
+ const inst = params?.Parent ? new Definition() : this;
40
+ init(inst, def);
41
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
42
+ for (const fn of inst._zod.deferred) {
43
+ fn();
44
+ }
45
+ return inst;
46
+ }
47
+ Object.defineProperty(_, "init", { value: init });
48
+ Object.defineProperty(_, Symbol.hasInstance, {
49
+ value: (inst) => {
50
+ if (params?.Parent && inst instanceof params.Parent)
51
+ return true;
52
+ return inst?._zod?.traits?.has(name);
53
+ },
54
+ });
55
+ Object.defineProperty(_, "name", { value: name });
56
+ return _;
57
+ }
58
+ class $ZodAsyncError extends Error {
59
+ constructor() {
60
+ super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
61
+ }
62
+ }
63
+ (_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});
64
+ const globalConfig = globalThis.__zod_globalConfig;
65
+ function config(newConfig) {
66
+ return globalConfig;
67
+ }
68
+
69
+ function getEnumValues(entries) {
70
+ const numericValues = Object.values(entries).filter((v) => typeof v === "number");
71
+ const values = Object.entries(entries)
72
+ .filter(([k, _]) => numericValues.indexOf(+k) === -1)
73
+ .map(([_, v]) => v);
74
+ return values;
75
+ }
76
+ function joinValues(array, separator = "|") {
77
+ return array.map((val) => stringifyPrimitive(val)).join(separator);
78
+ }
79
+ function jsonStringifyReplacer(_, value) {
80
+ if (typeof value === "bigint")
81
+ return value.toString();
82
+ return value;
83
+ }
84
+ function cached(getter) {
85
+ return {
86
+ get value() {
87
+ {
88
+ const value = getter();
89
+ Object.defineProperty(this, "value", { value });
90
+ return value;
91
+ }
92
+ },
93
+ };
94
+ }
95
+ function cleanRegex(source) {
96
+ const start = source.startsWith("^") ? 1 : 0;
97
+ const end = source.endsWith("$") ? source.length - 1 : source.length;
98
+ return source.slice(start, end);
99
+ }
100
+ const EVALUATING = /* @__PURE__*/ Symbol("evaluating");
101
+ function defineLazy(object, key, getter) {
102
+ let value = undefined;
103
+ Object.defineProperty(object, key, {
104
+ get() {
105
+ if (value === EVALUATING) {
106
+ // Circular reference detected, return undefined to break the cycle
107
+ return undefined;
108
+ }
109
+ if (value === undefined) {
110
+ value = EVALUATING;
111
+ value = getter();
112
+ }
113
+ return value;
114
+ },
115
+ set(v) {
116
+ Object.defineProperty(object, key, {
117
+ value: v,
118
+ // configurable: true,
119
+ });
120
+ // object[key] = v;
121
+ },
122
+ configurable: true,
123
+ });
124
+ }
125
+ const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { });
126
+ function isObject(data) {
127
+ return typeof data === "object" && data !== null && !Array.isArray(data);
128
+ }
129
+ function isPlainObject(o) {
130
+ if (isObject(o) === false)
131
+ return false;
132
+ // modified constructor
133
+ const ctor = o.constructor;
134
+ if (ctor === undefined)
135
+ return true;
136
+ if (typeof ctor !== "function")
137
+ return true;
138
+ // modified prototype
139
+ const prot = ctor.prototype;
140
+ if (isObject(prot) === false)
141
+ return false;
142
+ // ctor doesn't have static `isPrototypeOf`
143
+ if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
144
+ return false;
145
+ }
146
+ return true;
147
+ }
148
+ const propertyKeyTypes = /* @__PURE__*/ new Set(["string", "number", "symbol"]);
149
+ function escapeRegex(str) {
150
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
151
+ }
152
+ // zod-specific utils
153
+ function clone(inst, def, params) {
154
+ const cl = new inst._zod.constr(def ?? inst._zod.def);
155
+ if (!def || params?.parent)
156
+ cl._zod.parent = inst;
157
+ return cl;
158
+ }
159
+ function normalizeParams(_params) {
160
+ const params = _params;
161
+ if (!params)
162
+ return {};
163
+ if (typeof params === "string")
164
+ return { error: () => params };
165
+ if (params?.message !== undefined) {
166
+ if (params?.error !== undefined)
167
+ throw new Error("Cannot specify both `message` and `error` params");
168
+ params.error = params.message;
169
+ }
170
+ delete params.message;
171
+ if (typeof params.error === "string")
172
+ return { ...params, error: () => params.error };
173
+ return params;
174
+ }
175
+ function stringifyPrimitive(value) {
176
+ if (typeof value === "bigint")
177
+ return value.toString() + "n";
178
+ if (typeof value === "string")
179
+ return `"${value}"`;
180
+ return `${value}`;
181
+ }
182
+ function optionalKeys(shape) {
183
+ return Object.keys(shape).filter((k) => {
184
+ return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
185
+ });
186
+ }
187
+ // invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom
188
+ function aborted(x, startIndex = 0) {
189
+ if (x.aborted === true)
190
+ return true;
191
+ for (let i = startIndex; i < x.issues.length; i++) {
192
+ if (x.issues[i]?.continue !== true) {
193
+ return true;
194
+ }
195
+ }
196
+ return false;
197
+ }
198
+ // Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined).
199
+ // Used to respect `abort: true` in .refine() even for checks that have a `when` function.
200
+ function explicitlyAborted(x, startIndex = 0) {
201
+ if (x.aborted === true)
202
+ return true;
203
+ for (let i = startIndex; i < x.issues.length; i++) {
204
+ if (x.issues[i]?.continue === false) {
205
+ return true;
206
+ }
207
+ }
208
+ return false;
209
+ }
210
+ function prefixIssues(path, issues) {
211
+ return issues.map((iss) => {
212
+ var _a;
213
+ (_a = iss).path ?? (_a.path = []);
214
+ iss.path.unshift(path);
215
+ return iss;
216
+ });
217
+ }
218
+ function unwrapMessage(message) {
219
+ return typeof message === "string" ? message : message?.message;
220
+ }
221
+ function finalizeIssue(iss, ctx, config) {
222
+ const message = iss.message
223
+ ? iss.message
224
+ : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??
225
+ unwrapMessage(ctx?.error?.(iss)) ??
226
+ unwrapMessage(config.customError?.(iss)) ??
227
+ unwrapMessage(config.localeError?.(iss)) ??
228
+ "Invalid input");
229
+ const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;
230
+ rest.path ?? (rest.path = []);
231
+ rest.message = message;
232
+ if (ctx?.reportInput) {
233
+ rest.input = _input;
234
+ }
235
+ return rest;
236
+ }
237
+ function parsedType(data) {
238
+ const t = typeof data;
239
+ switch (t) {
240
+ case "number": {
241
+ return Number.isNaN(data) ? "nan" : "number";
242
+ }
243
+ case "object": {
244
+ if (data === null) {
245
+ return "null";
246
+ }
247
+ if (Array.isArray(data)) {
248
+ return "array";
249
+ }
250
+ const obj = data;
251
+ if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) {
252
+ return obj.constructor.name;
253
+ }
254
+ }
255
+ }
256
+ return t;
257
+ }
258
+
259
+ const initializer = (inst, def) => {
260
+ inst.name = "$ZodError";
261
+ Object.defineProperty(inst, "_zod", {
262
+ value: inst._zod,
263
+ enumerable: false,
264
+ });
265
+ Object.defineProperty(inst, "issues", {
266
+ value: def,
267
+ enumerable: false,
268
+ });
269
+ inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
270
+ Object.defineProperty(inst, "toString", {
271
+ value: () => inst.message,
272
+ enumerable: false,
273
+ });
274
+ };
275
+ const $ZodError = $constructor("$ZodError", initializer);
276
+ const $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
277
+
278
+ const _parse = (_Err) => (schema, value, _ctx, _params) => {
279
+ const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
280
+ const result = schema._zod.run({ value, issues: [] }, ctx);
281
+ if (result instanceof Promise) {
282
+ throw new $ZodAsyncError();
283
+ }
284
+ if (result.issues.length) {
285
+ const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
286
+ captureStackTrace(e, _params?.callee);
287
+ throw e;
288
+ }
289
+ return result.value;
290
+ };
291
+ const parse = /* @__PURE__*/ _parse($ZodRealError);
292
+ const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
293
+ const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
294
+ let result = schema._zod.run({ value, issues: [] }, ctx);
295
+ if (result instanceof Promise)
296
+ result = await result;
297
+ if (result.issues.length) {
298
+ const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
299
+ captureStackTrace(e, params?.callee);
300
+ throw e;
301
+ }
302
+ return result.value;
303
+ };
304
+ const parseAsync = /* @__PURE__*/ _parseAsync($ZodRealError);
305
+ const _safeParse = (_Err) => (schema, value, _ctx) => {
306
+ const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
307
+ const result = schema._zod.run({ value, issues: [] }, ctx);
308
+ if (result instanceof Promise) {
309
+ throw new $ZodAsyncError();
310
+ }
311
+ return result.issues.length
312
+ ? {
313
+ success: false,
314
+ error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))),
315
+ }
316
+ : { success: true, data: result.value };
317
+ };
318
+ const safeParse = /* @__PURE__*/ _safeParse($ZodRealError);
319
+ const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
320
+ const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
321
+ let result = schema._zod.run({ value, issues: [] }, ctx);
322
+ if (result instanceof Promise)
323
+ result = await result;
324
+ return result.issues.length
325
+ ? {
326
+ success: false,
327
+ error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))),
328
+ }
329
+ : { success: true, data: result.value };
330
+ };
331
+ const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError);
332
+
333
+ const string$1 = (params) => {
334
+ const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
335
+ return new RegExp(`^${regex}$`);
336
+ };
337
+ const number$1 = /^-?\d+(?:\.\d+)?$/;
338
+ const boolean$1 = /^(?:true|false)$/i;
339
+
340
+ const version = {
341
+ major: 4,
342
+ minor: 4,
343
+ patch: 3,
344
+ };
345
+
346
+ const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
347
+ var _a;
348
+ inst ?? (inst = {});
349
+ inst._zod.def = def; // set _def property
350
+ inst._zod.bag = inst._zod.bag || {}; // initialize _bag object
351
+ inst._zod.version = version;
352
+ const checks = [...(inst._zod.def.checks ?? [])];
353
+ // if inst is itself a checks.$ZodCheck, run it as a check
354
+ if (inst._zod.traits.has("$ZodCheck")) {
355
+ checks.unshift(inst);
356
+ }
357
+ for (const ch of checks) {
358
+ for (const fn of ch._zod.onattach) {
359
+ fn(inst);
360
+ }
361
+ }
362
+ if (checks.length === 0) {
363
+ // deferred initializer
364
+ // inst._zod.parse is not yet defined
365
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
366
+ inst._zod.deferred?.push(() => {
367
+ inst._zod.run = inst._zod.parse;
368
+ });
369
+ }
370
+ else {
371
+ const runChecks = (payload, checks, ctx) => {
372
+ let isAborted = aborted(payload);
373
+ let asyncResult;
374
+ for (const ch of checks) {
375
+ if (ch._zod.def.when) {
376
+ if (explicitlyAborted(payload))
377
+ continue;
378
+ const shouldRun = ch._zod.def.when(payload);
379
+ if (!shouldRun)
380
+ continue;
381
+ }
382
+ else if (isAborted) {
383
+ continue;
384
+ }
385
+ const currLen = payload.issues.length;
386
+ const _ = ch._zod.check(payload);
387
+ if (_ instanceof Promise && ctx?.async === false) {
388
+ throw new $ZodAsyncError();
389
+ }
390
+ if (asyncResult || _ instanceof Promise) {
391
+ asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
392
+ await _;
393
+ const nextLen = payload.issues.length;
394
+ if (nextLen === currLen)
395
+ return;
396
+ if (!isAborted)
397
+ isAborted = aborted(payload, currLen);
398
+ });
399
+ }
400
+ else {
401
+ const nextLen = payload.issues.length;
402
+ if (nextLen === currLen)
403
+ continue;
404
+ if (!isAborted)
405
+ isAborted = aborted(payload, currLen);
406
+ }
407
+ }
408
+ if (asyncResult) {
409
+ return asyncResult.then(() => {
410
+ return payload;
411
+ });
412
+ }
413
+ return payload;
414
+ };
415
+ const handleCanaryResult = (canary, payload, ctx) => {
416
+ // abort if the canary is aborted
417
+ if (aborted(canary)) {
418
+ canary.aborted = true;
419
+ return canary;
420
+ }
421
+ // run checks first, then
422
+ const checkResult = runChecks(payload, checks, ctx);
423
+ if (checkResult instanceof Promise) {
424
+ if (ctx.async === false)
425
+ throw new $ZodAsyncError();
426
+ return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));
427
+ }
428
+ return inst._zod.parse(checkResult, ctx);
429
+ };
430
+ inst._zod.run = (payload, ctx) => {
431
+ if (ctx.skipChecks) {
432
+ return inst._zod.parse(payload, ctx);
433
+ }
434
+ if (ctx.direction === "backward") {
435
+ // run canary
436
+ // initial pass (no checks)
437
+ const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });
438
+ if (canary instanceof Promise) {
439
+ return canary.then((canary) => {
440
+ return handleCanaryResult(canary, payload, ctx);
441
+ });
442
+ }
443
+ return handleCanaryResult(canary, payload, ctx);
444
+ }
445
+ // forward
446
+ const result = inst._zod.parse(payload, ctx);
447
+ if (result instanceof Promise) {
448
+ if (ctx.async === false)
449
+ throw new $ZodAsyncError();
450
+ return result.then((result) => runChecks(result, checks, ctx));
451
+ }
452
+ return runChecks(result, checks, ctx);
453
+ };
454
+ }
455
+ // Lazy initialize ~standard to avoid creating objects for every schema
456
+ defineLazy(inst, "~standard", () => ({
457
+ validate: (value) => {
458
+ try {
459
+ const r = safeParse(inst, value);
460
+ return r.success ? { value: r.data } : { issues: r.error?.issues };
461
+ }
462
+ catch (_) {
463
+ return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));
464
+ }
465
+ },
466
+ vendor: "zod",
467
+ version: 1,
468
+ }));
469
+ });
470
+ const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => {
471
+ $ZodType.init(inst, def);
472
+ inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? string$1(inst._zod.bag);
473
+ inst._zod.parse = (payload, _) => {
474
+ if (def.coerce)
475
+ try {
476
+ payload.value = String(payload.value);
477
+ }
478
+ catch (_) { }
479
+ if (typeof payload.value === "string")
480
+ return payload;
481
+ payload.issues.push({
482
+ expected: "string",
483
+ code: "invalid_type",
484
+ input: payload.value,
485
+ inst,
486
+ });
487
+ return payload;
488
+ };
489
+ });
490
+ const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => {
491
+ $ZodType.init(inst, def);
492
+ inst._zod.pattern = inst._zod.bag.pattern ?? number$1;
493
+ inst._zod.parse = (payload, _ctx) => {
494
+ if (def.coerce)
495
+ try {
496
+ payload.value = Number(payload.value);
497
+ }
498
+ catch (_) { }
499
+ const input = payload.value;
500
+ if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
501
+ return payload;
502
+ }
503
+ const received = typeof input === "number"
504
+ ? Number.isNaN(input)
505
+ ? "NaN"
506
+ : !Number.isFinite(input)
507
+ ? "Infinity"
508
+ : undefined
509
+ : undefined;
510
+ payload.issues.push({
511
+ expected: "number",
512
+ code: "invalid_type",
513
+ input,
514
+ inst,
515
+ ...(received ? { received } : {}),
516
+ });
517
+ return payload;
518
+ };
519
+ });
520
+ const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => {
521
+ $ZodType.init(inst, def);
522
+ inst._zod.pattern = boolean$1;
523
+ inst._zod.parse = (payload, _ctx) => {
524
+ if (def.coerce)
525
+ try {
526
+ payload.value = Boolean(payload.value);
527
+ }
528
+ catch (_) { }
529
+ const input = payload.value;
530
+ if (typeof input === "boolean")
531
+ return payload;
532
+ payload.issues.push({
533
+ expected: "boolean",
534
+ code: "invalid_type",
535
+ input,
536
+ inst,
537
+ });
538
+ return payload;
539
+ };
540
+ });
541
+ const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => {
542
+ $ZodType.init(inst, def);
543
+ inst._zod.parse = (payload) => payload;
544
+ });
545
+ function handleArrayResult(result, final, index) {
546
+ if (result.issues.length) {
547
+ final.issues.push(...prefixIssues(index, result.issues));
548
+ }
549
+ final.value[index] = result.value;
550
+ }
551
+ const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => {
552
+ $ZodType.init(inst, def);
553
+ inst._zod.parse = (payload, ctx) => {
554
+ const input = payload.value;
555
+ if (!Array.isArray(input)) {
556
+ payload.issues.push({
557
+ expected: "array",
558
+ code: "invalid_type",
559
+ input,
560
+ inst,
561
+ });
562
+ return payload;
563
+ }
564
+ payload.value = Array(input.length);
565
+ const proms = [];
566
+ for (let i = 0; i < input.length; i++) {
567
+ const item = input[i];
568
+ const result = def.element._zod.run({
569
+ value: item,
570
+ issues: [],
571
+ }, ctx);
572
+ if (result instanceof Promise) {
573
+ proms.push(result.then((result) => handleArrayResult(result, payload, i)));
574
+ }
575
+ else {
576
+ handleArrayResult(result, payload, i);
577
+ }
578
+ }
579
+ if (proms.length) {
580
+ return Promise.all(proms).then(() => payload);
581
+ }
582
+ return payload; //handleArrayResultsAsync(parseResults, final);
583
+ };
584
+ });
585
+ function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {
586
+ const isPresent = key in input;
587
+ if (result.issues.length) {
588
+ // For optional-in/out schemas, ignore errors on absent keys.
589
+ if (isOptionalIn && isOptionalOut && !isPresent) {
590
+ return;
591
+ }
592
+ final.issues.push(...prefixIssues(key, result.issues));
593
+ }
594
+ if (!isPresent && !isOptionalIn) {
595
+ if (!result.issues.length) {
596
+ final.issues.push({
597
+ code: "invalid_type",
598
+ expected: "nonoptional",
599
+ input: undefined,
600
+ path: [key],
601
+ });
602
+ }
603
+ return;
604
+ }
605
+ if (result.value === undefined) {
606
+ if (isPresent) {
607
+ final.value[key] = undefined;
608
+ }
609
+ }
610
+ else {
611
+ final.value[key] = result.value;
612
+ }
613
+ }
614
+ function normalizeDef(def) {
615
+ const keys = Object.keys(def.shape);
616
+ for (const k of keys) {
617
+ if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) {
618
+ throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
619
+ }
620
+ }
621
+ const okeys = optionalKeys(def.shape);
622
+ return {
623
+ ...def,
624
+ keys,
625
+ keySet: new Set(keys),
626
+ numKeys: keys.length,
627
+ optionalKeys: new Set(okeys),
628
+ };
629
+ }
630
+ function handleCatchall(proms, input, payload, ctx, def, inst) {
631
+ const unrecognized = [];
632
+ const keySet = def.keySet;
633
+ const _catchall = def.catchall._zod;
634
+ const t = _catchall.def.type;
635
+ const isOptionalIn = _catchall.optin === "optional";
636
+ const isOptionalOut = _catchall.optout === "optional";
637
+ for (const key in input) {
638
+ // skip __proto__ so it can't replace the result prototype via the
639
+ // assignment setter on the plain {} we build into
640
+ if (key === "__proto__")
641
+ continue;
642
+ if (keySet.has(key))
643
+ continue;
644
+ if (t === "never") {
645
+ unrecognized.push(key);
646
+ continue;
647
+ }
648
+ const r = _catchall.run({ value: input[key], issues: [] }, ctx);
649
+ if (r instanceof Promise) {
650
+ proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));
651
+ }
652
+ else {
653
+ handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
654
+ }
655
+ }
656
+ if (unrecognized.length) {
657
+ payload.issues.push({
658
+ code: "unrecognized_keys",
659
+ keys: unrecognized,
660
+ input,
661
+ inst,
662
+ });
663
+ }
664
+ if (!proms.length)
665
+ return payload;
666
+ return Promise.all(proms).then(() => {
667
+ return payload;
668
+ });
669
+ }
670
+ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
671
+ // requires cast because technically $ZodObject doesn't extend
672
+ $ZodType.init(inst, def);
673
+ // const sh = def.shape;
674
+ const desc = Object.getOwnPropertyDescriptor(def, "shape");
675
+ if (!desc?.get) {
676
+ const sh = def.shape;
677
+ Object.defineProperty(def, "shape", {
678
+ get: () => {
679
+ const newSh = { ...sh };
680
+ Object.defineProperty(def, "shape", {
681
+ value: newSh,
682
+ });
683
+ return newSh;
684
+ },
685
+ });
686
+ }
687
+ const _normalized = cached(() => normalizeDef(def));
688
+ defineLazy(inst._zod, "propValues", () => {
689
+ const shape = def.shape;
690
+ const propValues = {};
691
+ for (const key in shape) {
692
+ const field = shape[key]._zod;
693
+ if (field.values) {
694
+ propValues[key] ?? (propValues[key] = new Set());
695
+ for (const v of field.values)
696
+ propValues[key].add(v);
697
+ }
698
+ }
699
+ return propValues;
700
+ });
701
+ const isObject$1 = isObject;
702
+ const catchall = def.catchall;
703
+ let value;
704
+ inst._zod.parse = (payload, ctx) => {
705
+ value ?? (value = _normalized.value);
706
+ const input = payload.value;
707
+ if (!isObject$1(input)) {
708
+ payload.issues.push({
709
+ expected: "object",
710
+ code: "invalid_type",
711
+ input,
712
+ inst,
713
+ });
714
+ return payload;
715
+ }
716
+ payload.value = {};
717
+ const proms = [];
718
+ const shape = value.shape;
719
+ for (const key of value.keys) {
720
+ const el = shape[key];
721
+ const isOptionalIn = el._zod.optin === "optional";
722
+ const isOptionalOut = el._zod.optout === "optional";
723
+ const r = el._zod.run({ value: input[key], issues: [] }, ctx);
724
+ if (r instanceof Promise) {
725
+ proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));
726
+ }
727
+ else {
728
+ handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
729
+ }
730
+ }
731
+ if (!catchall) {
732
+ return proms.length ? Promise.all(proms).then(() => payload) : payload;
733
+ }
734
+ return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
735
+ };
736
+ });
737
+ function handleUnionResults(results, final, inst, ctx) {
738
+ for (const result of results) {
739
+ if (result.issues.length === 0) {
740
+ final.value = result.value;
741
+ return final;
742
+ }
743
+ }
744
+ const nonaborted = results.filter((r) => !aborted(r));
745
+ if (nonaborted.length === 1) {
746
+ final.value = nonaborted[0].value;
747
+ return nonaborted[0];
748
+ }
749
+ final.issues.push({
750
+ code: "invalid_union",
751
+ input: final.value,
752
+ inst,
753
+ errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))),
754
+ });
755
+ return final;
756
+ }
757
+ const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => {
758
+ $ZodType.init(inst, def);
759
+ defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined);
760
+ defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined);
761
+ defineLazy(inst._zod, "values", () => {
762
+ if (def.options.every((o) => o._zod.values)) {
763
+ return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
764
+ }
765
+ return undefined;
766
+ });
767
+ defineLazy(inst._zod, "pattern", () => {
768
+ if (def.options.every((o) => o._zod.pattern)) {
769
+ const patterns = def.options.map((o) => o._zod.pattern);
770
+ return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
771
+ }
772
+ return undefined;
773
+ });
774
+ const first = def.options.length === 1 ? def.options[0]._zod.run : null;
775
+ inst._zod.parse = (payload, ctx) => {
776
+ if (first) {
777
+ return first(payload, ctx);
778
+ }
779
+ let async = false;
780
+ const results = [];
781
+ for (const option of def.options) {
782
+ const result = option._zod.run({
783
+ value: payload.value,
784
+ issues: [],
785
+ }, ctx);
786
+ if (result instanceof Promise) {
787
+ results.push(result);
788
+ async = true;
789
+ }
790
+ else {
791
+ if (result.issues.length === 0)
792
+ return result;
793
+ results.push(result);
794
+ }
795
+ }
796
+ if (!async)
797
+ return handleUnionResults(results, payload, inst, ctx);
798
+ return Promise.all(results).then((results) => {
799
+ return handleUnionResults(results, payload, inst, ctx);
800
+ });
801
+ };
802
+ });
803
+ const $ZodDiscriminatedUnion =
804
+ /*@__PURE__*/
805
+ $constructor("$ZodDiscriminatedUnion", (inst, def) => {
806
+ def.inclusive = false;
807
+ $ZodUnion.init(inst, def);
808
+ const _super = inst._zod.parse;
809
+ defineLazy(inst._zod, "propValues", () => {
810
+ const propValues = {};
811
+ for (const option of def.options) {
812
+ const pv = option._zod.propValues;
813
+ if (!pv || Object.keys(pv).length === 0)
814
+ throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
815
+ for (const [k, v] of Object.entries(pv)) {
816
+ if (!propValues[k])
817
+ propValues[k] = new Set();
818
+ for (const val of v) {
819
+ propValues[k].add(val);
820
+ }
821
+ }
822
+ }
823
+ return propValues;
824
+ });
825
+ const disc = cached(() => {
826
+ const opts = def.options;
827
+ const map = new Map();
828
+ for (const o of opts) {
829
+ const values = o._zod.propValues?.[def.discriminator];
830
+ if (!values || values.size === 0)
831
+ throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
832
+ for (const v of values) {
833
+ if (map.has(v)) {
834
+ throw new Error(`Duplicate discriminator value "${String(v)}"`);
835
+ }
836
+ map.set(v, o);
837
+ }
838
+ }
839
+ return map;
840
+ });
841
+ inst._zod.parse = (payload, ctx) => {
842
+ const input = payload.value;
843
+ if (!isObject(input)) {
844
+ payload.issues.push({
845
+ code: "invalid_type",
846
+ expected: "object",
847
+ input,
848
+ inst,
849
+ });
850
+ return payload;
851
+ }
852
+ const opt = disc.value.get(input?.[def.discriminator]);
853
+ if (opt) {
854
+ return opt._zod.run(payload, ctx);
855
+ }
856
+ // Fall back to union matching when the fast discriminator path fails:
857
+ // - explicitly enabled via unionFallback, or
858
+ // - during backward direction (encode), since codec-based discriminators
859
+ // have different values in forward vs backward directions
860
+ if (def.unionFallback || ctx.direction === "backward") {
861
+ return _super(payload, ctx);
862
+ }
863
+ // no matching discriminator
864
+ payload.issues.push({
865
+ code: "invalid_union",
866
+ errors: [],
867
+ note: "No matching discriminator",
868
+ discriminator: def.discriminator,
869
+ options: Array.from(disc.value.keys()),
870
+ input,
871
+ path: [def.discriminator],
872
+ inst,
873
+ });
874
+ return payload;
875
+ };
876
+ });
877
+ const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => {
878
+ $ZodType.init(inst, def);
879
+ inst._zod.parse = (payload, ctx) => {
880
+ const input = payload.value;
881
+ if (!isPlainObject(input)) {
882
+ payload.issues.push({
883
+ expected: "record",
884
+ code: "invalid_type",
885
+ input,
886
+ inst,
887
+ });
888
+ return payload;
889
+ }
890
+ const proms = [];
891
+ const values = def.keyType._zod.values;
892
+ if (values) {
893
+ payload.value = {};
894
+ const recordKeys = new Set();
895
+ for (const key of values) {
896
+ if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
897
+ recordKeys.add(typeof key === "number" ? key.toString() : key);
898
+ const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
899
+ if (keyResult instanceof Promise) {
900
+ throw new Error("Async schemas not supported in object keys currently");
901
+ }
902
+ if (keyResult.issues.length) {
903
+ payload.issues.push({
904
+ code: "invalid_key",
905
+ origin: "record",
906
+ issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
907
+ input: key,
908
+ path: [key],
909
+ inst,
910
+ });
911
+ continue;
912
+ }
913
+ const outKey = keyResult.value;
914
+ const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
915
+ if (result instanceof Promise) {
916
+ proms.push(result.then((result) => {
917
+ if (result.issues.length) {
918
+ payload.issues.push(...prefixIssues(key, result.issues));
919
+ }
920
+ payload.value[outKey] = result.value;
921
+ }));
922
+ }
923
+ else {
924
+ if (result.issues.length) {
925
+ payload.issues.push(...prefixIssues(key, result.issues));
926
+ }
927
+ payload.value[outKey] = result.value;
928
+ }
929
+ }
930
+ }
931
+ let unrecognized;
932
+ for (const key in input) {
933
+ if (!recordKeys.has(key)) {
934
+ unrecognized = unrecognized ?? [];
935
+ unrecognized.push(key);
936
+ }
937
+ }
938
+ if (unrecognized && unrecognized.length > 0) {
939
+ payload.issues.push({
940
+ code: "unrecognized_keys",
941
+ input,
942
+ inst,
943
+ keys: unrecognized,
944
+ });
945
+ }
946
+ }
947
+ else {
948
+ payload.value = {};
949
+ // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()
950
+ for (const key of Reflect.ownKeys(input)) {
951
+ if (key === "__proto__")
952
+ continue;
953
+ if (!Object.prototype.propertyIsEnumerable.call(input, key))
954
+ continue;
955
+ let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
956
+ if (keyResult instanceof Promise) {
957
+ throw new Error("Async schemas not supported in object keys currently");
958
+ }
959
+ // Numeric string fallback: if key is a numeric string and failed, retry with Number(key)
960
+ // This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals
961
+ const checkNumericKey = typeof key === "string" && number$1.test(key) && keyResult.issues.length;
962
+ if (checkNumericKey) {
963
+ const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);
964
+ if (retryResult instanceof Promise) {
965
+ throw new Error("Async schemas not supported in object keys currently");
966
+ }
967
+ if (retryResult.issues.length === 0) {
968
+ keyResult = retryResult;
969
+ }
970
+ }
971
+ if (keyResult.issues.length) {
972
+ if (def.mode === "loose") {
973
+ // Pass through unchanged
974
+ payload.value[key] = input[key];
975
+ }
976
+ else {
977
+ // Default "strict" behavior: error on invalid key
978
+ payload.issues.push({
979
+ code: "invalid_key",
980
+ origin: "record",
981
+ issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
982
+ input: key,
983
+ path: [key],
984
+ inst,
985
+ });
986
+ }
987
+ continue;
988
+ }
989
+ const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
990
+ if (result instanceof Promise) {
991
+ proms.push(result.then((result) => {
992
+ if (result.issues.length) {
993
+ payload.issues.push(...prefixIssues(key, result.issues));
994
+ }
995
+ payload.value[keyResult.value] = result.value;
996
+ }));
997
+ }
998
+ else {
999
+ if (result.issues.length) {
1000
+ payload.issues.push(...prefixIssues(key, result.issues));
1001
+ }
1002
+ payload.value[keyResult.value] = result.value;
1003
+ }
1004
+ }
1005
+ }
1006
+ if (proms.length) {
1007
+ return Promise.all(proms).then(() => payload);
1008
+ }
1009
+ return payload;
1010
+ };
1011
+ });
1012
+ const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => {
1013
+ $ZodType.init(inst, def);
1014
+ const values = getEnumValues(def.entries);
1015
+ const valuesSet = new Set(values);
1016
+ inst._zod.values = valuesSet;
1017
+ inst._zod.pattern = new RegExp(`^(${values
1018
+ .filter((k) => propertyKeyTypes.has(typeof k))
1019
+ .map((o) => (typeof o === "string" ? escapeRegex(o) : o.toString()))
1020
+ .join("|")})$`);
1021
+ inst._zod.parse = (payload, _ctx) => {
1022
+ const input = payload.value;
1023
+ if (valuesSet.has(input)) {
1024
+ return payload;
1025
+ }
1026
+ payload.issues.push({
1027
+ code: "invalid_value",
1028
+ values,
1029
+ input,
1030
+ inst,
1031
+ });
1032
+ return payload;
1033
+ };
1034
+ });
1035
+ const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => {
1036
+ $ZodType.init(inst, def);
1037
+ if (def.values.length === 0) {
1038
+ throw new Error("Cannot create literal schema with no valid values");
1039
+ }
1040
+ const values = new Set(def.values);
1041
+ inst._zod.values = values;
1042
+ inst._zod.pattern = new RegExp(`^(${def.values
1043
+ .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)))
1044
+ .join("|")})$`);
1045
+ inst._zod.parse = (payload, _ctx) => {
1046
+ const input = payload.value;
1047
+ if (values.has(input)) {
1048
+ return payload;
1049
+ }
1050
+ payload.issues.push({
1051
+ code: "invalid_value",
1052
+ values: def.values,
1053
+ input,
1054
+ inst,
1055
+ });
1056
+ return payload;
1057
+ };
1058
+ });
1059
+ function handleOptionalResult(result, input) {
1060
+ if (input === undefined && (result.issues.length || result.fallback)) {
1061
+ return { issues: [], value: undefined };
1062
+ }
1063
+ return result;
1064
+ }
1065
+ const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => {
1066
+ $ZodType.init(inst, def);
1067
+ inst._zod.optin = "optional";
1068
+ inst._zod.optout = "optional";
1069
+ defineLazy(inst._zod, "values", () => {
1070
+ return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;
1071
+ });
1072
+ defineLazy(inst._zod, "pattern", () => {
1073
+ const pattern = def.innerType._zod.pattern;
1074
+ return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined;
1075
+ });
1076
+ inst._zod.parse = (payload, ctx) => {
1077
+ if (def.innerType._zod.optin === "optional") {
1078
+ const input = payload.value;
1079
+ const result = def.innerType._zod.run(payload, ctx);
1080
+ if (result instanceof Promise)
1081
+ return result.then((r) => handleOptionalResult(r, input));
1082
+ return handleOptionalResult(result, input);
1083
+ }
1084
+ if (payload.value === undefined) {
1085
+ return payload;
1086
+ }
1087
+ return def.innerType._zod.run(payload, ctx);
1088
+ };
1089
+ });
1090
+
1091
+ const error = () => {
1092
+ const Sizable = {
1093
+ string: { unit: "characters", verb: "to have" },
1094
+ file: { unit: "bytes", verb: "to have" },
1095
+ array: { unit: "items", verb: "to have" },
1096
+ set: { unit: "items", verb: "to have" },
1097
+ map: { unit: "entries", verb: "to have" },
1098
+ };
1099
+ function getSizing(origin) {
1100
+ return Sizable[origin] ?? null;
1101
+ }
1102
+ const FormatDictionary = {
1103
+ regex: "input",
1104
+ email: "email address",
1105
+ url: "URL",
1106
+ emoji: "emoji",
1107
+ uuid: "UUID",
1108
+ uuidv4: "UUIDv4",
1109
+ uuidv6: "UUIDv6",
1110
+ nanoid: "nanoid",
1111
+ guid: "GUID",
1112
+ cuid: "cuid",
1113
+ cuid2: "cuid2",
1114
+ ulid: "ULID",
1115
+ xid: "XID",
1116
+ ksuid: "KSUID",
1117
+ datetime: "ISO datetime",
1118
+ date: "ISO date",
1119
+ time: "ISO time",
1120
+ duration: "ISO duration",
1121
+ ipv4: "IPv4 address",
1122
+ ipv6: "IPv6 address",
1123
+ mac: "MAC address",
1124
+ cidrv4: "IPv4 range",
1125
+ cidrv6: "IPv6 range",
1126
+ base64: "base64-encoded string",
1127
+ base64url: "base64url-encoded string",
1128
+ json_string: "JSON string",
1129
+ e164: "E.164 number",
1130
+ jwt: "JWT",
1131
+ template_literal: "input",
1132
+ };
1133
+ // type names: missing keys = do not translate (use raw value via ?? fallback)
1134
+ const TypeDictionary = {
1135
+ // Compatibility: "nan" -> "NaN" for display
1136
+ nan: "NaN",
1137
+ // All other type names omitted - they fall back to raw values via ?? operator
1138
+ };
1139
+ return (issue) => {
1140
+ switch (issue.code) {
1141
+ case "invalid_type": {
1142
+ const expected = TypeDictionary[issue.expected] ?? issue.expected;
1143
+ const receivedType = parsedType(issue.input);
1144
+ const received = TypeDictionary[receivedType] ?? receivedType;
1145
+ return `Invalid input: expected ${expected}, received ${received}`;
1146
+ }
1147
+ case "invalid_value":
1148
+ if (issue.values.length === 1)
1149
+ return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`;
1150
+ return `Invalid option: expected one of ${joinValues(issue.values, "|")}`;
1151
+ case "too_big": {
1152
+ const adj = issue.inclusive ? "<=" : "<";
1153
+ const sizing = getSizing(issue.origin);
1154
+ if (sizing)
1155
+ return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`;
1156
+ return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`;
1157
+ }
1158
+ case "too_small": {
1159
+ const adj = issue.inclusive ? ">=" : ">";
1160
+ const sizing = getSizing(issue.origin);
1161
+ if (sizing) {
1162
+ return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;
1163
+ }
1164
+ return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;
1165
+ }
1166
+ case "invalid_format": {
1167
+ const _issue = issue;
1168
+ if (_issue.format === "starts_with") {
1169
+ return `Invalid string: must start with "${_issue.prefix}"`;
1170
+ }
1171
+ if (_issue.format === "ends_with")
1172
+ return `Invalid string: must end with "${_issue.suffix}"`;
1173
+ if (_issue.format === "includes")
1174
+ return `Invalid string: must include "${_issue.includes}"`;
1175
+ if (_issue.format === "regex")
1176
+ return `Invalid string: must match pattern ${_issue.pattern}`;
1177
+ return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;
1178
+ }
1179
+ case "not_multiple_of":
1180
+ return `Invalid number: must be a multiple of ${issue.divisor}`;
1181
+ case "unrecognized_keys":
1182
+ return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`;
1183
+ case "invalid_key":
1184
+ return `Invalid key in ${issue.origin}`;
1185
+ case "invalid_union":
1186
+ if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) {
1187
+ const opts = issue.options.map((o) => `'${o}'`).join(" | ");
1188
+ return `Invalid discriminator value. Expected ${opts}`;
1189
+ }
1190
+ return "Invalid input";
1191
+ case "invalid_element":
1192
+ return `Invalid value in ${issue.origin}`;
1193
+ default:
1194
+ return `Invalid input`;
1195
+ }
1196
+ };
1197
+ };
1198
+ function en () {
1199
+ return {
1200
+ localeError: error(),
1201
+ };
1202
+ }
1203
+
1204
+ // @__NO_SIDE_EFFECTS__
1205
+ function _string(Class, params) {
1206
+ return new Class({
1207
+ type: "string",
1208
+ ...normalizeParams(params),
1209
+ });
1210
+ }
1211
+ // @__NO_SIDE_EFFECTS__
1212
+ function _number(Class, params) {
1213
+ return new Class({
1214
+ type: "number",
1215
+ checks: [],
1216
+ ...normalizeParams(params),
1217
+ });
1218
+ }
1219
+ // @__NO_SIDE_EFFECTS__
1220
+ function _boolean(Class, params) {
1221
+ return new Class({
1222
+ type: "boolean",
1223
+ ...normalizeParams(params),
1224
+ });
1225
+ }
1226
+ // @__NO_SIDE_EFFECTS__
1227
+ function _unknown(Class) {
1228
+ return new Class({
1229
+ type: "unknown",
1230
+ });
1231
+ }
1232
+
1233
+ const ZodMiniType = /*@__PURE__*/ $constructor("ZodMiniType", (inst, def) => {
1234
+ if (!inst._zod)
1235
+ throw new Error("Uninitialized schema in ZodMiniType.");
1236
+ $ZodType.init(inst, def);
1237
+ inst.def = def;
1238
+ inst.type = def.type;
1239
+ inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });
1240
+ inst.safeParse = (data, params) => safeParse(inst, data, params);
1241
+ inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
1242
+ inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
1243
+ inst.check = (...checks) => {
1244
+ return inst.clone({
1245
+ ...def,
1246
+ checks: [
1247
+ ...(def.checks ?? []),
1248
+ ...checks.map((ch) => typeof ch === "function"
1249
+ ? {
1250
+ _zod: { check: ch, def: { check: "custom" }, onattach: [] },
1251
+ }
1252
+ : ch),
1253
+ ],
1254
+ }, { parent: true });
1255
+ };
1256
+ inst.with = inst.check;
1257
+ inst.clone = (_def, params) => clone(inst, _def, params);
1258
+ inst.brand = () => inst;
1259
+ inst.register = ((reg, meta) => {
1260
+ reg.add(inst, meta);
1261
+ return inst;
1262
+ });
1263
+ inst.apply = (fn) => fn(inst);
1264
+ });
1265
+ const ZodMiniString = /*@__PURE__*/ $constructor("ZodMiniString", (inst, def) => {
1266
+ $ZodString.init(inst, def);
1267
+ ZodMiniType.init(inst, def);
1268
+ });
1269
+ // @__NO_SIDE_EFFECTS__
1270
+ function string(params) {
1271
+ return _string(ZodMiniString, params);
1272
+ }
1273
+ const ZodMiniNumber = /*@__PURE__*/ $constructor("ZodMiniNumber", (inst, def) => {
1274
+ $ZodNumber.init(inst, def);
1275
+ ZodMiniType.init(inst, def);
1276
+ });
1277
+ // @__NO_SIDE_EFFECTS__
1278
+ function number(params) {
1279
+ return _number(ZodMiniNumber, params);
1280
+ }
1281
+ const ZodMiniBoolean = /*@__PURE__*/ $constructor("ZodMiniBoolean", (inst, def) => {
1282
+ $ZodBoolean.init(inst, def);
1283
+ ZodMiniType.init(inst, def);
1284
+ });
1285
+ // @__NO_SIDE_EFFECTS__
1286
+ function boolean(params) {
1287
+ return _boolean(ZodMiniBoolean, params);
1288
+ }
1289
+ const ZodMiniUnknown = /*@__PURE__*/ $constructor("ZodMiniUnknown", (inst, def) => {
1290
+ $ZodUnknown.init(inst, def);
1291
+ ZodMiniType.init(inst, def);
1292
+ });
1293
+ // @__NO_SIDE_EFFECTS__
1294
+ function unknown() {
1295
+ return _unknown(ZodMiniUnknown);
1296
+ }
1297
+ const ZodMiniArray = /*@__PURE__*/ $constructor("ZodMiniArray", (inst, def) => {
1298
+ $ZodArray.init(inst, def);
1299
+ ZodMiniType.init(inst, def);
1300
+ });
1301
+ // @__NO_SIDE_EFFECTS__
1302
+ function array(element, params) {
1303
+ return new ZodMiniArray({
1304
+ type: "array",
1305
+ element: element,
1306
+ ...normalizeParams(params),
1307
+ });
1308
+ }
1309
+ const ZodMiniObject = /*@__PURE__*/ $constructor("ZodMiniObject", (inst, def) => {
1310
+ $ZodObject.init(inst, def);
1311
+ ZodMiniType.init(inst, def);
1312
+ defineLazy(inst, "shape", () => def.shape);
1313
+ });
1314
+ // @__NO_SIDE_EFFECTS__
1315
+ function object(shape, params) {
1316
+ const def = {
1317
+ type: "object",
1318
+ shape: shape ?? {},
1319
+ ...normalizeParams(params),
1320
+ };
1321
+ return new ZodMiniObject(def);
1322
+ }
1323
+ const ZodMiniDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodMiniDiscriminatedUnion", (inst, def) => {
1324
+ $ZodDiscriminatedUnion.init(inst, def);
1325
+ ZodMiniType.init(inst, def);
1326
+ });
1327
+ // @__NO_SIDE_EFFECTS__
1328
+ function discriminatedUnion(discriminator, options, params) {
1329
+ return new ZodMiniDiscriminatedUnion({
1330
+ type: "union",
1331
+ options,
1332
+ discriminator,
1333
+ ...normalizeParams(params),
1334
+ });
1335
+ }
1336
+ const ZodMiniRecord = /*@__PURE__*/ $constructor("ZodMiniRecord", (inst, def) => {
1337
+ $ZodRecord.init(inst, def);
1338
+ ZodMiniType.init(inst, def);
1339
+ });
1340
+ // @__NO_SIDE_EFFECTS__
1341
+ function record$1(keyType, valueType, params) {
1342
+ // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()
1343
+ if (!valueType || !valueType._zod) {
1344
+ return new ZodMiniRecord({
1345
+ type: "record",
1346
+ keyType: string(),
1347
+ valueType: keyType,
1348
+ ...normalizeParams(valueType),
1349
+ });
1350
+ }
1351
+ return new ZodMiniRecord({
1352
+ type: "record",
1353
+ keyType,
1354
+ valueType: valueType,
1355
+ ...normalizeParams(params),
1356
+ });
1357
+ }
1358
+ const ZodMiniEnum = /*@__PURE__*/ $constructor("ZodMiniEnum", (inst, def) => {
1359
+ $ZodEnum.init(inst, def);
1360
+ ZodMiniType.init(inst, def);
1361
+ inst.options = Object.values(def.entries);
1362
+ });
1363
+ // @__NO_SIDE_EFFECTS__
1364
+ function _enum(values, params) {
1365
+ const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
1366
+ return new ZodMiniEnum({
1367
+ type: "enum",
1368
+ entries,
1369
+ ...normalizeParams(params),
1370
+ });
1371
+ }
1372
+ const ZodMiniLiteral = /*@__PURE__*/ $constructor("ZodMiniLiteral", (inst, def) => {
1373
+ $ZodLiteral.init(inst, def);
1374
+ ZodMiniType.init(inst, def);
1375
+ });
1376
+ // @__NO_SIDE_EFFECTS__
1377
+ function literal(value, params) {
1378
+ return new ZodMiniLiteral({
1379
+ type: "literal",
1380
+ values: Array.isArray(value) ? value : [value],
1381
+ ...normalizeParams(params),
1382
+ });
1383
+ }
1384
+ const ZodMiniOptional = /*@__PURE__*/ $constructor("ZodMiniOptional", (inst, def) => {
1385
+ $ZodOptional.init(inst, def);
1386
+ ZodMiniType.init(inst, def);
1387
+ });
1388
+ // @__NO_SIDE_EFFECTS__
1389
+ function optional(innerType) {
1390
+ return new ZodMiniOptional({
1391
+ type: "optional",
1392
+ innerType: innerType,
1393
+ });
1394
+ }
1395
+
1396
+ // zod/mini ships with a minimal error map ("Invalid input"). The English
1397
+ // locale restores messages like "expected number, received string", which is
1398
+ // what a PROTOCOL_ERROR reason is for. Passed per parse call, never through
1399
+ // z.config: a library must not overwrite the host application's zod
1400
+ // configuration, and the host's must not change these reasons.
1401
+ const englishErrors = en().localeError;
1402
+ const eventEnvelopeSchema = object({
1403
+ source: literal(MESSAGE_SOURCE),
1404
+ version: literal(MESSAGE_VERSION),
1405
+ type: string(),
1406
+ instanceId: string(),
1407
+ // Deliberately unvalidated here. A malformed payload must fail at the
1408
+ // message schema, AFTER the instance is identified, so the failure comes
1409
+ // back as PROTOCOL_ERROR instead of being dropped as foreign traffic.
1410
+ payload: optional(unknown()),
1411
+ });
1412
+ /**
1413
+ * Reads a raw postMessage payload as a protocol envelope. Anything that is not
1414
+ * an envelope of this protocol version returns null: the `message` event is a
1415
+ * channel shared with the whole page, so foreign traffic is dropped, not
1416
+ * reported.
1417
+ */
1418
+ function parseEnvelope(data) {
1419
+ const parsed = eventEnvelopeSchema.safeParse(data);
1420
+ return parsed.success ? parsed.data : null;
1421
+ }
1422
+ /** Formats the first zod issue as a PROTOCOL_ERROR reason, rooted at the wire type. */
1423
+ function formatReason(path, error) {
1424
+ const issue = error.issues[0];
1425
+ if (!issue)
1426
+ return `${path}: invalid payload`;
1427
+ const at = issue.path.length > 0 ? `${path}.${issue.path.join('.')}` : path;
1428
+ return `${at}: ${issue.message}`;
1429
+ }
1430
+ /**
1431
+ * Every protocol payload is a plain record. zod's object types accept any
1432
+ * non-array object, so a `Date` or `Map` would pass a schema whose declared
1433
+ * properties are all optional. Structured clone can deliver those values, and
1434
+ * postMessage recreates plain objects in the receiving realm, so the
1435
+ * prototype check holds across the frame boundary.
1436
+ */
1437
+ function isPlainRecord(value) {
1438
+ if (!value || typeof value !== 'object')
1439
+ return false;
1440
+ const proto = Object.getPrototypeOf(value);
1441
+ return proto === Object.prototype || proto === null;
1442
+ }
1443
+ /**
1444
+ * Validates one payload against its wire schema and reports failures in the
1445
+ * `ParseResult` shape the SDK turns into PROTOCOL_ERROR messages.
1446
+ */
1447
+ function parsePayload(schema, value, path) {
1448
+ if (!isPlainRecord(value)) {
1449
+ return { ok: false, reason: `${path}: Invalid input: expected object` };
1450
+ }
1451
+ const result = safeParse(schema, value, { error: englishErrors });
1452
+ return result.success
1453
+ ? { ok: true, value: result.data }
1454
+ : { ok: false, reason: formatReason(path, result.error) };
1455
+ }
1456
+ /**
1457
+ * Validates one envelope against a schema map and returns the typed message.
1458
+ * Own-property lookup only: a wire type like "constructor" must resolve to
1459
+ * "unknown type", never to Object.prototype.
1460
+ */
1461
+ function parseMessage(envelope, events) {
1462
+ const schema = Object.prototype.hasOwnProperty.call(events, envelope.type)
1463
+ ? events[envelope.type]
1464
+ : undefined;
1465
+ if (!schema) {
1466
+ return { ok: false, reason: `Unknown message type: ${envelope.type}` };
1467
+ }
1468
+ // Only an ABSENT payload defaults to empty. An explicit null must reach the
1469
+ // plain-record gate and be rejected, not be read as an empty payload.
1470
+ const payload = parsePayload(schema, envelope.payload === undefined ? {} : envelope.payload, envelope.type);
1471
+ if (!payload.ok)
1472
+ return payload;
1473
+ // The key/payload correlation holds by construction; TypeScript cannot
1474
+ // carry it through the indexed lookup above.
1475
+ return {
1476
+ ok: true,
1477
+ value: { type: envelope.type, payload: payload.value },
1478
+ };
1479
+ }
1480
+
1481
+ /**
1482
+ * The wire messages every component shares, plus the appearance contract.
1483
+ * Component-specific schemas live in each component's own folder
1484
+ * (`src/<component>/schema.ts`), never here.
1485
+ *
1486
+ * Every schema is a strict `z.object`: unknown keys are stripped, so an
1487
+ * additive field deploys in any order — the older side ignores it. A real
1488
+ * breaking change bumps MESSAGE_VERSION and fails loud at the envelope.
1489
+ */
1490
+ const record = record$1(string(), unknown());
1491
+ const emptyPayload = object({});
1492
+ const componentErrorSchema = object({
1493
+ code: string(),
1494
+ message: string(),
1495
+ recoverable: boolean(),
1496
+ details: optional(record),
1497
+ });
1498
+ /**
1499
+ * Client-side appearance, shared by every component. The SDK sends it in
1500
+ * CONFIG_SET and payhub parses it with this same object, so the layout
1501
+ * vocabulary exists in exactly one place.
1502
+ */
1503
+ const appearanceSchema = object({
1504
+ /**
1505
+ * Structure: how the buyer moves between payment methods.
1506
+ * Independent of `layoutVariant`, which controls density.
1507
+ * Defaults to `tabs`. A single-method session renders the bare form.
1508
+ */
1509
+ layout: optional(_enum(['tabs', 'accordion', 'stacked', 'minimal'])),
1510
+ /** Density: how much room the component takes. */
1511
+ layoutVariant: optional(_enum(['compact', 'standard', 'wide'])),
1512
+ /**
1513
+ * Field appearance: where a field's label sits.
1514
+ * `above` puts the label over the input. The other two start it inside the
1515
+ * field, in the place a placeholder would sit, and lift it once the field
1516
+ * has focus or a value: `floating` to the top of the box, `outlined` onto
1517
+ * the border, cutting a notch in the line. Defaults to `above`.
1518
+ */
1519
+ labelStyle: optional(_enum(['above', 'floating', 'outlined'])),
1520
+ mode: optional(_enum(['light', 'dark', 'system'])),
1521
+ tokens: optional(record$1(string(), string())),
1522
+ labels: optional(record$1(string(), string())),
1523
+ });
1524
+ /**
1525
+ * Inbound wire messages: iframe → parent SDK. One schema per wire type, and
1526
+ * this map is the only definition. Payhub emits through these objects and the
1527
+ * SDK validates with the same objects, so agreement between the two sides is
1528
+ * shared, not tested.
1529
+ */
1530
+ const baseInboundEvents = {
1531
+ READY: object({
1532
+ fields: optional(array(string())),
1533
+ methods: optional(array(string())),
1534
+ }),
1535
+ RENDERED: emptyPayload,
1536
+ CONFIG_REQUEST: emptyPayload,
1537
+ PREFILL_REQUEST: emptyPayload,
1538
+ RESIZE: object({ height: number() }),
1539
+ STATE_CHANGE: object({
1540
+ isValid: boolean(),
1541
+ completeness: optional(number()),
1542
+ fields: optional(record$1(string(), object({
1543
+ valid: optional(boolean()),
1544
+ touched: optional(boolean()),
1545
+ }))),
1546
+ }),
1547
+ SUBMIT_RESULT: discriminatedUnion('success', [
1548
+ // `data` stays an open record: the transaction result grows fields the
1549
+ // SDK does not interpret, and it forwards all of them.
1550
+ object({ success: literal(true), data: optional(record) }),
1551
+ object({ success: literal(false), error: componentErrorSchema }),
1552
+ ]),
1553
+ ERROR: componentErrorSchema,
1554
+ LOADING: object({
1555
+ state: _enum(['bootstrapping', 'submitting', 'validating']),
1556
+ }),
1557
+ };
1558
+ /**
1559
+ * Outbound wire messages: parent SDK → iframe. `options` is a plain record
1560
+ * here because its shape is per-component: payhub validates it with the
1561
+ * `optionsSchema` on the component's descriptor.
1562
+ */
1563
+ const outboundMessages = {
1564
+ CONFIG_SET: object({
1565
+ sessionToken: string(),
1566
+ options: optional(record),
1567
+ appearance: optional(appearanceSchema),
1568
+ }),
1569
+ PREFILL_SET: object({ prefill: record$1(string(), string()) }),
1570
+ FOCUS_REQUEST: object({ field: optional(string()) }),
1571
+ BLUR_REQUEST: emptyPayload,
1572
+ SUBMIT_REQUEST: emptyPayload,
1573
+ SESSION_UPDATE: object({
1574
+ sessionToken: string(),
1575
+ replace: optional(boolean()),
1576
+ }),
1577
+ DESTROY: emptyPayload,
1578
+ PROTOCOL_ERROR: object({ originalType: string(), reason: string() }),
1579
+ };
1580
+
1581
+ const descriptors = new Map();
1582
+ const componentDescriptors = descriptors;
1583
+ /** Kept in registration order to preserve the former COMPONENT_TYPES value. */
1584
+ const componentTypes = [];
1585
+ function register(descriptor) {
1586
+ if (descriptors.has(descriptor.type)) {
1587
+ throw new Error(`Component type "${descriptor.type}" is already registered.`);
1588
+ }
1589
+ const frozen = Object.freeze(Object.assign(Object.assign({}, descriptor), { eventSchemas: Object.freeze(Object.assign({}, descriptor.eventSchemas)) }));
1590
+ descriptors.set(descriptor.type, frozen);
1591
+ componentTypes.push(descriptor.type);
1592
+ return frozen;
1593
+ }
1594
+ function getComponentDescriptor(type) {
1595
+ return descriptors.get(type);
1596
+ }
1597
+
1598
+ /**
1599
+ * PayIn's wire contract: its event schemas, options schema, and vocabulary.
1600
+ * PayIn-specific on purpose — a payout component defines its own methods in
1601
+ * its own folder.
1602
+ */
1603
+ const PAYMENT_METHODS = [
1604
+ 'card',
1605
+ 'ach',
1606
+ 'check',
1607
+ 'applepay',
1608
+ 'googlepay',
1609
+ ];
1610
+ /**
1611
+ * A card network. Not a payment method. Accepted brands are session config
1612
+ * (`Session/init` acceptedCardBrands), not a client option: the API owns them
1613
+ * and payhub reads them from bootstrap.
1614
+ */
1615
+ const CARD_BRANDS = [
1616
+ 'Visa',
1617
+ 'Mastercard',
1618
+ 'Amex',
1619
+ 'Discover',
1620
+ 'Jcb',
1621
+ 'Diners',
1622
+ ];
1623
+ /**
1624
+ * Client-side UI behavior only. Business configuration — operation, methods,
1625
+ * amount, required fields, billing address — belongs to `Session/init` on the
1626
+ * partner's server, and its types belong to the API's generated SDK.
1627
+ *
1628
+ * The SDK sends this in CONFIG_SET.options and payhub parses with this same
1629
+ * object (via the descriptor's `optionsSchema`).
1630
+ */
1631
+ const payinOptionsSchema = object({
1632
+ showSubmitButton: optional(boolean()),
1633
+ });
1634
+ /** PayIn's own inbound events, beyond the base set every component shares. */
1635
+ const payinEvents = {
1636
+ METHOD_CHANGE: object({ method: _enum(PAYMENT_METHODS) }),
1637
+ WALLET_AVAILABLE: object({
1638
+ applepay: boolean(),
1639
+ googlepay: boolean(),
1640
+ }),
1641
+ CARD_BRAND_CHANGE: object({
1642
+ /** A known brand, or 'unknown' while the number is too short to classify. */
1643
+ brand: _enum([...CARD_BRANDS, 'unknown']),
1644
+ }),
1645
+ VALIDATION_STATUS: object({
1646
+ status: _enum(['verified', 'pending', 'failed', 'warning']),
1647
+ message: optional(string()),
1648
+ }),
1649
+ VENDOR_CREATED: object({ vendorId: string() }),
1650
+ };
1651
+
1652
+ /**
1653
+ * Wire type → emitter event, with the shared schema from `./schema.js` as the
1654
+ * only validator.
1655
+ */
1656
+ const payInEventSchemas = {
1657
+ METHOD_CHANGE: { event: 'methodChange', schema: payinEvents.METHOD_CHANGE },
1658
+ WALLET_AVAILABLE: {
1659
+ event: 'walletAvailable',
1660
+ schema: payinEvents.WALLET_AVAILABLE,
1661
+ },
1662
+ CARD_BRAND_CHANGE: {
1663
+ event: 'cardBrandChange',
1664
+ schema: payinEvents.CARD_BRAND_CHANGE,
1665
+ },
1666
+ VALIDATION_STATUS: {
1667
+ event: 'validationStatus',
1668
+ schema: payinEvents.VALIDATION_STATUS,
1669
+ },
1670
+ VENDOR_CREATED: {
1671
+ event: 'vendorCreated',
1672
+ schema: payinEvents.VENDOR_CREATED,
1673
+ },
1674
+ };
1675
+ const payInDescriptor = register({
1676
+ type: 'payin',
1677
+ displayName: 'PayIn',
1678
+ embedPath: '/embed/payin',
1679
+ optionsSchema: payinOptionsSchema,
1680
+ eventSchemas: payInEventSchemas,
1681
+ });
1682
+
1683
+ const ErrorCodes = {
1684
+ LOAD_TIMEOUT: 'LOAD_TIMEOUT',
1685
+ PROTOCOL_ERROR: 'PROTOCOL_ERROR',
1686
+ INVALID_STATE: 'INVALID_STATE',
1687
+ SESSION_EXPIRED: 'SESSION_EXPIRED',
1688
+ SESSION_REFRESH_FAILED: 'SESSION_REFRESH_FAILED',
1689
+ /** Reported by an iframe whose call was rejected for an expired JWT. Triggers a refresh. */
1690
+ TOKEN_EXPIRED: 'TOKEN_EXPIRED',
1691
+ /**
1692
+ * Reported by an iframe whose render token no longer renders. The SDK recreates the frame
1693
+ * with the latest render token.
1694
+ */
1695
+ RENDER_TOKEN_EXPIRED: 'RENDER_TOKEN_EXPIRED',
1696
+ /** The render token failed signature, audience, or format checks. Needs a new session. */
1697
+ RENDER_TOKEN_INVALID: 'RENDER_TOKEN_INVALID',
1698
+ /** Refresh rejected: the page origin is not on the session's allowlist. Terminal. */
1699
+ ORIGIN_NOT_ALLOWED: 'ORIGIN_NOT_ALLOWED',
1700
+ /** Refresh rejected: the session was revoked (token reuse included). Terminal. */
1701
+ SESSION_REVOKED: 'SESSION_REVOKED',
1702
+ /** Refresh rejected: the session reached its expiration ceiling. Terminal. */
1703
+ SESSION_LIMIT_REACHED: 'SESSION_LIMIT_REACHED',
1704
+ /** Refresh rejected: unknown session, or one that names a component this API build lacks. Terminal. */
1705
+ SESSION_INVALID: 'SESSION_INVALID',
1706
+ /** Refresh could not mint a render token: server misconfiguration. Terminal regardless of status. */
1707
+ RENDER_TOKEN_FAILED: 'RENDER_TOKEN_FAILED',
1708
+ };
1709
+
1710
+ const BASE_COMPONENT_EVENT_NAMES = [
1711
+ 'ready',
1712
+ 'rendered',
1713
+ 'message',
1714
+ 'success',
1715
+ 'change',
1716
+ 'error',
1717
+ 'loading',
1718
+ 'resize',
1719
+ ];
1720
+
1721
+ export { BASE_COMPONENT_EVENT_NAMES, CARD_BRANDS, ErrorCodes, MESSAGE_SOURCE, MESSAGE_VERSION, PAYMENT_METHODS, appearanceSchema, baseInboundEvents, componentDescriptors, componentErrorSchema, componentTypes, eventEnvelopeSchema, getComponentDescriptor, outboundMessages, parseEnvelope, parseMessage, parsePayload, payInDescriptor, payInEventSchemas, payinEvents, payinOptionsSchema, register };