@likec4/config 1.40.0 → 1.42.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.
@@ -1,3251 +0,0 @@
1
- import JSON5 from 'json5';
2
-
3
- /** A special constant with type `never` */
4
- function $constructor(name, initializer, params) {
5
- function init(inst, def) {
6
- var _a;
7
- Object.defineProperty(inst, "_zod", {
8
- value: inst._zod ?? {},
9
- enumerable: false,
10
- });
11
- (_a = inst._zod).traits ?? (_a.traits = new Set());
12
- inst._zod.traits.add(name);
13
- initializer(inst, def);
14
- // support prototype modifications
15
- for (const k in _.prototype) {
16
- if (!(k in inst))
17
- Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });
18
- }
19
- inst._zod.constr = _;
20
- inst._zod.def = def;
21
- }
22
- // doesn't work if Parent has a constructor with arguments
23
- const Parent = params?.Parent ?? Object;
24
- class Definition extends Parent {
25
- }
26
- Object.defineProperty(Definition, "name", { value: name });
27
- function _(def) {
28
- var _a;
29
- const inst = params?.Parent ? new Definition() : this;
30
- init(inst, def);
31
- (_a = inst._zod).deferred ?? (_a.deferred = []);
32
- for (const fn of inst._zod.deferred) {
33
- fn();
34
- }
35
- return inst;
36
- }
37
- Object.defineProperty(_, "init", { value: init });
38
- Object.defineProperty(_, Symbol.hasInstance, {
39
- value: (inst) => {
40
- if (params?.Parent && inst instanceof params.Parent)
41
- return true;
42
- return inst?._zod?.traits?.has(name);
43
- },
44
- });
45
- Object.defineProperty(_, "name", { value: name });
46
- return _;
47
- }
48
- class $ZodAsyncError extends Error {
49
- constructor() {
50
- super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
51
- }
52
- }
53
- const globalConfig = {};
54
- function config(newConfig) {
55
- return globalConfig;
56
- }
57
-
58
- // functions
59
- function getEnumValues(entries) {
60
- const numericValues = Object.values(entries).filter((v) => typeof v === "number");
61
- const values = Object.entries(entries)
62
- .filter(([k, _]) => numericValues.indexOf(+k) === -1)
63
- .map(([_, v]) => v);
64
- return values;
65
- }
66
- function jsonStringifyReplacer(_, value) {
67
- if (typeof value === "bigint")
68
- return value.toString();
69
- return value;
70
- }
71
- function cached(getter) {
72
- return {
73
- get value() {
74
- {
75
- const value = getter();
76
- Object.defineProperty(this, "value", { value });
77
- return value;
78
- }
79
- },
80
- };
81
- }
82
- function nullish(input) {
83
- return input === null || input === undefined;
84
- }
85
- function cleanRegex(source) {
86
- const start = source.startsWith("^") ? 1 : 0;
87
- const end = source.endsWith("$") ? source.length - 1 : source.length;
88
- return source.slice(start, end);
89
- }
90
- const EVALUATING = Symbol("evaluating");
91
- function defineLazy(object, key, getter) {
92
- let value = undefined;
93
- Object.defineProperty(object, key, {
94
- get() {
95
- if (value === EVALUATING) {
96
- // Circular reference detected, return undefined to break the cycle
97
- return undefined;
98
- }
99
- if (value === undefined) {
100
- value = EVALUATING;
101
- value = getter();
102
- }
103
- return value;
104
- },
105
- set(v) {
106
- Object.defineProperty(object, key, {
107
- value: v,
108
- // configurable: true,
109
- });
110
- // object[key] = v;
111
- },
112
- configurable: true,
113
- });
114
- }
115
- function objectClone(obj) {
116
- return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
117
- }
118
- function assignProp(target, prop, value) {
119
- Object.defineProperty(target, prop, {
120
- value,
121
- writable: true,
122
- enumerable: true,
123
- configurable: true,
124
- });
125
- }
126
- function mergeDefs(...defs) {
127
- const mergedDescriptors = {};
128
- for (const def of defs) {
129
- const descriptors = Object.getOwnPropertyDescriptors(def);
130
- Object.assign(mergedDescriptors, descriptors);
131
- }
132
- return Object.defineProperties({}, mergedDescriptors);
133
- }
134
- function esc(str) {
135
- return JSON.stringify(str);
136
- }
137
- const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { });
138
- function isObject(data) {
139
- return typeof data === "object" && data !== null && !Array.isArray(data);
140
- }
141
- const allowsEval = cached(() => {
142
- // @ts-ignore
143
- if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
144
- return false;
145
- }
146
- try {
147
- const F = Function;
148
- new F("");
149
- return true;
150
- }
151
- catch (_) {
152
- return false;
153
- }
154
- });
155
- function isPlainObject(o) {
156
- if (isObject(o) === false)
157
- return false;
158
- // modified constructor
159
- const ctor = o.constructor;
160
- if (ctor === undefined)
161
- return true;
162
- // modified prototype
163
- const prot = ctor.prototype;
164
- if (isObject(prot) === false)
165
- return false;
166
- // ctor doesn't have static `isPrototypeOf`
167
- if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
168
- return false;
169
- }
170
- return true;
171
- }
172
- function shallowClone(o) {
173
- if (isPlainObject(o))
174
- return { ...o };
175
- return o;
176
- }
177
- const propertyKeyTypes = new Set(["string", "number", "symbol"]);
178
- function escapeRegex(str) {
179
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
180
- }
181
- // zod-specific utils
182
- function clone(inst, def, params) {
183
- const cl = new inst._zod.constr(def ?? inst._zod.def);
184
- if (!def || params?.parent)
185
- cl._zod.parent = inst;
186
- return cl;
187
- }
188
- function normalizeParams(_params) {
189
- const params = _params;
190
- if (!params)
191
- return {};
192
- if (typeof params === "string")
193
- return { error: () => params };
194
- if (params?.message !== undefined) {
195
- if (params?.error !== undefined)
196
- throw new Error("Cannot specify both `message` and `error` params");
197
- params.error = params.message;
198
- }
199
- delete params.message;
200
- if (typeof params.error === "string")
201
- return { ...params, error: () => params.error };
202
- return params;
203
- }
204
- function optionalKeys(shape) {
205
- return Object.keys(shape).filter((k) => {
206
- return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
207
- });
208
- }
209
- function pick(schema, mask) {
210
- const currDef = schema._zod.def;
211
- const def = mergeDefs(schema._zod.def, {
212
- get shape() {
213
- const newShape = {};
214
- for (const key in mask) {
215
- if (!(key in currDef.shape)) {
216
- throw new Error(`Unrecognized key: "${key}"`);
217
- }
218
- if (!mask[key])
219
- continue;
220
- newShape[key] = currDef.shape[key];
221
- }
222
- assignProp(this, "shape", newShape); // self-caching
223
- return newShape;
224
- },
225
- checks: [],
226
- });
227
- return clone(schema, def);
228
- }
229
- function omit(schema, mask) {
230
- const currDef = schema._zod.def;
231
- const def = mergeDefs(schema._zod.def, {
232
- get shape() {
233
- const newShape = { ...schema._zod.def.shape };
234
- for (const key in mask) {
235
- if (!(key in currDef.shape)) {
236
- throw new Error(`Unrecognized key: "${key}"`);
237
- }
238
- if (!mask[key])
239
- continue;
240
- delete newShape[key];
241
- }
242
- assignProp(this, "shape", newShape); // self-caching
243
- return newShape;
244
- },
245
- checks: [],
246
- });
247
- return clone(schema, def);
248
- }
249
- function extend(schema, shape) {
250
- if (!isPlainObject(shape)) {
251
- throw new Error("Invalid input to extend: expected a plain object");
252
- }
253
- const def = mergeDefs(schema._zod.def, {
254
- get shape() {
255
- const _shape = { ...schema._zod.def.shape, ...shape };
256
- assignProp(this, "shape", _shape); // self-caching
257
- return _shape;
258
- },
259
- checks: [],
260
- });
261
- return clone(schema, def);
262
- }
263
- function merge(a, b) {
264
- const def = mergeDefs(a._zod.def, {
265
- get shape() {
266
- const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
267
- assignProp(this, "shape", _shape); // self-caching
268
- return _shape;
269
- },
270
- get catchall() {
271
- return b._zod.def.catchall;
272
- },
273
- checks: [], // delete existing checks
274
- });
275
- return clone(a, def);
276
- }
277
- function partial(Class, schema, mask) {
278
- const def = mergeDefs(schema._zod.def, {
279
- get shape() {
280
- const oldShape = schema._zod.def.shape;
281
- const shape = { ...oldShape };
282
- if (mask) {
283
- for (const key in mask) {
284
- if (!(key in oldShape)) {
285
- throw new Error(`Unrecognized key: "${key}"`);
286
- }
287
- if (!mask[key])
288
- continue;
289
- // if (oldShape[key]!._zod.optin === "optional") continue;
290
- shape[key] = Class
291
- ? new Class({
292
- type: "optional",
293
- innerType: oldShape[key],
294
- })
295
- : oldShape[key];
296
- }
297
- }
298
- else {
299
- for (const key in oldShape) {
300
- // if (oldShape[key]!._zod.optin === "optional") continue;
301
- shape[key] = Class
302
- ? new Class({
303
- type: "optional",
304
- innerType: oldShape[key],
305
- })
306
- : oldShape[key];
307
- }
308
- }
309
- assignProp(this, "shape", shape); // self-caching
310
- return shape;
311
- },
312
- checks: [],
313
- });
314
- return clone(schema, def);
315
- }
316
- function required(Class, schema, mask) {
317
- const def = mergeDefs(schema._zod.def, {
318
- get shape() {
319
- const oldShape = schema._zod.def.shape;
320
- const shape = { ...oldShape };
321
- if (mask) {
322
- for (const key in mask) {
323
- if (!(key in shape)) {
324
- throw new Error(`Unrecognized key: "${key}"`);
325
- }
326
- if (!mask[key])
327
- continue;
328
- // overwrite with non-optional
329
- shape[key] = new Class({
330
- type: "nonoptional",
331
- innerType: oldShape[key],
332
- });
333
- }
334
- }
335
- else {
336
- for (const key in oldShape) {
337
- // overwrite with non-optional
338
- shape[key] = new Class({
339
- type: "nonoptional",
340
- innerType: oldShape[key],
341
- });
342
- }
343
- }
344
- assignProp(this, "shape", shape); // self-caching
345
- return shape;
346
- },
347
- checks: [],
348
- });
349
- return clone(schema, def);
350
- }
351
- // invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom
352
- function aborted(x, startIndex = 0) {
353
- for (let i = startIndex; i < x.issues.length; i++) {
354
- if (x.issues[i]?.continue !== true) {
355
- return true;
356
- }
357
- }
358
- return false;
359
- }
360
- function prefixIssues(path, issues) {
361
- return issues.map((iss) => {
362
- var _a;
363
- (_a = iss).path ?? (_a.path = []);
364
- iss.path.unshift(path);
365
- return iss;
366
- });
367
- }
368
- function unwrapMessage(message) {
369
- return typeof message === "string" ? message : message?.message;
370
- }
371
- function finalizeIssue(iss, ctx, config) {
372
- const full = { ...iss, path: iss.path ?? [] };
373
- // for backwards compatibility
374
- if (!iss.message) {
375
- const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??
376
- unwrapMessage(ctx?.error?.(iss)) ??
377
- unwrapMessage(config.customError?.(iss)) ??
378
- unwrapMessage(config.localeError?.(iss)) ??
379
- "Invalid input";
380
- full.message = message;
381
- }
382
- // delete (full as any).def;
383
- delete full.inst;
384
- delete full.continue;
385
- if (!ctx?.reportInput) {
386
- delete full.input;
387
- }
388
- return full;
389
- }
390
- function getLengthableOrigin(input) {
391
- if (Array.isArray(input))
392
- return "array";
393
- if (typeof input === "string")
394
- return "string";
395
- return "unknown";
396
- }
397
- function issue(...args) {
398
- const [iss, input, inst] = args;
399
- if (typeof iss === "string") {
400
- return {
401
- message: iss,
402
- code: "custom",
403
- input,
404
- inst,
405
- };
406
- }
407
- return { ...iss };
408
- }
409
-
410
- const initializer$1 = (inst, def) => {
411
- inst.name = "$ZodError";
412
- Object.defineProperty(inst, "_zod", {
413
- value: inst._zod,
414
- enumerable: false,
415
- });
416
- Object.defineProperty(inst, "issues", {
417
- value: def,
418
- enumerable: false,
419
- });
420
- inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
421
- Object.defineProperty(inst, "toString", {
422
- value: () => inst.message,
423
- enumerable: false,
424
- });
425
- };
426
- const $ZodError = $constructor("$ZodError", initializer$1);
427
- const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error });
428
- function flattenError(error, mapper = (issue) => issue.message) {
429
- const fieldErrors = {};
430
- const formErrors = [];
431
- for (const sub of error.issues) {
432
- if (sub.path.length > 0) {
433
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
434
- fieldErrors[sub.path[0]].push(mapper(sub));
435
- }
436
- else {
437
- formErrors.push(mapper(sub));
438
- }
439
- }
440
- return { formErrors, fieldErrors };
441
- }
442
- function formatError(error, _mapper) {
443
- const mapper = _mapper ||
444
- function (issue) {
445
- return issue.message;
446
- };
447
- const fieldErrors = { _errors: [] };
448
- const processError = (error) => {
449
- for (const issue of error.issues) {
450
- if (issue.code === "invalid_union" && issue.errors.length) {
451
- issue.errors.map((issues) => processError({ issues }));
452
- }
453
- else if (issue.code === "invalid_key") {
454
- processError({ issues: issue.issues });
455
- }
456
- else if (issue.code === "invalid_element") {
457
- processError({ issues: issue.issues });
458
- }
459
- else if (issue.path.length === 0) {
460
- fieldErrors._errors.push(mapper(issue));
461
- }
462
- else {
463
- let curr = fieldErrors;
464
- let i = 0;
465
- while (i < issue.path.length) {
466
- const el = issue.path[i];
467
- const terminal = i === issue.path.length - 1;
468
- if (!terminal) {
469
- curr[el] = curr[el] || { _errors: [] };
470
- }
471
- else {
472
- curr[el] = curr[el] || { _errors: [] };
473
- curr[el]._errors.push(mapper(issue));
474
- }
475
- curr = curr[el];
476
- i++;
477
- }
478
- }
479
- }
480
- };
481
- processError(error);
482
- return fieldErrors;
483
- }
484
- /** Format a ZodError as a human-readable string in the following form.
485
- *
486
- * From
487
- *
488
- * ```ts
489
- * ZodError {
490
- * issues: [
491
- * {
492
- * expected: 'string',
493
- * code: 'invalid_type',
494
- * path: [ 'username' ],
495
- * message: 'Invalid input: expected string'
496
- * },
497
- * {
498
- * expected: 'number',
499
- * code: 'invalid_type',
500
- * path: [ 'favoriteNumbers', 1 ],
501
- * message: 'Invalid input: expected number'
502
- * }
503
- * ];
504
- * }
505
- * ```
506
- *
507
- * to
508
- *
509
- * ```
510
- * username
511
- * ✖ Expected number, received string at "username
512
- * favoriteNumbers[0]
513
- * ✖ Invalid input: expected number
514
- * ```
515
- */
516
- function toDotPath(_path) {
517
- const segs = [];
518
- const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg));
519
- for (const seg of path) {
520
- if (typeof seg === "number")
521
- segs.push(`[${seg}]`);
522
- else if (typeof seg === "symbol")
523
- segs.push(`[${JSON.stringify(String(seg))}]`);
524
- else if (/[^\w$]/.test(seg))
525
- segs.push(`[${JSON.stringify(seg)}]`);
526
- else {
527
- if (segs.length)
528
- segs.push(".");
529
- segs.push(seg);
530
- }
531
- }
532
- return segs.join("");
533
- }
534
- function prettifyError(error) {
535
- const lines = [];
536
- // sort by path length
537
- const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);
538
- // Process each issue
539
- for (const issue of issues) {
540
- lines.push(`✖ ${issue.message}`);
541
- if (issue.path?.length)
542
- lines.push(` → at ${toDotPath(issue.path)}`);
543
- }
544
- // Convert Map to formatted string
545
- return lines.join("\n");
546
- }
547
-
548
- const _parse = (_Err) => (schema, value, _ctx, _params) => {
549
- const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
550
- const result = schema._zod.run({ value, issues: [] }, ctx);
551
- if (result instanceof Promise) {
552
- throw new $ZodAsyncError();
553
- }
554
- if (result.issues.length) {
555
- const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
556
- captureStackTrace(e, _params?.callee);
557
- throw e;
558
- }
559
- return result.value;
560
- };
561
- const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
562
- const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
563
- let result = schema._zod.run({ value, issues: [] }, ctx);
564
- if (result instanceof Promise)
565
- result = await result;
566
- if (result.issues.length) {
567
- const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
568
- captureStackTrace(e, params?.callee);
569
- throw e;
570
- }
571
- return result.value;
572
- };
573
- const _safeParse = (_Err) => (schema, value, _ctx) => {
574
- const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
575
- const result = schema._zod.run({ value, issues: [] }, ctx);
576
- if (result instanceof Promise) {
577
- throw new $ZodAsyncError();
578
- }
579
- return result.issues.length
580
- ? {
581
- success: false,
582
- error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))),
583
- }
584
- : { success: true, data: result.value };
585
- };
586
- const safeParse$1 = /* @__PURE__*/ _safeParse($ZodRealError);
587
- const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
588
- const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
589
- let result = schema._zod.run({ value, issues: [] }, ctx);
590
- if (result instanceof Promise)
591
- result = await result;
592
- return result.issues.length
593
- ? {
594
- success: false,
595
- error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))),
596
- }
597
- : { success: true, data: result.value };
598
- };
599
- const safeParseAsync$1 = /* @__PURE__*/ _safeParseAsync($ZodRealError);
600
-
601
- const cuid = /^[cC][^\s-]{8,}$/;
602
- const cuid2 = /^[0-9a-z]+$/;
603
- const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
604
- const xid = /^[0-9a-vA-V]{20}$/;
605
- const ksuid = /^[A-Za-z0-9]{27}$/;
606
- const nanoid = /^[a-zA-Z0-9_-]{21}$/;
607
- /** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
608
- const duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
609
- /** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
610
- const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
611
- /** Returns a regex for validating an RFC 9562/4122 UUID.
612
- *
613
- * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
614
- const uuid = (version) => {
615
- if (!version)
616
- return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;
617
- return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
618
- };
619
- /** Practical email validation */
620
- const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
621
- // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
622
- const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
623
- function emoji() {
624
- return new RegExp(_emoji$1, "u");
625
- }
626
- const ipv4 = /^(?:(?: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])$/;
627
- const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/;
628
- const cidrv4 = /^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/;
629
- const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
630
- // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
631
- const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
632
- const base64url = /^[A-Za-z0-9_-]*$/;
633
- // based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address
634
- // export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
635
- const hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;
636
- // https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)
637
- const e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
638
- // const dateSource = `((\\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])))`;
639
- const dateSource = `(?:(?:\\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])))`;
640
- const date$1 = /*@__PURE__*/ new RegExp(`^${dateSource}$`);
641
- function timeSource(args) {
642
- const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
643
- const regex = typeof args.precision === "number"
644
- ? args.precision === -1
645
- ? `${hhmm}`
646
- : args.precision === 0
647
- ? `${hhmm}:[0-5]\\d`
648
- : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`
649
- : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
650
- return regex;
651
- }
652
- function time$1(args) {
653
- return new RegExp(`^${timeSource(args)}$`);
654
- }
655
- // Adapted from https://stackoverflow.com/a/3143231
656
- function datetime$1(args) {
657
- const time = timeSource({ precision: args.precision });
658
- const opts = ["Z"];
659
- if (args.local)
660
- opts.push("");
661
- // if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`);
662
- if (args.offset)
663
- opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
664
- const timeRegex = `${time}(?:${opts.join("|")})`;
665
- return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
666
- }
667
- const string$1 = (params) => {
668
- const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
669
- return new RegExp(`^${regex}$`);
670
- };
671
- // regex for string with no uppercase letters
672
- const lowercase = /^[^A-Z]*$/;
673
- // regex for string with no lowercase letters
674
- const uppercase = /^[^a-z]*$/;
675
-
676
- // import { $ZodType } from "./schemas.js";
677
- const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => {
678
- var _a;
679
- inst._zod ?? (inst._zod = {});
680
- inst._zod.def = def;
681
- (_a = inst._zod).onattach ?? (_a.onattach = []);
682
- });
683
- const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => {
684
- var _a;
685
- $ZodCheck.init(inst, def);
686
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
687
- const val = payload.value;
688
- return !nullish(val) && val.length !== undefined;
689
- });
690
- inst._zod.onattach.push((inst) => {
691
- const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);
692
- if (def.maximum < curr)
693
- inst._zod.bag.maximum = def.maximum;
694
- });
695
- inst._zod.check = (payload) => {
696
- const input = payload.value;
697
- const length = input.length;
698
- if (length <= def.maximum)
699
- return;
700
- const origin = getLengthableOrigin(input);
701
- payload.issues.push({
702
- origin,
703
- code: "too_big",
704
- maximum: def.maximum,
705
- inclusive: true,
706
- input,
707
- inst,
708
- continue: !def.abort,
709
- });
710
- };
711
- });
712
- const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => {
713
- var _a;
714
- $ZodCheck.init(inst, def);
715
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
716
- const val = payload.value;
717
- return !nullish(val) && val.length !== undefined;
718
- });
719
- inst._zod.onattach.push((inst) => {
720
- const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);
721
- if (def.minimum > curr)
722
- inst._zod.bag.minimum = def.minimum;
723
- });
724
- inst._zod.check = (payload) => {
725
- const input = payload.value;
726
- const length = input.length;
727
- if (length >= def.minimum)
728
- return;
729
- const origin = getLengthableOrigin(input);
730
- payload.issues.push({
731
- origin,
732
- code: "too_small",
733
- minimum: def.minimum,
734
- inclusive: true,
735
- input,
736
- inst,
737
- continue: !def.abort,
738
- });
739
- };
740
- });
741
- const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => {
742
- var _a;
743
- $ZodCheck.init(inst, def);
744
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
745
- const val = payload.value;
746
- return !nullish(val) && val.length !== undefined;
747
- });
748
- inst._zod.onattach.push((inst) => {
749
- const bag = inst._zod.bag;
750
- bag.minimum = def.length;
751
- bag.maximum = def.length;
752
- bag.length = def.length;
753
- });
754
- inst._zod.check = (payload) => {
755
- const input = payload.value;
756
- const length = input.length;
757
- if (length === def.length)
758
- return;
759
- const origin = getLengthableOrigin(input);
760
- const tooBig = length > def.length;
761
- payload.issues.push({
762
- origin,
763
- ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }),
764
- inclusive: true,
765
- exact: true,
766
- input: payload.value,
767
- inst,
768
- continue: !def.abort,
769
- });
770
- };
771
- });
772
- const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => {
773
- var _a, _b;
774
- $ZodCheck.init(inst, def);
775
- inst._zod.onattach.push((inst) => {
776
- const bag = inst._zod.bag;
777
- bag.format = def.format;
778
- if (def.pattern) {
779
- bag.patterns ?? (bag.patterns = new Set());
780
- bag.patterns.add(def.pattern);
781
- }
782
- });
783
- if (def.pattern)
784
- (_a = inst._zod).check ?? (_a.check = (payload) => {
785
- def.pattern.lastIndex = 0;
786
- if (def.pattern.test(payload.value))
787
- return;
788
- payload.issues.push({
789
- origin: "string",
790
- code: "invalid_format",
791
- format: def.format,
792
- input: payload.value,
793
- ...(def.pattern ? { pattern: def.pattern.toString() } : {}),
794
- inst,
795
- continue: !def.abort,
796
- });
797
- });
798
- else
799
- (_b = inst._zod).check ?? (_b.check = () => { });
800
- });
801
- const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => {
802
- $ZodCheckStringFormat.init(inst, def);
803
- inst._zod.check = (payload) => {
804
- def.pattern.lastIndex = 0;
805
- if (def.pattern.test(payload.value))
806
- return;
807
- payload.issues.push({
808
- origin: "string",
809
- code: "invalid_format",
810
- format: "regex",
811
- input: payload.value,
812
- pattern: def.pattern.toString(),
813
- inst,
814
- continue: !def.abort,
815
- });
816
- };
817
- });
818
- const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => {
819
- def.pattern ?? (def.pattern = lowercase);
820
- $ZodCheckStringFormat.init(inst, def);
821
- });
822
- const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => {
823
- def.pattern ?? (def.pattern = uppercase);
824
- $ZodCheckStringFormat.init(inst, def);
825
- });
826
- const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => {
827
- $ZodCheck.init(inst, def);
828
- const escapedRegex = escapeRegex(def.includes);
829
- const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
830
- def.pattern = pattern;
831
- inst._zod.onattach.push((inst) => {
832
- const bag = inst._zod.bag;
833
- bag.patterns ?? (bag.patterns = new Set());
834
- bag.patterns.add(pattern);
835
- });
836
- inst._zod.check = (payload) => {
837
- if (payload.value.includes(def.includes, def.position))
838
- return;
839
- payload.issues.push({
840
- origin: "string",
841
- code: "invalid_format",
842
- format: "includes",
843
- includes: def.includes,
844
- input: payload.value,
845
- inst,
846
- continue: !def.abort,
847
- });
848
- };
849
- });
850
- const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => {
851
- $ZodCheck.init(inst, def);
852
- const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
853
- def.pattern ?? (def.pattern = pattern);
854
- inst._zod.onattach.push((inst) => {
855
- const bag = inst._zod.bag;
856
- bag.patterns ?? (bag.patterns = new Set());
857
- bag.patterns.add(pattern);
858
- });
859
- inst._zod.check = (payload) => {
860
- if (payload.value.startsWith(def.prefix))
861
- return;
862
- payload.issues.push({
863
- origin: "string",
864
- code: "invalid_format",
865
- format: "starts_with",
866
- prefix: def.prefix,
867
- input: payload.value,
868
- inst,
869
- continue: !def.abort,
870
- });
871
- };
872
- });
873
- const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => {
874
- $ZodCheck.init(inst, def);
875
- const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
876
- def.pattern ?? (def.pattern = pattern);
877
- inst._zod.onattach.push((inst) => {
878
- const bag = inst._zod.bag;
879
- bag.patterns ?? (bag.patterns = new Set());
880
- bag.patterns.add(pattern);
881
- });
882
- inst._zod.check = (payload) => {
883
- if (payload.value.endsWith(def.suffix))
884
- return;
885
- payload.issues.push({
886
- origin: "string",
887
- code: "invalid_format",
888
- format: "ends_with",
889
- suffix: def.suffix,
890
- input: payload.value,
891
- inst,
892
- continue: !def.abort,
893
- });
894
- };
895
- });
896
- const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => {
897
- $ZodCheck.init(inst, def);
898
- inst._zod.check = (payload) => {
899
- payload.value = def.tx(payload.value);
900
- };
901
- });
902
-
903
- class Doc {
904
- constructor(args = []) {
905
- this.content = [];
906
- this.indent = 0;
907
- if (this)
908
- this.args = args;
909
- }
910
- indented(fn) {
911
- this.indent += 1;
912
- fn(this);
913
- this.indent -= 1;
914
- }
915
- write(arg) {
916
- if (typeof arg === "function") {
917
- arg(this, { execution: "sync" });
918
- arg(this, { execution: "async" });
919
- return;
920
- }
921
- const content = arg;
922
- const lines = content.split("\n").filter((x) => x);
923
- const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
924
- const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
925
- for (const line of dedented) {
926
- this.content.push(line);
927
- }
928
- }
929
- compile() {
930
- const F = Function;
931
- const args = this?.args;
932
- const content = this?.content ?? [``];
933
- const lines = [...content.map((x) => ` ${x}`)];
934
- // console.log(lines.join("\n"));
935
- return new F(...args, lines.join("\n"));
936
- }
937
- }
938
-
939
- const version = {
940
- major: 4,
941
- minor: 0,
942
- patch: 17,
943
- };
944
-
945
- const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
946
- var _a;
947
- inst ?? (inst = {});
948
- inst._zod.def = def; // set _def property
949
- inst._zod.bag = inst._zod.bag || {}; // initialize _bag object
950
- inst._zod.version = version;
951
- const checks = [...(inst._zod.def.checks ?? [])];
952
- // if inst is itself a checks.$ZodCheck, run it as a check
953
- if (inst._zod.traits.has("$ZodCheck")) {
954
- checks.unshift(inst);
955
- }
956
- //
957
- for (const ch of checks) {
958
- for (const fn of ch._zod.onattach) {
959
- fn(inst);
960
- }
961
- }
962
- if (checks.length === 0) {
963
- // deferred initializer
964
- // inst._zod.parse is not yet defined
965
- (_a = inst._zod).deferred ?? (_a.deferred = []);
966
- inst._zod.deferred?.push(() => {
967
- inst._zod.run = inst._zod.parse;
968
- });
969
- }
970
- else {
971
- const runChecks = (payload, checks, ctx) => {
972
- let isAborted = aborted(payload);
973
- let asyncResult;
974
- for (const ch of checks) {
975
- if (ch._zod.def.when) {
976
- const shouldRun = ch._zod.def.when(payload);
977
- if (!shouldRun)
978
- continue;
979
- }
980
- else if (isAborted) {
981
- continue;
982
- }
983
- const currLen = payload.issues.length;
984
- const _ = ch._zod.check(payload);
985
- if (_ instanceof Promise && ctx?.async === false) {
986
- throw new $ZodAsyncError();
987
- }
988
- if (asyncResult || _ instanceof Promise) {
989
- asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
990
- await _;
991
- const nextLen = payload.issues.length;
992
- if (nextLen === currLen)
993
- return;
994
- if (!isAborted)
995
- isAborted = aborted(payload, currLen);
996
- });
997
- }
998
- else {
999
- const nextLen = payload.issues.length;
1000
- if (nextLen === currLen)
1001
- continue;
1002
- if (!isAborted)
1003
- isAborted = aborted(payload, currLen);
1004
- }
1005
- }
1006
- if (asyncResult) {
1007
- return asyncResult.then(() => {
1008
- return payload;
1009
- });
1010
- }
1011
- return payload;
1012
- };
1013
- inst._zod.run = (payload, ctx) => {
1014
- const result = inst._zod.parse(payload, ctx);
1015
- if (result instanceof Promise) {
1016
- if (ctx.async === false)
1017
- throw new $ZodAsyncError();
1018
- return result.then((result) => runChecks(result, checks, ctx));
1019
- }
1020
- return runChecks(result, checks, ctx);
1021
- };
1022
- }
1023
- inst["~standard"] = {
1024
- validate: (value) => {
1025
- try {
1026
- const r = safeParse$1(inst, value);
1027
- return r.success ? { value: r.data } : { issues: r.error?.issues };
1028
- }
1029
- catch (_) {
1030
- return safeParseAsync$1(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));
1031
- }
1032
- },
1033
- vendor: "zod",
1034
- version: 1,
1035
- };
1036
- });
1037
- const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => {
1038
- $ZodType.init(inst, def);
1039
- inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? string$1(inst._zod.bag);
1040
- inst._zod.parse = (payload, _) => {
1041
- if (def.coerce)
1042
- try {
1043
- payload.value = String(payload.value);
1044
- }
1045
- catch (_) { }
1046
- if (typeof payload.value === "string")
1047
- return payload;
1048
- payload.issues.push({
1049
- expected: "string",
1050
- code: "invalid_type",
1051
- input: payload.value,
1052
- inst,
1053
- });
1054
- return payload;
1055
- };
1056
- });
1057
- const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => {
1058
- // check initialization must come first
1059
- $ZodCheckStringFormat.init(inst, def);
1060
- $ZodString.init(inst, def);
1061
- });
1062
- const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => {
1063
- def.pattern ?? (def.pattern = guid);
1064
- $ZodStringFormat.init(inst, def);
1065
- });
1066
- const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => {
1067
- if (def.version) {
1068
- const versionMap = {
1069
- v1: 1,
1070
- v2: 2,
1071
- v3: 3,
1072
- v4: 4,
1073
- v5: 5,
1074
- v6: 6,
1075
- v7: 7,
1076
- v8: 8,
1077
- };
1078
- const v = versionMap[def.version];
1079
- if (v === undefined)
1080
- throw new Error(`Invalid UUID version: "${def.version}"`);
1081
- def.pattern ?? (def.pattern = uuid(v));
1082
- }
1083
- else
1084
- def.pattern ?? (def.pattern = uuid());
1085
- $ZodStringFormat.init(inst, def);
1086
- });
1087
- const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => {
1088
- def.pattern ?? (def.pattern = email);
1089
- $ZodStringFormat.init(inst, def);
1090
- });
1091
- const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => {
1092
- $ZodStringFormat.init(inst, def);
1093
- inst._zod.check = (payload) => {
1094
- try {
1095
- // Trim whitespace from input
1096
- const trimmed = payload.value.trim();
1097
- // @ts-ignore
1098
- const url = new URL(trimmed);
1099
- if (def.hostname) {
1100
- def.hostname.lastIndex = 0;
1101
- if (!def.hostname.test(url.hostname)) {
1102
- payload.issues.push({
1103
- code: "invalid_format",
1104
- format: "url",
1105
- note: "Invalid hostname",
1106
- pattern: hostname.source,
1107
- input: payload.value,
1108
- inst,
1109
- continue: !def.abort,
1110
- });
1111
- }
1112
- }
1113
- if (def.protocol) {
1114
- def.protocol.lastIndex = 0;
1115
- if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) {
1116
- payload.issues.push({
1117
- code: "invalid_format",
1118
- format: "url",
1119
- note: "Invalid protocol",
1120
- pattern: def.protocol.source,
1121
- input: payload.value,
1122
- inst,
1123
- continue: !def.abort,
1124
- });
1125
- }
1126
- }
1127
- // Set the output value based on normalize flag
1128
- if (def.normalize) {
1129
- // Use normalized URL
1130
- payload.value = url.href;
1131
- }
1132
- else {
1133
- // Preserve the original input (trimmed)
1134
- payload.value = trimmed;
1135
- }
1136
- return;
1137
- }
1138
- catch (_) {
1139
- payload.issues.push({
1140
- code: "invalid_format",
1141
- format: "url",
1142
- input: payload.value,
1143
- inst,
1144
- continue: !def.abort,
1145
- });
1146
- }
1147
- };
1148
- });
1149
- const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => {
1150
- def.pattern ?? (def.pattern = emoji());
1151
- $ZodStringFormat.init(inst, def);
1152
- });
1153
- const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => {
1154
- def.pattern ?? (def.pattern = nanoid);
1155
- $ZodStringFormat.init(inst, def);
1156
- });
1157
- const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => {
1158
- def.pattern ?? (def.pattern = cuid);
1159
- $ZodStringFormat.init(inst, def);
1160
- });
1161
- const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => {
1162
- def.pattern ?? (def.pattern = cuid2);
1163
- $ZodStringFormat.init(inst, def);
1164
- });
1165
- const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => {
1166
- def.pattern ?? (def.pattern = ulid);
1167
- $ZodStringFormat.init(inst, def);
1168
- });
1169
- const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => {
1170
- def.pattern ?? (def.pattern = xid);
1171
- $ZodStringFormat.init(inst, def);
1172
- });
1173
- const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => {
1174
- def.pattern ?? (def.pattern = ksuid);
1175
- $ZodStringFormat.init(inst, def);
1176
- });
1177
- const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => {
1178
- def.pattern ?? (def.pattern = datetime$1(def));
1179
- $ZodStringFormat.init(inst, def);
1180
- });
1181
- const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => {
1182
- def.pattern ?? (def.pattern = date$1);
1183
- $ZodStringFormat.init(inst, def);
1184
- });
1185
- const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => {
1186
- def.pattern ?? (def.pattern = time$1(def));
1187
- $ZodStringFormat.init(inst, def);
1188
- });
1189
- const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => {
1190
- def.pattern ?? (def.pattern = duration$1);
1191
- $ZodStringFormat.init(inst, def);
1192
- });
1193
- const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => {
1194
- def.pattern ?? (def.pattern = ipv4);
1195
- $ZodStringFormat.init(inst, def);
1196
- inst._zod.onattach.push((inst) => {
1197
- const bag = inst._zod.bag;
1198
- bag.format = `ipv4`;
1199
- });
1200
- });
1201
- const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => {
1202
- def.pattern ?? (def.pattern = ipv6);
1203
- $ZodStringFormat.init(inst, def);
1204
- inst._zod.onattach.push((inst) => {
1205
- const bag = inst._zod.bag;
1206
- bag.format = `ipv6`;
1207
- });
1208
- inst._zod.check = (payload) => {
1209
- try {
1210
- // @ts-ignore
1211
- new URL(`http://[${payload.value}]`);
1212
- // return;
1213
- }
1214
- catch {
1215
- payload.issues.push({
1216
- code: "invalid_format",
1217
- format: "ipv6",
1218
- input: payload.value,
1219
- inst,
1220
- continue: !def.abort,
1221
- });
1222
- }
1223
- };
1224
- });
1225
- const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => {
1226
- def.pattern ?? (def.pattern = cidrv4);
1227
- $ZodStringFormat.init(inst, def);
1228
- });
1229
- const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => {
1230
- def.pattern ?? (def.pattern = cidrv6); // not used for validation
1231
- $ZodStringFormat.init(inst, def);
1232
- inst._zod.check = (payload) => {
1233
- const [address, prefix] = payload.value.split("/");
1234
- try {
1235
- if (!prefix)
1236
- throw new Error();
1237
- const prefixNum = Number(prefix);
1238
- if (`${prefixNum}` !== prefix)
1239
- throw new Error();
1240
- if (prefixNum < 0 || prefixNum > 128)
1241
- throw new Error();
1242
- // @ts-ignore
1243
- new URL(`http://[${address}]`);
1244
- }
1245
- catch {
1246
- payload.issues.push({
1247
- code: "invalid_format",
1248
- format: "cidrv6",
1249
- input: payload.value,
1250
- inst,
1251
- continue: !def.abort,
1252
- });
1253
- }
1254
- };
1255
- });
1256
- ////////////////////////////// ZodBase64 //////////////////////////////
1257
- function isValidBase64(data) {
1258
- if (data === "")
1259
- return true;
1260
- if (data.length % 4 !== 0)
1261
- return false;
1262
- try {
1263
- // @ts-ignore
1264
- atob(data);
1265
- return true;
1266
- }
1267
- catch {
1268
- return false;
1269
- }
1270
- }
1271
- const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => {
1272
- def.pattern ?? (def.pattern = base64);
1273
- $ZodStringFormat.init(inst, def);
1274
- inst._zod.onattach.push((inst) => {
1275
- inst._zod.bag.contentEncoding = "base64";
1276
- });
1277
- inst._zod.check = (payload) => {
1278
- if (isValidBase64(payload.value))
1279
- return;
1280
- payload.issues.push({
1281
- code: "invalid_format",
1282
- format: "base64",
1283
- input: payload.value,
1284
- inst,
1285
- continue: !def.abort,
1286
- });
1287
- };
1288
- });
1289
- ////////////////////////////// ZodBase64 //////////////////////////////
1290
- function isValidBase64URL(data) {
1291
- if (!base64url.test(data))
1292
- return false;
1293
- const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/"));
1294
- const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
1295
- return isValidBase64(padded);
1296
- }
1297
- const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => {
1298
- def.pattern ?? (def.pattern = base64url);
1299
- $ZodStringFormat.init(inst, def);
1300
- inst._zod.onattach.push((inst) => {
1301
- inst._zod.bag.contentEncoding = "base64url";
1302
- });
1303
- inst._zod.check = (payload) => {
1304
- if (isValidBase64URL(payload.value))
1305
- return;
1306
- payload.issues.push({
1307
- code: "invalid_format",
1308
- format: "base64url",
1309
- input: payload.value,
1310
- inst,
1311
- continue: !def.abort,
1312
- });
1313
- };
1314
- });
1315
- const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => {
1316
- def.pattern ?? (def.pattern = e164);
1317
- $ZodStringFormat.init(inst, def);
1318
- });
1319
- ////////////////////////////// ZodJWT //////////////////////////////
1320
- function isValidJWT(token, algorithm = null) {
1321
- try {
1322
- const tokensParts = token.split(".");
1323
- if (tokensParts.length !== 3)
1324
- return false;
1325
- const [header] = tokensParts;
1326
- if (!header)
1327
- return false;
1328
- // @ts-ignore
1329
- const parsedHeader = JSON.parse(atob(header));
1330
- if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")
1331
- return false;
1332
- if (!parsedHeader.alg)
1333
- return false;
1334
- if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
1335
- return false;
1336
- return true;
1337
- }
1338
- catch {
1339
- return false;
1340
- }
1341
- }
1342
- const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => {
1343
- $ZodStringFormat.init(inst, def);
1344
- inst._zod.check = (payload) => {
1345
- if (isValidJWT(payload.value, def.alg))
1346
- return;
1347
- payload.issues.push({
1348
- code: "invalid_format",
1349
- format: "jwt",
1350
- input: payload.value,
1351
- inst,
1352
- continue: !def.abort,
1353
- });
1354
- };
1355
- });
1356
- const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => {
1357
- $ZodType.init(inst, def);
1358
- inst._zod.parse = (payload) => payload;
1359
- });
1360
- const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => {
1361
- $ZodType.init(inst, def);
1362
- inst._zod.parse = (payload, _ctx) => {
1363
- payload.issues.push({
1364
- expected: "never",
1365
- code: "invalid_type",
1366
- input: payload.value,
1367
- inst,
1368
- });
1369
- return payload;
1370
- };
1371
- });
1372
- function handleArrayResult(result, final, index) {
1373
- if (result.issues.length) {
1374
- final.issues.push(...prefixIssues(index, result.issues));
1375
- }
1376
- final.value[index] = result.value;
1377
- }
1378
- const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => {
1379
- $ZodType.init(inst, def);
1380
- inst._zod.parse = (payload, ctx) => {
1381
- const input = payload.value;
1382
- if (!Array.isArray(input)) {
1383
- payload.issues.push({
1384
- expected: "array",
1385
- code: "invalid_type",
1386
- input,
1387
- inst,
1388
- });
1389
- return payload;
1390
- }
1391
- payload.value = Array(input.length);
1392
- const proms = [];
1393
- for (let i = 0; i < input.length; i++) {
1394
- const item = input[i];
1395
- const result = def.element._zod.run({
1396
- value: item,
1397
- issues: [],
1398
- }, ctx);
1399
- if (result instanceof Promise) {
1400
- proms.push(result.then((result) => handleArrayResult(result, payload, i)));
1401
- }
1402
- else {
1403
- handleArrayResult(result, payload, i);
1404
- }
1405
- }
1406
- if (proms.length) {
1407
- return Promise.all(proms).then(() => payload);
1408
- }
1409
- return payload; //handleArrayResultsAsync(parseResults, final);
1410
- };
1411
- });
1412
- function handlePropertyResult(result, final, key, input) {
1413
- if (result.issues.length) {
1414
- final.issues.push(...prefixIssues(key, result.issues));
1415
- }
1416
- if (result.value === undefined) {
1417
- if (key in input) {
1418
- final.value[key] = undefined;
1419
- }
1420
- }
1421
- else {
1422
- final.value[key] = result.value;
1423
- }
1424
- }
1425
- const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
1426
- // requires cast because technically $ZodObject doesn't extend
1427
- $ZodType.init(inst, def);
1428
- const _normalized = cached(() => {
1429
- const keys = Object.keys(def.shape);
1430
- for (const k of keys) {
1431
- if (!def.shape[k]._zod.traits.has("$ZodType")) {
1432
- throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
1433
- }
1434
- }
1435
- const okeys = optionalKeys(def.shape);
1436
- return {
1437
- shape: def.shape,
1438
- keys,
1439
- keySet: new Set(keys),
1440
- numKeys: keys.length,
1441
- optionalKeys: new Set(okeys),
1442
- };
1443
- });
1444
- defineLazy(inst._zod, "propValues", () => {
1445
- const shape = def.shape;
1446
- const propValues = {};
1447
- for (const key in shape) {
1448
- const field = shape[key]._zod;
1449
- if (field.values) {
1450
- propValues[key] ?? (propValues[key] = new Set());
1451
- for (const v of field.values)
1452
- propValues[key].add(v);
1453
- }
1454
- }
1455
- return propValues;
1456
- });
1457
- const generateFastpass = (shape) => {
1458
- const doc = new Doc(["shape", "payload", "ctx"]);
1459
- const normalized = _normalized.value;
1460
- const parseStr = (key) => {
1461
- const k = esc(key);
1462
- return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
1463
- };
1464
- doc.write(`const input = payload.value;`);
1465
- const ids = Object.create(null);
1466
- let counter = 0;
1467
- for (const key of normalized.keys) {
1468
- ids[key] = `key_${counter++}`;
1469
- }
1470
- // A: preserve key order {
1471
- doc.write(`const newResult = {}`);
1472
- for (const key of normalized.keys) {
1473
- const id = ids[key];
1474
- const k = esc(key);
1475
- doc.write(`const ${id} = ${parseStr(key)};`);
1476
- doc.write(`
1477
- if (${id}.issues.length) {
1478
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
1479
- ...iss,
1480
- path: iss.path ? [${k}, ...iss.path] : [${k}]
1481
- })));
1482
- }
1483
-
1484
- if (${id}.value === undefined) {
1485
- if (${k} in input) {
1486
- newResult[${k}] = undefined;
1487
- }
1488
- } else {
1489
- newResult[${k}] = ${id}.value;
1490
- }
1491
- `);
1492
- }
1493
- doc.write(`payload.value = newResult;`);
1494
- doc.write(`return payload;`);
1495
- const fn = doc.compile();
1496
- return (payload, ctx) => fn(shape, payload, ctx);
1497
- };
1498
- let fastpass;
1499
- const isObject$1 = isObject;
1500
- const jit = !globalConfig.jitless;
1501
- const allowsEval$1 = allowsEval;
1502
- const fastEnabled = jit && allowsEval$1.value; // && !def.catchall;
1503
- const catchall = def.catchall;
1504
- let value;
1505
- inst._zod.parse = (payload, ctx) => {
1506
- value ?? (value = _normalized.value);
1507
- const input = payload.value;
1508
- if (!isObject$1(input)) {
1509
- payload.issues.push({
1510
- expected: "object",
1511
- code: "invalid_type",
1512
- input,
1513
- inst,
1514
- });
1515
- return payload;
1516
- }
1517
- const proms = [];
1518
- if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
1519
- // always synchronous
1520
- if (!fastpass)
1521
- fastpass = generateFastpass(def.shape);
1522
- payload = fastpass(payload, ctx);
1523
- }
1524
- else {
1525
- payload.value = {};
1526
- const shape = value.shape;
1527
- for (const key of value.keys) {
1528
- const el = shape[key];
1529
- const r = el._zod.run({ value: input[key], issues: [] }, ctx);
1530
- if (r instanceof Promise) {
1531
- proms.push(r.then((r) => handlePropertyResult(r, payload, key, input)));
1532
- }
1533
- else {
1534
- handlePropertyResult(r, payload, key, input);
1535
- }
1536
- }
1537
- }
1538
- if (!catchall) {
1539
- return proms.length ? Promise.all(proms).then(() => payload) : payload;
1540
- }
1541
- const unrecognized = [];
1542
- // iterate over input keys
1543
- const keySet = value.keySet;
1544
- const _catchall = catchall._zod;
1545
- const t = _catchall.def.type;
1546
- for (const key of Object.keys(input)) {
1547
- if (keySet.has(key))
1548
- continue;
1549
- if (t === "never") {
1550
- unrecognized.push(key);
1551
- continue;
1552
- }
1553
- const r = _catchall.run({ value: input[key], issues: [] }, ctx);
1554
- if (r instanceof Promise) {
1555
- proms.push(r.then((r) => handlePropertyResult(r, payload, key, input)));
1556
- }
1557
- else {
1558
- handlePropertyResult(r, payload, key, input);
1559
- }
1560
- }
1561
- if (unrecognized.length) {
1562
- payload.issues.push({
1563
- code: "unrecognized_keys",
1564
- keys: unrecognized,
1565
- input,
1566
- inst,
1567
- });
1568
- }
1569
- if (!proms.length)
1570
- return payload;
1571
- return Promise.all(proms).then(() => {
1572
- return payload;
1573
- });
1574
- };
1575
- });
1576
- function handleUnionResults(results, final, inst, ctx) {
1577
- for (const result of results) {
1578
- if (result.issues.length === 0) {
1579
- final.value = result.value;
1580
- return final;
1581
- }
1582
- }
1583
- const nonaborted = results.filter((r) => !aborted(r));
1584
- if (nonaborted.length === 1) {
1585
- final.value = nonaborted[0].value;
1586
- return nonaborted[0];
1587
- }
1588
- final.issues.push({
1589
- code: "invalid_union",
1590
- input: final.value,
1591
- inst,
1592
- errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))),
1593
- });
1594
- return final;
1595
- }
1596
- const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => {
1597
- $ZodType.init(inst, def);
1598
- defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined);
1599
- defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined);
1600
- defineLazy(inst._zod, "values", () => {
1601
- if (def.options.every((o) => o._zod.values)) {
1602
- return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
1603
- }
1604
- return undefined;
1605
- });
1606
- defineLazy(inst._zod, "pattern", () => {
1607
- if (def.options.every((o) => o._zod.pattern)) {
1608
- const patterns = def.options.map((o) => o._zod.pattern);
1609
- return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
1610
- }
1611
- return undefined;
1612
- });
1613
- const single = def.options.length === 1;
1614
- const first = def.options[0]._zod.run;
1615
- inst._zod.parse = (payload, ctx) => {
1616
- if (single) {
1617
- return first(payload, ctx);
1618
- }
1619
- let async = false;
1620
- const results = [];
1621
- for (const option of def.options) {
1622
- const result = option._zod.run({
1623
- value: payload.value,
1624
- issues: [],
1625
- }, ctx);
1626
- if (result instanceof Promise) {
1627
- results.push(result);
1628
- async = true;
1629
- }
1630
- else {
1631
- if (result.issues.length === 0)
1632
- return result;
1633
- results.push(result);
1634
- }
1635
- }
1636
- if (!async)
1637
- return handleUnionResults(results, payload, inst, ctx);
1638
- return Promise.all(results).then((results) => {
1639
- return handleUnionResults(results, payload, inst, ctx);
1640
- });
1641
- };
1642
- });
1643
- const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => {
1644
- $ZodType.init(inst, def);
1645
- inst._zod.parse = (payload, ctx) => {
1646
- const input = payload.value;
1647
- const left = def.left._zod.run({ value: input, issues: [] }, ctx);
1648
- const right = def.right._zod.run({ value: input, issues: [] }, ctx);
1649
- const async = left instanceof Promise || right instanceof Promise;
1650
- if (async) {
1651
- return Promise.all([left, right]).then(([left, right]) => {
1652
- return handleIntersectionResults(payload, left, right);
1653
- });
1654
- }
1655
- return handleIntersectionResults(payload, left, right);
1656
- };
1657
- });
1658
- function mergeValues(a, b) {
1659
- // const aType = parse.t(a);
1660
- // const bType = parse.t(b);
1661
- if (a === b) {
1662
- return { valid: true, data: a };
1663
- }
1664
- if (a instanceof Date && b instanceof Date && +a === +b) {
1665
- return { valid: true, data: a };
1666
- }
1667
- if (isPlainObject(a) && isPlainObject(b)) {
1668
- const bKeys = Object.keys(b);
1669
- const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
1670
- const newObj = { ...a, ...b };
1671
- for (const key of sharedKeys) {
1672
- const sharedValue = mergeValues(a[key], b[key]);
1673
- if (!sharedValue.valid) {
1674
- return {
1675
- valid: false,
1676
- mergeErrorPath: [key, ...sharedValue.mergeErrorPath],
1677
- };
1678
- }
1679
- newObj[key] = sharedValue.data;
1680
- }
1681
- return { valid: true, data: newObj };
1682
- }
1683
- if (Array.isArray(a) && Array.isArray(b)) {
1684
- if (a.length !== b.length) {
1685
- return { valid: false, mergeErrorPath: [] };
1686
- }
1687
- const newArray = [];
1688
- for (let index = 0; index < a.length; index++) {
1689
- const itemA = a[index];
1690
- const itemB = b[index];
1691
- const sharedValue = mergeValues(itemA, itemB);
1692
- if (!sharedValue.valid) {
1693
- return {
1694
- valid: false,
1695
- mergeErrorPath: [index, ...sharedValue.mergeErrorPath],
1696
- };
1697
- }
1698
- newArray.push(sharedValue.data);
1699
- }
1700
- return { valid: true, data: newArray };
1701
- }
1702
- return { valid: false, mergeErrorPath: [] };
1703
- }
1704
- function handleIntersectionResults(result, left, right) {
1705
- if (left.issues.length) {
1706
- result.issues.push(...left.issues);
1707
- }
1708
- if (right.issues.length) {
1709
- result.issues.push(...right.issues);
1710
- }
1711
- if (aborted(result))
1712
- return result;
1713
- const merged = mergeValues(left.value, right.value);
1714
- if (!merged.valid) {
1715
- throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);
1716
- }
1717
- result.value = merged.data;
1718
- return result;
1719
- }
1720
- const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => {
1721
- $ZodType.init(inst, def);
1722
- inst._zod.parse = (payload, ctx) => {
1723
- const input = payload.value;
1724
- if (!isPlainObject(input)) {
1725
- payload.issues.push({
1726
- expected: "record",
1727
- code: "invalid_type",
1728
- input,
1729
- inst,
1730
- });
1731
- return payload;
1732
- }
1733
- const proms = [];
1734
- if (def.keyType._zod.values) {
1735
- const values = def.keyType._zod.values;
1736
- payload.value = {};
1737
- for (const key of values) {
1738
- if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
1739
- const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
1740
- if (result instanceof Promise) {
1741
- proms.push(result.then((result) => {
1742
- if (result.issues.length) {
1743
- payload.issues.push(...prefixIssues(key, result.issues));
1744
- }
1745
- payload.value[key] = result.value;
1746
- }));
1747
- }
1748
- else {
1749
- if (result.issues.length) {
1750
- payload.issues.push(...prefixIssues(key, result.issues));
1751
- }
1752
- payload.value[key] = result.value;
1753
- }
1754
- }
1755
- }
1756
- let unrecognized;
1757
- for (const key in input) {
1758
- if (!values.has(key)) {
1759
- unrecognized = unrecognized ?? [];
1760
- unrecognized.push(key);
1761
- }
1762
- }
1763
- if (unrecognized && unrecognized.length > 0) {
1764
- payload.issues.push({
1765
- code: "unrecognized_keys",
1766
- input,
1767
- inst,
1768
- keys: unrecognized,
1769
- });
1770
- }
1771
- }
1772
- else {
1773
- payload.value = {};
1774
- for (const key of Reflect.ownKeys(input)) {
1775
- if (key === "__proto__")
1776
- continue;
1777
- const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
1778
- if (keyResult instanceof Promise) {
1779
- throw new Error("Async schemas not supported in object keys currently");
1780
- }
1781
- if (keyResult.issues.length) {
1782
- payload.issues.push({
1783
- code: "invalid_key",
1784
- origin: "record",
1785
- issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
1786
- input: key,
1787
- path: [key],
1788
- inst,
1789
- });
1790
- payload.value[keyResult.value] = keyResult.value;
1791
- continue;
1792
- }
1793
- const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
1794
- if (result instanceof Promise) {
1795
- proms.push(result.then((result) => {
1796
- if (result.issues.length) {
1797
- payload.issues.push(...prefixIssues(key, result.issues));
1798
- }
1799
- payload.value[keyResult.value] = result.value;
1800
- }));
1801
- }
1802
- else {
1803
- if (result.issues.length) {
1804
- payload.issues.push(...prefixIssues(key, result.issues));
1805
- }
1806
- payload.value[keyResult.value] = result.value;
1807
- }
1808
- }
1809
- }
1810
- if (proms.length) {
1811
- return Promise.all(proms).then(() => payload);
1812
- }
1813
- return payload;
1814
- };
1815
- });
1816
- const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => {
1817
- $ZodType.init(inst, def);
1818
- const values = getEnumValues(def.entries);
1819
- const valuesSet = new Set(values);
1820
- inst._zod.values = valuesSet;
1821
- inst._zod.pattern = new RegExp(`^(${values
1822
- .filter((k) => propertyKeyTypes.has(typeof k))
1823
- .map((o) => (typeof o === "string" ? escapeRegex(o) : o.toString()))
1824
- .join("|")})$`);
1825
- inst._zod.parse = (payload, _ctx) => {
1826
- const input = payload.value;
1827
- if (valuesSet.has(input)) {
1828
- return payload;
1829
- }
1830
- payload.issues.push({
1831
- code: "invalid_value",
1832
- values,
1833
- input,
1834
- inst,
1835
- });
1836
- return payload;
1837
- };
1838
- });
1839
- const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => {
1840
- $ZodType.init(inst, def);
1841
- inst._zod.parse = (payload, _ctx) => {
1842
- const _out = def.transform(payload.value, payload);
1843
- if (_ctx.async) {
1844
- const output = _out instanceof Promise ? _out : Promise.resolve(_out);
1845
- return output.then((output) => {
1846
- payload.value = output;
1847
- return payload;
1848
- });
1849
- }
1850
- if (_out instanceof Promise) {
1851
- throw new $ZodAsyncError();
1852
- }
1853
- payload.value = _out;
1854
- return payload;
1855
- };
1856
- });
1857
- function handleOptionalResult(result, input) {
1858
- if (result.issues.length && input === undefined) {
1859
- return { issues: [], value: undefined };
1860
- }
1861
- return result;
1862
- }
1863
- const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => {
1864
- $ZodType.init(inst, def);
1865
- inst._zod.optin = "optional";
1866
- inst._zod.optout = "optional";
1867
- defineLazy(inst._zod, "values", () => {
1868
- return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;
1869
- });
1870
- defineLazy(inst._zod, "pattern", () => {
1871
- const pattern = def.innerType._zod.pattern;
1872
- return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined;
1873
- });
1874
- inst._zod.parse = (payload, ctx) => {
1875
- if (def.innerType._zod.optin === "optional") {
1876
- const result = def.innerType._zod.run(payload, ctx);
1877
- if (result instanceof Promise)
1878
- return result.then((r) => handleOptionalResult(r, payload.value));
1879
- return handleOptionalResult(result, payload.value);
1880
- }
1881
- if (payload.value === undefined) {
1882
- return payload;
1883
- }
1884
- return def.innerType._zod.run(payload, ctx);
1885
- };
1886
- });
1887
- const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => {
1888
- $ZodType.init(inst, def);
1889
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
1890
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
1891
- defineLazy(inst._zod, "pattern", () => {
1892
- const pattern = def.innerType._zod.pattern;
1893
- return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined;
1894
- });
1895
- defineLazy(inst._zod, "values", () => {
1896
- return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;
1897
- });
1898
- inst._zod.parse = (payload, ctx) => {
1899
- if (payload.value === null)
1900
- return payload;
1901
- return def.innerType._zod.run(payload, ctx);
1902
- };
1903
- });
1904
- const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => {
1905
- $ZodType.init(inst, def);
1906
- // inst._zod.qin = "true";
1907
- inst._zod.optin = "optional";
1908
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1909
- inst._zod.parse = (payload, ctx) => {
1910
- if (payload.value === undefined) {
1911
- payload.value = def.defaultValue;
1912
- /**
1913
- * $ZodDefault always returns the default value immediately.
1914
- * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */
1915
- return payload;
1916
- }
1917
- const result = def.innerType._zod.run(payload, ctx);
1918
- if (result instanceof Promise) {
1919
- return result.then((result) => handleDefaultResult(result, def));
1920
- }
1921
- return handleDefaultResult(result, def);
1922
- };
1923
- });
1924
- function handleDefaultResult(payload, def) {
1925
- if (payload.value === undefined) {
1926
- payload.value = def.defaultValue;
1927
- }
1928
- return payload;
1929
- }
1930
- const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => {
1931
- $ZodType.init(inst, def);
1932
- inst._zod.optin = "optional";
1933
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1934
- inst._zod.parse = (payload, ctx) => {
1935
- if (payload.value === undefined) {
1936
- payload.value = def.defaultValue;
1937
- }
1938
- return def.innerType._zod.run(payload, ctx);
1939
- };
1940
- });
1941
- const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => {
1942
- $ZodType.init(inst, def);
1943
- defineLazy(inst._zod, "values", () => {
1944
- const v = def.innerType._zod.values;
1945
- return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;
1946
- });
1947
- inst._zod.parse = (payload, ctx) => {
1948
- const result = def.innerType._zod.run(payload, ctx);
1949
- if (result instanceof Promise) {
1950
- return result.then((result) => handleNonOptionalResult(result, inst));
1951
- }
1952
- return handleNonOptionalResult(result, inst);
1953
- };
1954
- });
1955
- function handleNonOptionalResult(payload, inst) {
1956
- if (!payload.issues.length && payload.value === undefined) {
1957
- payload.issues.push({
1958
- code: "invalid_type",
1959
- expected: "nonoptional",
1960
- input: payload.value,
1961
- inst,
1962
- });
1963
- }
1964
- return payload;
1965
- }
1966
- const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => {
1967
- $ZodType.init(inst, def);
1968
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
1969
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
1970
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1971
- inst._zod.parse = (payload, ctx) => {
1972
- const result = def.innerType._zod.run(payload, ctx);
1973
- if (result instanceof Promise) {
1974
- return result.then((result) => {
1975
- payload.value = result.value;
1976
- if (result.issues.length) {
1977
- payload.value = def.catchValue({
1978
- ...payload,
1979
- error: {
1980
- issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())),
1981
- },
1982
- input: payload.value,
1983
- });
1984
- payload.issues = [];
1985
- }
1986
- return payload;
1987
- });
1988
- }
1989
- payload.value = result.value;
1990
- if (result.issues.length) {
1991
- payload.value = def.catchValue({
1992
- ...payload,
1993
- error: {
1994
- issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())),
1995
- },
1996
- input: payload.value,
1997
- });
1998
- payload.issues = [];
1999
- }
2000
- return payload;
2001
- };
2002
- });
2003
- const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => {
2004
- $ZodType.init(inst, def);
2005
- defineLazy(inst._zod, "values", () => def.in._zod.values);
2006
- defineLazy(inst._zod, "optin", () => def.in._zod.optin);
2007
- defineLazy(inst._zod, "optout", () => def.out._zod.optout);
2008
- defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
2009
- inst._zod.parse = (payload, ctx) => {
2010
- const left = def.in._zod.run(payload, ctx);
2011
- if (left instanceof Promise) {
2012
- return left.then((left) => handlePipeResult(left, def, ctx));
2013
- }
2014
- return handlePipeResult(left, def, ctx);
2015
- };
2016
- });
2017
- function handlePipeResult(left, def, ctx) {
2018
- if (left.issues.length) {
2019
- return left;
2020
- }
2021
- return def.out._zod.run({ value: left.value, issues: left.issues }, ctx);
2022
- }
2023
- const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => {
2024
- $ZodType.init(inst, def);
2025
- defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
2026
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2027
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
2028
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
2029
- inst._zod.parse = (payload, ctx) => {
2030
- const result = def.innerType._zod.run(payload, ctx);
2031
- if (result instanceof Promise) {
2032
- return result.then(handleReadonlyResult);
2033
- }
2034
- return handleReadonlyResult(result);
2035
- };
2036
- });
2037
- function handleReadonlyResult(payload) {
2038
- payload.value = Object.freeze(payload.value);
2039
- return payload;
2040
- }
2041
- const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => {
2042
- $ZodCheck.init(inst, def);
2043
- $ZodType.init(inst, def);
2044
- inst._zod.parse = (payload, _) => {
2045
- return payload;
2046
- };
2047
- inst._zod.check = (payload) => {
2048
- const input = payload.value;
2049
- const r = def.fn(input);
2050
- if (r instanceof Promise) {
2051
- return r.then((r) => handleRefineResult(r, payload, input, inst));
2052
- }
2053
- handleRefineResult(r, payload, input, inst);
2054
- return;
2055
- };
2056
- });
2057
- function handleRefineResult(result, payload, input, inst) {
2058
- if (!result) {
2059
- const _iss = {
2060
- code: "custom",
2061
- input,
2062
- inst, // incorporates params.error into issue reporting
2063
- path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting
2064
- continue: !inst._zod.def.abort,
2065
- // params: inst._zod.def.params,
2066
- };
2067
- if (inst._zod.def.params)
2068
- _iss.params = inst._zod.def.params;
2069
- payload.issues.push(issue(_iss));
2070
- }
2071
- }
2072
-
2073
- class $ZodRegistry {
2074
- constructor() {
2075
- this._map = new Map();
2076
- this._idmap = new Map();
2077
- }
2078
- add(schema, ..._meta) {
2079
- const meta = _meta[0];
2080
- this._map.set(schema, meta);
2081
- if (meta && typeof meta === "object" && "id" in meta) {
2082
- if (this._idmap.has(meta.id)) {
2083
- throw new Error(`ID ${meta.id} already exists in the registry`);
2084
- }
2085
- this._idmap.set(meta.id, schema);
2086
- }
2087
- return this;
2088
- }
2089
- clear() {
2090
- this._map = new Map();
2091
- this._idmap = new Map();
2092
- return this;
2093
- }
2094
- remove(schema) {
2095
- const meta = this._map.get(schema);
2096
- if (meta && typeof meta === "object" && "id" in meta) {
2097
- this._idmap.delete(meta.id);
2098
- }
2099
- this._map.delete(schema);
2100
- return this;
2101
- }
2102
- get(schema) {
2103
- // return this._map.get(schema) as any;
2104
- // inherit metadata
2105
- const p = schema._zod.parent;
2106
- if (p) {
2107
- const pm = { ...(this.get(p) ?? {}) };
2108
- delete pm.id; // do not inherit id
2109
- const f = { ...pm, ...this._map.get(schema) };
2110
- return Object.keys(f).length ? f : undefined;
2111
- }
2112
- return this._map.get(schema);
2113
- }
2114
- has(schema) {
2115
- return this._map.has(schema);
2116
- }
2117
- }
2118
- // registries
2119
- function registry() {
2120
- return new $ZodRegistry();
2121
- }
2122
- const globalRegistry = /*@__PURE__*/ registry();
2123
-
2124
- function _string(Class, params) {
2125
- return new Class({
2126
- type: "string",
2127
- ...normalizeParams(params),
2128
- });
2129
- }
2130
- function _email(Class, params) {
2131
- return new Class({
2132
- type: "string",
2133
- format: "email",
2134
- check: "string_format",
2135
- abort: false,
2136
- ...normalizeParams(params),
2137
- });
2138
- }
2139
- function _guid(Class, params) {
2140
- return new Class({
2141
- type: "string",
2142
- format: "guid",
2143
- check: "string_format",
2144
- abort: false,
2145
- ...normalizeParams(params),
2146
- });
2147
- }
2148
- function _uuid(Class, params) {
2149
- return new Class({
2150
- type: "string",
2151
- format: "uuid",
2152
- check: "string_format",
2153
- abort: false,
2154
- ...normalizeParams(params),
2155
- });
2156
- }
2157
- function _uuidv4(Class, params) {
2158
- return new Class({
2159
- type: "string",
2160
- format: "uuid",
2161
- check: "string_format",
2162
- abort: false,
2163
- version: "v4",
2164
- ...normalizeParams(params),
2165
- });
2166
- }
2167
- function _uuidv6(Class, params) {
2168
- return new Class({
2169
- type: "string",
2170
- format: "uuid",
2171
- check: "string_format",
2172
- abort: false,
2173
- version: "v6",
2174
- ...normalizeParams(params),
2175
- });
2176
- }
2177
- function _uuidv7(Class, params) {
2178
- return new Class({
2179
- type: "string",
2180
- format: "uuid",
2181
- check: "string_format",
2182
- abort: false,
2183
- version: "v7",
2184
- ...normalizeParams(params),
2185
- });
2186
- }
2187
- function _url(Class, params) {
2188
- return new Class({
2189
- type: "string",
2190
- format: "url",
2191
- check: "string_format",
2192
- abort: false,
2193
- ...normalizeParams(params),
2194
- });
2195
- }
2196
- function _emoji(Class, params) {
2197
- return new Class({
2198
- type: "string",
2199
- format: "emoji",
2200
- check: "string_format",
2201
- abort: false,
2202
- ...normalizeParams(params),
2203
- });
2204
- }
2205
- function _nanoid(Class, params) {
2206
- return new Class({
2207
- type: "string",
2208
- format: "nanoid",
2209
- check: "string_format",
2210
- abort: false,
2211
- ...normalizeParams(params),
2212
- });
2213
- }
2214
- function _cuid(Class, params) {
2215
- return new Class({
2216
- type: "string",
2217
- format: "cuid",
2218
- check: "string_format",
2219
- abort: false,
2220
- ...normalizeParams(params),
2221
- });
2222
- }
2223
- function _cuid2(Class, params) {
2224
- return new Class({
2225
- type: "string",
2226
- format: "cuid2",
2227
- check: "string_format",
2228
- abort: false,
2229
- ...normalizeParams(params),
2230
- });
2231
- }
2232
- function _ulid(Class, params) {
2233
- return new Class({
2234
- type: "string",
2235
- format: "ulid",
2236
- check: "string_format",
2237
- abort: false,
2238
- ...normalizeParams(params),
2239
- });
2240
- }
2241
- function _xid(Class, params) {
2242
- return new Class({
2243
- type: "string",
2244
- format: "xid",
2245
- check: "string_format",
2246
- abort: false,
2247
- ...normalizeParams(params),
2248
- });
2249
- }
2250
- function _ksuid(Class, params) {
2251
- return new Class({
2252
- type: "string",
2253
- format: "ksuid",
2254
- check: "string_format",
2255
- abort: false,
2256
- ...normalizeParams(params),
2257
- });
2258
- }
2259
- function _ipv4(Class, params) {
2260
- return new Class({
2261
- type: "string",
2262
- format: "ipv4",
2263
- check: "string_format",
2264
- abort: false,
2265
- ...normalizeParams(params),
2266
- });
2267
- }
2268
- function _ipv6(Class, params) {
2269
- return new Class({
2270
- type: "string",
2271
- format: "ipv6",
2272
- check: "string_format",
2273
- abort: false,
2274
- ...normalizeParams(params),
2275
- });
2276
- }
2277
- function _cidrv4(Class, params) {
2278
- return new Class({
2279
- type: "string",
2280
- format: "cidrv4",
2281
- check: "string_format",
2282
- abort: false,
2283
- ...normalizeParams(params),
2284
- });
2285
- }
2286
- function _cidrv6(Class, params) {
2287
- return new Class({
2288
- type: "string",
2289
- format: "cidrv6",
2290
- check: "string_format",
2291
- abort: false,
2292
- ...normalizeParams(params),
2293
- });
2294
- }
2295
- function _base64(Class, params) {
2296
- return new Class({
2297
- type: "string",
2298
- format: "base64",
2299
- check: "string_format",
2300
- abort: false,
2301
- ...normalizeParams(params),
2302
- });
2303
- }
2304
- function _base64url(Class, params) {
2305
- return new Class({
2306
- type: "string",
2307
- format: "base64url",
2308
- check: "string_format",
2309
- abort: false,
2310
- ...normalizeParams(params),
2311
- });
2312
- }
2313
- function _e164(Class, params) {
2314
- return new Class({
2315
- type: "string",
2316
- format: "e164",
2317
- check: "string_format",
2318
- abort: false,
2319
- ...normalizeParams(params),
2320
- });
2321
- }
2322
- function _jwt(Class, params) {
2323
- return new Class({
2324
- type: "string",
2325
- format: "jwt",
2326
- check: "string_format",
2327
- abort: false,
2328
- ...normalizeParams(params),
2329
- });
2330
- }
2331
- function _isoDateTime(Class, params) {
2332
- return new Class({
2333
- type: "string",
2334
- format: "datetime",
2335
- check: "string_format",
2336
- offset: false,
2337
- local: false,
2338
- precision: null,
2339
- ...normalizeParams(params),
2340
- });
2341
- }
2342
- function _isoDate(Class, params) {
2343
- return new Class({
2344
- type: "string",
2345
- format: "date",
2346
- check: "string_format",
2347
- ...normalizeParams(params),
2348
- });
2349
- }
2350
- function _isoTime(Class, params) {
2351
- return new Class({
2352
- type: "string",
2353
- format: "time",
2354
- check: "string_format",
2355
- precision: null,
2356
- ...normalizeParams(params),
2357
- });
2358
- }
2359
- function _isoDuration(Class, params) {
2360
- return new Class({
2361
- type: "string",
2362
- format: "duration",
2363
- check: "string_format",
2364
- ...normalizeParams(params),
2365
- });
2366
- }
2367
- function _unknown(Class) {
2368
- return new Class({
2369
- type: "unknown",
2370
- });
2371
- }
2372
- function _never(Class, params) {
2373
- return new Class({
2374
- type: "never",
2375
- ...normalizeParams(params),
2376
- });
2377
- }
2378
- function _maxLength(maximum, params) {
2379
- const ch = new $ZodCheckMaxLength({
2380
- check: "max_length",
2381
- ...normalizeParams(params),
2382
- maximum,
2383
- });
2384
- return ch;
2385
- }
2386
- function _minLength(minimum, params) {
2387
- return new $ZodCheckMinLength({
2388
- check: "min_length",
2389
- ...normalizeParams(params),
2390
- minimum,
2391
- });
2392
- }
2393
- function _length(length, params) {
2394
- return new $ZodCheckLengthEquals({
2395
- check: "length_equals",
2396
- ...normalizeParams(params),
2397
- length,
2398
- });
2399
- }
2400
- function _regex(pattern, params) {
2401
- return new $ZodCheckRegex({
2402
- check: "string_format",
2403
- format: "regex",
2404
- ...normalizeParams(params),
2405
- pattern,
2406
- });
2407
- }
2408
- function _lowercase(params) {
2409
- return new $ZodCheckLowerCase({
2410
- check: "string_format",
2411
- format: "lowercase",
2412
- ...normalizeParams(params),
2413
- });
2414
- }
2415
- function _uppercase(params) {
2416
- return new $ZodCheckUpperCase({
2417
- check: "string_format",
2418
- format: "uppercase",
2419
- ...normalizeParams(params),
2420
- });
2421
- }
2422
- function _includes(includes, params) {
2423
- return new $ZodCheckIncludes({
2424
- check: "string_format",
2425
- format: "includes",
2426
- ...normalizeParams(params),
2427
- includes,
2428
- });
2429
- }
2430
- function _startsWith(prefix, params) {
2431
- return new $ZodCheckStartsWith({
2432
- check: "string_format",
2433
- format: "starts_with",
2434
- ...normalizeParams(params),
2435
- prefix,
2436
- });
2437
- }
2438
- function _endsWith(suffix, params) {
2439
- return new $ZodCheckEndsWith({
2440
- check: "string_format",
2441
- format: "ends_with",
2442
- ...normalizeParams(params),
2443
- suffix,
2444
- });
2445
- }
2446
- function _overwrite(tx) {
2447
- return new $ZodCheckOverwrite({
2448
- check: "overwrite",
2449
- tx,
2450
- });
2451
- }
2452
- // normalize
2453
- function _normalize(form) {
2454
- return _overwrite((input) => input.normalize(form));
2455
- }
2456
- // trim
2457
- function _trim() {
2458
- return _overwrite((input) => input.trim());
2459
- }
2460
- // toLowerCase
2461
- function _toLowerCase() {
2462
- return _overwrite((input) => input.toLowerCase());
2463
- }
2464
- // toUpperCase
2465
- function _toUpperCase() {
2466
- return _overwrite((input) => input.toUpperCase());
2467
- }
2468
- function _array(Class, element, params) {
2469
- return new Class({
2470
- type: "array",
2471
- element,
2472
- // get element() {
2473
- // return element;
2474
- // },
2475
- ...normalizeParams(params),
2476
- });
2477
- }
2478
- // same as _custom but defaults to abort:false
2479
- function _refine(Class, fn, _params) {
2480
- const schema = new Class({
2481
- type: "custom",
2482
- check: "custom",
2483
- fn: fn,
2484
- ...normalizeParams(_params),
2485
- });
2486
- return schema;
2487
- }
2488
- function _superRefine(fn) {
2489
- const ch = _check((payload) => {
2490
- payload.addIssue = (issue$1) => {
2491
- if (typeof issue$1 === "string") {
2492
- payload.issues.push(issue(issue$1, payload.value, ch._zod.def));
2493
- }
2494
- else {
2495
- // for Zod 3 backwards compatibility
2496
- const _issue = issue$1;
2497
- if (_issue.fatal)
2498
- _issue.continue = false;
2499
- _issue.code ?? (_issue.code = "custom");
2500
- _issue.input ?? (_issue.input = payload.value);
2501
- _issue.inst ?? (_issue.inst = ch);
2502
- _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
2503
- payload.issues.push(issue(_issue));
2504
- }
2505
- };
2506
- return fn(payload.value, payload);
2507
- });
2508
- return ch;
2509
- }
2510
- function _check(fn, params) {
2511
- const ch = new $ZodCheck({
2512
- check: "custom",
2513
- ...normalizeParams(params),
2514
- });
2515
- ch._zod.check = fn;
2516
- return ch;
2517
- }
2518
-
2519
- const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
2520
- $ZodISODateTime.init(inst, def);
2521
- ZodStringFormat.init(inst, def);
2522
- });
2523
- function datetime(params) {
2524
- return _isoDateTime(ZodISODateTime, params);
2525
- }
2526
- const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => {
2527
- $ZodISODate.init(inst, def);
2528
- ZodStringFormat.init(inst, def);
2529
- });
2530
- function date(params) {
2531
- return _isoDate(ZodISODate, params);
2532
- }
2533
- const ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => {
2534
- $ZodISOTime.init(inst, def);
2535
- ZodStringFormat.init(inst, def);
2536
- });
2537
- function time(params) {
2538
- return _isoTime(ZodISOTime, params);
2539
- }
2540
- const ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => {
2541
- $ZodISODuration.init(inst, def);
2542
- ZodStringFormat.init(inst, def);
2543
- });
2544
- function duration(params) {
2545
- return _isoDuration(ZodISODuration, params);
2546
- }
2547
-
2548
- const initializer = (inst, issues) => {
2549
- $ZodError.init(inst, issues);
2550
- inst.name = "ZodError";
2551
- Object.defineProperties(inst, {
2552
- format: {
2553
- value: (mapper) => formatError(inst, mapper),
2554
- // enumerable: false,
2555
- },
2556
- flatten: {
2557
- value: (mapper) => flattenError(inst, mapper),
2558
- // enumerable: false,
2559
- },
2560
- addIssue: {
2561
- value: (issue) => {
2562
- inst.issues.push(issue);
2563
- inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
2564
- },
2565
- // enumerable: false,
2566
- },
2567
- addIssues: {
2568
- value: (issues) => {
2569
- inst.issues.push(...issues);
2570
- inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
2571
- },
2572
- // enumerable: false,
2573
- },
2574
- isEmpty: {
2575
- get() {
2576
- return inst.issues.length === 0;
2577
- },
2578
- // enumerable: false,
2579
- },
2580
- });
2581
- // Object.defineProperty(inst, "isEmpty", {
2582
- // get() {
2583
- // return inst.issues.length === 0;
2584
- // },
2585
- // });
2586
- };
2587
- const ZodRealError = $constructor("ZodError", initializer, {
2588
- Parent: Error,
2589
- });
2590
- // /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */
2591
- // export type ErrorMapCtx = core.$ZodErrorMapCtx;
2592
-
2593
- const parse = /* @__PURE__ */ _parse(ZodRealError);
2594
- const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
2595
- const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
2596
- const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
2597
-
2598
- const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => {
2599
- $ZodType.init(inst, def);
2600
- inst.def = def;
2601
- Object.defineProperty(inst, "_def", { value: def });
2602
- // base methods
2603
- inst.check = (...checks) => {
2604
- return inst.clone({
2605
- ...def,
2606
- checks: [
2607
- ...(def.checks ?? []),
2608
- ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch),
2609
- ],
2610
- }
2611
- // { parent: true }
2612
- );
2613
- };
2614
- inst.clone = (def, params) => clone(inst, def, params);
2615
- inst.brand = () => inst;
2616
- inst.register = ((reg, meta) => {
2617
- reg.add(inst, meta);
2618
- return inst;
2619
- });
2620
- // parsing
2621
- inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });
2622
- inst.safeParse = (data, params) => safeParse(inst, data, params);
2623
- inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
2624
- inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
2625
- inst.spa = inst.safeParseAsync;
2626
- // refinements
2627
- inst.refine = (check, params) => inst.check(refine(check, params));
2628
- inst.superRefine = (refinement) => inst.check(superRefine(refinement));
2629
- inst.overwrite = (fn) => inst.check(_overwrite(fn));
2630
- // wrappers
2631
- inst.optional = () => optional(inst);
2632
- inst.nullable = () => nullable(inst);
2633
- inst.nullish = () => optional(nullable(inst));
2634
- inst.nonoptional = (params) => nonoptional(inst, params);
2635
- inst.array = () => array(inst);
2636
- inst.or = (arg) => union([inst, arg]);
2637
- inst.and = (arg) => intersection(inst, arg);
2638
- inst.transform = (tx) => pipe(inst, transform(tx));
2639
- inst.default = (def) => _default(inst, def);
2640
- inst.prefault = (def) => prefault(inst, def);
2641
- // inst.coalesce = (def, params) => coalesce(inst, def, params);
2642
- inst.catch = (params) => _catch(inst, params);
2643
- inst.pipe = (target) => pipe(inst, target);
2644
- inst.readonly = () => readonly(inst);
2645
- // meta
2646
- inst.describe = (description) => {
2647
- const cl = inst.clone();
2648
- globalRegistry.add(cl, { description });
2649
- return cl;
2650
- };
2651
- Object.defineProperty(inst, "description", {
2652
- get() {
2653
- return globalRegistry.get(inst)?.description;
2654
- },
2655
- configurable: true,
2656
- });
2657
- inst.meta = (...args) => {
2658
- if (args.length === 0) {
2659
- return globalRegistry.get(inst);
2660
- }
2661
- const cl = inst.clone();
2662
- globalRegistry.add(cl, args[0]);
2663
- return cl;
2664
- };
2665
- // helpers
2666
- inst.isOptional = () => inst.safeParse(undefined).success;
2667
- inst.isNullable = () => inst.safeParse(null).success;
2668
- return inst;
2669
- });
2670
- /** @internal */
2671
- const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => {
2672
- $ZodString.init(inst, def);
2673
- ZodType.init(inst, def);
2674
- const bag = inst._zod.bag;
2675
- inst.format = bag.format ?? null;
2676
- inst.minLength = bag.minimum ?? null;
2677
- inst.maxLength = bag.maximum ?? null;
2678
- // validations
2679
- inst.regex = (...args) => inst.check(_regex(...args));
2680
- inst.includes = (...args) => inst.check(_includes(...args));
2681
- inst.startsWith = (...args) => inst.check(_startsWith(...args));
2682
- inst.endsWith = (...args) => inst.check(_endsWith(...args));
2683
- inst.min = (...args) => inst.check(_minLength(...args));
2684
- inst.max = (...args) => inst.check(_maxLength(...args));
2685
- inst.length = (...args) => inst.check(_length(...args));
2686
- inst.nonempty = (...args) => inst.check(_minLength(1, ...args));
2687
- inst.lowercase = (params) => inst.check(_lowercase(params));
2688
- inst.uppercase = (params) => inst.check(_uppercase(params));
2689
- // transforms
2690
- inst.trim = () => inst.check(_trim());
2691
- inst.normalize = (...args) => inst.check(_normalize(...args));
2692
- inst.toLowerCase = () => inst.check(_toLowerCase());
2693
- inst.toUpperCase = () => inst.check(_toUpperCase());
2694
- });
2695
- const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => {
2696
- $ZodString.init(inst, def);
2697
- _ZodString.init(inst, def);
2698
- inst.email = (params) => inst.check(_email(ZodEmail, params));
2699
- inst.url = (params) => inst.check(_url(ZodURL, params));
2700
- inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
2701
- inst.emoji = (params) => inst.check(_emoji(ZodEmoji, params));
2702
- inst.guid = (params) => inst.check(_guid(ZodGUID, params));
2703
- inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
2704
- inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
2705
- inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
2706
- inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
2707
- inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
2708
- inst.guid = (params) => inst.check(_guid(ZodGUID, params));
2709
- inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
2710
- inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
2711
- inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
2712
- inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
2713
- inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
2714
- inst.xid = (params) => inst.check(_xid(ZodXID, params));
2715
- inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
2716
- inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
2717
- inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
2718
- inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
2719
- inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
2720
- inst.e164 = (params) => inst.check(_e164(ZodE164, params));
2721
- // iso
2722
- inst.datetime = (params) => inst.check(datetime(params));
2723
- inst.date = (params) => inst.check(date(params));
2724
- inst.time = (params) => inst.check(time(params));
2725
- inst.duration = (params) => inst.check(duration(params));
2726
- });
2727
- function string(params) {
2728
- return _string(ZodString, params);
2729
- }
2730
- const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => {
2731
- $ZodStringFormat.init(inst, def);
2732
- _ZodString.init(inst, def);
2733
- });
2734
- const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => {
2735
- // ZodStringFormat.init(inst, def);
2736
- $ZodEmail.init(inst, def);
2737
- ZodStringFormat.init(inst, def);
2738
- });
2739
- const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => {
2740
- // ZodStringFormat.init(inst, def);
2741
- $ZodGUID.init(inst, def);
2742
- ZodStringFormat.init(inst, def);
2743
- });
2744
- const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => {
2745
- // ZodStringFormat.init(inst, def);
2746
- $ZodUUID.init(inst, def);
2747
- ZodStringFormat.init(inst, def);
2748
- });
2749
- const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => {
2750
- // ZodStringFormat.init(inst, def);
2751
- $ZodURL.init(inst, def);
2752
- ZodStringFormat.init(inst, def);
2753
- });
2754
- const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => {
2755
- // ZodStringFormat.init(inst, def);
2756
- $ZodEmoji.init(inst, def);
2757
- ZodStringFormat.init(inst, def);
2758
- });
2759
- const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => {
2760
- // ZodStringFormat.init(inst, def);
2761
- $ZodNanoID.init(inst, def);
2762
- ZodStringFormat.init(inst, def);
2763
- });
2764
- const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => {
2765
- // ZodStringFormat.init(inst, def);
2766
- $ZodCUID.init(inst, def);
2767
- ZodStringFormat.init(inst, def);
2768
- });
2769
- const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => {
2770
- // ZodStringFormat.init(inst, def);
2771
- $ZodCUID2.init(inst, def);
2772
- ZodStringFormat.init(inst, def);
2773
- });
2774
- const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => {
2775
- // ZodStringFormat.init(inst, def);
2776
- $ZodULID.init(inst, def);
2777
- ZodStringFormat.init(inst, def);
2778
- });
2779
- const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => {
2780
- // ZodStringFormat.init(inst, def);
2781
- $ZodXID.init(inst, def);
2782
- ZodStringFormat.init(inst, def);
2783
- });
2784
- const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => {
2785
- // ZodStringFormat.init(inst, def);
2786
- $ZodKSUID.init(inst, def);
2787
- ZodStringFormat.init(inst, def);
2788
- });
2789
- const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => {
2790
- // ZodStringFormat.init(inst, def);
2791
- $ZodIPv4.init(inst, def);
2792
- ZodStringFormat.init(inst, def);
2793
- });
2794
- const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => {
2795
- // ZodStringFormat.init(inst, def);
2796
- $ZodIPv6.init(inst, def);
2797
- ZodStringFormat.init(inst, def);
2798
- });
2799
- const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => {
2800
- $ZodCIDRv4.init(inst, def);
2801
- ZodStringFormat.init(inst, def);
2802
- });
2803
- const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => {
2804
- $ZodCIDRv6.init(inst, def);
2805
- ZodStringFormat.init(inst, def);
2806
- });
2807
- const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => {
2808
- // ZodStringFormat.init(inst, def);
2809
- $ZodBase64.init(inst, def);
2810
- ZodStringFormat.init(inst, def);
2811
- });
2812
- const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => {
2813
- // ZodStringFormat.init(inst, def);
2814
- $ZodBase64URL.init(inst, def);
2815
- ZodStringFormat.init(inst, def);
2816
- });
2817
- const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => {
2818
- // ZodStringFormat.init(inst, def);
2819
- $ZodE164.init(inst, def);
2820
- ZodStringFormat.init(inst, def);
2821
- });
2822
- const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => {
2823
- // ZodStringFormat.init(inst, def);
2824
- $ZodJWT.init(inst, def);
2825
- ZodStringFormat.init(inst, def);
2826
- });
2827
- const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => {
2828
- $ZodUnknown.init(inst, def);
2829
- ZodType.init(inst, def);
2830
- });
2831
- function unknown() {
2832
- return _unknown(ZodUnknown);
2833
- }
2834
- const ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => {
2835
- $ZodNever.init(inst, def);
2836
- ZodType.init(inst, def);
2837
- });
2838
- function never(params) {
2839
- return _never(ZodNever, params);
2840
- }
2841
- const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => {
2842
- $ZodArray.init(inst, def);
2843
- ZodType.init(inst, def);
2844
- inst.element = def.element;
2845
- inst.min = (minLength, params) => inst.check(_minLength(minLength, params));
2846
- inst.nonempty = (params) => inst.check(_minLength(1, params));
2847
- inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params));
2848
- inst.length = (len, params) => inst.check(_length(len, params));
2849
- inst.unwrap = () => inst.element;
2850
- });
2851
- function array(element, params) {
2852
- return _array(ZodArray, element, params);
2853
- }
2854
- const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => {
2855
- $ZodObject.init(inst, def);
2856
- ZodType.init(inst, def);
2857
- defineLazy(inst, "shape", () => def.shape);
2858
- inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
2859
- inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall });
2860
- inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
2861
- inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
2862
- inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });
2863
- inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined });
2864
- inst.extend = (incoming) => {
2865
- return extend(inst, incoming);
2866
- };
2867
- inst.merge = (other) => merge(inst, other);
2868
- inst.pick = (mask) => pick(inst, mask);
2869
- inst.omit = (mask) => omit(inst, mask);
2870
- inst.partial = (...args) => partial(ZodOptional, inst, args[0]);
2871
- inst.required = (...args) => required(ZodNonOptional, inst, args[0]);
2872
- });
2873
- function object(shape, params) {
2874
- const def = {
2875
- type: "object",
2876
- get shape() {
2877
- assignProp(this, "shape", shape ? objectClone(shape) : {});
2878
- return this.shape;
2879
- },
2880
- ...normalizeParams(params),
2881
- };
2882
- return new ZodObject(def);
2883
- }
2884
- const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => {
2885
- $ZodUnion.init(inst, def);
2886
- ZodType.init(inst, def);
2887
- inst.options = def.options;
2888
- });
2889
- function union(options, params) {
2890
- return new ZodUnion({
2891
- type: "union",
2892
- options: options,
2893
- ...normalizeParams(params),
2894
- });
2895
- }
2896
- const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => {
2897
- $ZodIntersection.init(inst, def);
2898
- ZodType.init(inst, def);
2899
- });
2900
- function intersection(left, right) {
2901
- return new ZodIntersection({
2902
- type: "intersection",
2903
- left: left,
2904
- right: right,
2905
- });
2906
- }
2907
- const ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => {
2908
- $ZodRecord.init(inst, def);
2909
- ZodType.init(inst, def);
2910
- inst.keyType = def.keyType;
2911
- inst.valueType = def.valueType;
2912
- });
2913
- function record(keyType, valueType, params) {
2914
- return new ZodRecord({
2915
- type: "record",
2916
- keyType,
2917
- valueType: valueType,
2918
- ...normalizeParams(params),
2919
- });
2920
- }
2921
- const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => {
2922
- $ZodEnum.init(inst, def);
2923
- ZodType.init(inst, def);
2924
- inst.enum = def.entries;
2925
- inst.options = Object.values(def.entries);
2926
- const keys = new Set(Object.keys(def.entries));
2927
- inst.extract = (values, params) => {
2928
- const newEntries = {};
2929
- for (const value of values) {
2930
- if (keys.has(value)) {
2931
- newEntries[value] = def.entries[value];
2932
- }
2933
- else
2934
- throw new Error(`Key ${value} not found in enum`);
2935
- }
2936
- return new ZodEnum({
2937
- ...def,
2938
- checks: [],
2939
- ...normalizeParams(params),
2940
- entries: newEntries,
2941
- });
2942
- };
2943
- inst.exclude = (values, params) => {
2944
- const newEntries = { ...def.entries };
2945
- for (const value of values) {
2946
- if (keys.has(value)) {
2947
- delete newEntries[value];
2948
- }
2949
- else
2950
- throw new Error(`Key ${value} not found in enum`);
2951
- }
2952
- return new ZodEnum({
2953
- ...def,
2954
- checks: [],
2955
- ...normalizeParams(params),
2956
- entries: newEntries,
2957
- });
2958
- };
2959
- });
2960
- function _enum(values, params) {
2961
- const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
2962
- return new ZodEnum({
2963
- type: "enum",
2964
- entries,
2965
- ...normalizeParams(params),
2966
- });
2967
- }
2968
- const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => {
2969
- $ZodTransform.init(inst, def);
2970
- ZodType.init(inst, def);
2971
- inst._zod.parse = (payload, _ctx) => {
2972
- payload.addIssue = (issue$1) => {
2973
- if (typeof issue$1 === "string") {
2974
- payload.issues.push(issue(issue$1, payload.value, def));
2975
- }
2976
- else {
2977
- // for Zod 3 backwards compatibility
2978
- const _issue = issue$1;
2979
- if (_issue.fatal)
2980
- _issue.continue = false;
2981
- _issue.code ?? (_issue.code = "custom");
2982
- _issue.input ?? (_issue.input = payload.value);
2983
- _issue.inst ?? (_issue.inst = inst);
2984
- // _issue.continue ??= true;
2985
- payload.issues.push(issue(_issue));
2986
- }
2987
- };
2988
- const output = def.transform(payload.value, payload);
2989
- if (output instanceof Promise) {
2990
- return output.then((output) => {
2991
- payload.value = output;
2992
- return payload;
2993
- });
2994
- }
2995
- payload.value = output;
2996
- return payload;
2997
- };
2998
- });
2999
- function transform(fn) {
3000
- return new ZodTransform({
3001
- type: "transform",
3002
- transform: fn,
3003
- });
3004
- }
3005
- const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => {
3006
- $ZodOptional.init(inst, def);
3007
- ZodType.init(inst, def);
3008
- inst.unwrap = () => inst._zod.def.innerType;
3009
- });
3010
- function optional(innerType) {
3011
- return new ZodOptional({
3012
- type: "optional",
3013
- innerType: innerType,
3014
- });
3015
- }
3016
- const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => {
3017
- $ZodNullable.init(inst, def);
3018
- ZodType.init(inst, def);
3019
- inst.unwrap = () => inst._zod.def.innerType;
3020
- });
3021
- function nullable(innerType) {
3022
- return new ZodNullable({
3023
- type: "nullable",
3024
- innerType: innerType,
3025
- });
3026
- }
3027
- const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => {
3028
- $ZodDefault.init(inst, def);
3029
- ZodType.init(inst, def);
3030
- inst.unwrap = () => inst._zod.def.innerType;
3031
- inst.removeDefault = inst.unwrap;
3032
- });
3033
- function _default(innerType, defaultValue) {
3034
- return new ZodDefault({
3035
- type: "default",
3036
- innerType: innerType,
3037
- get defaultValue() {
3038
- return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
3039
- },
3040
- });
3041
- }
3042
- const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => {
3043
- $ZodPrefault.init(inst, def);
3044
- ZodType.init(inst, def);
3045
- inst.unwrap = () => inst._zod.def.innerType;
3046
- });
3047
- function prefault(innerType, defaultValue) {
3048
- return new ZodPrefault({
3049
- type: "prefault",
3050
- innerType: innerType,
3051
- get defaultValue() {
3052
- return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
3053
- },
3054
- });
3055
- }
3056
- const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => {
3057
- $ZodNonOptional.init(inst, def);
3058
- ZodType.init(inst, def);
3059
- inst.unwrap = () => inst._zod.def.innerType;
3060
- });
3061
- function nonoptional(innerType, params) {
3062
- return new ZodNonOptional({
3063
- type: "nonoptional",
3064
- innerType: innerType,
3065
- ...normalizeParams(params),
3066
- });
3067
- }
3068
- const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => {
3069
- $ZodCatch.init(inst, def);
3070
- ZodType.init(inst, def);
3071
- inst.unwrap = () => inst._zod.def.innerType;
3072
- inst.removeCatch = inst.unwrap;
3073
- });
3074
- function _catch(innerType, catchValue) {
3075
- return new ZodCatch({
3076
- type: "catch",
3077
- innerType: innerType,
3078
- catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue),
3079
- });
3080
- }
3081
- const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => {
3082
- $ZodPipe.init(inst, def);
3083
- ZodType.init(inst, def);
3084
- inst.in = def.in;
3085
- inst.out = def.out;
3086
- });
3087
- function pipe(in_, out) {
3088
- return new ZodPipe({
3089
- type: "pipe",
3090
- in: in_,
3091
- out: out,
3092
- // ...util.normalizeParams(params),
3093
- });
3094
- }
3095
- const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => {
3096
- $ZodReadonly.init(inst, def);
3097
- ZodType.init(inst, def);
3098
- inst.unwrap = () => inst._zod.def.innerType;
3099
- });
3100
- function readonly(innerType) {
3101
- return new ZodReadonly({
3102
- type: "readonly",
3103
- innerType: innerType,
3104
- });
3105
- }
3106
- const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => {
3107
- $ZodCustom.init(inst, def);
3108
- ZodType.init(inst, def);
3109
- });
3110
- function refine(fn, _params = {}) {
3111
- return _refine(ZodCustom, fn, _params);
3112
- }
3113
- // superRefine
3114
- function superRefine(fn) {
3115
- return _superRefine(fn);
3116
- }
3117
- function _instanceof(cls, params = {
3118
- error: `Input not instance of ${cls.name}`,
3119
- }) {
3120
- const inst = new ZodCustom({
3121
- type: "custom",
3122
- check: "custom",
3123
- fn: (data) => data instanceof cls,
3124
- abort: true,
3125
- ...normalizeParams(params),
3126
- });
3127
- inst._zod.bag.Class = cls;
3128
- return inst;
3129
- }
3130
-
3131
- const IMAGE_ALIAS_KEY_REGEX = /^@[A-Za-z0-9_-]*$/;
3132
- const IMAGE_ALIAS_VALUE_REGEX = /^(?!\/|[A-Za-z]:[\\\/])(?!.*:\/\/).*$/;
3133
- const ImageAliasValue = string().nonempty("Image alias value cannot be empty").regex(
3134
- IMAGE_ALIAS_VALUE_REGEX,
3135
- "Image alias value must be a relative path (no leading slash or protocol)"
3136
- );
3137
- const ImageAliasesSchema = record(
3138
- string(),
3139
- // PLAIN key schema - valibot JSON schema export-safe.
3140
- ImageAliasValue
3141
- ).meta({
3142
- description: "Map of image alias prefixes to relative paths (keys must match /^@\\w+$/; values must be relative paths without protocol or leading slash)."
3143
- });
3144
- function validateImageAliases(imageAliases) {
3145
- const invalidKeys = [];
3146
- const invalidValues = [];
3147
- if (imageAliases) {
3148
- for (const [key, value] of Object.entries(imageAliases)) {
3149
- if (!IMAGE_ALIAS_KEY_REGEX.test(key)) {
3150
- invalidKeys.push(key);
3151
- }
3152
- if (!IMAGE_ALIAS_VALUE_REGEX.test(value)) {
3153
- invalidValues.push(`${key} -> ${value}`);
3154
- }
3155
- }
3156
- }
3157
- if (invalidKeys.length || invalidValues.length) {
3158
- const parts = [];
3159
- if (invalidKeys.length) {
3160
- parts.push(
3161
- `Invalid image alias key(s): ${invalidKeys.map((k) => JSON.stringify(k)).join(", ")} (must match ${IMAGE_ALIAS_KEY_REGEX})`
3162
- );
3163
- }
3164
- if (invalidValues.length) {
3165
- parts.push(
3166
- `Invalid image alias value(s): ${invalidValues.map((kv) => JSON.stringify(kv)).join(", ")} (must match ${IMAGE_ALIAS_VALUE_REGEX})`
3167
- );
3168
- }
3169
- throw new Error(parts.join(" | "));
3170
- }
3171
- }
3172
-
3173
- const LikeC4ProjectJsonConfigSchema = object({
3174
- name: string().nonempty("Project name cannot be empty").refine((value) => value !== "default", {
3175
- abort: true,
3176
- error: 'Project name cannot be "default"'
3177
- }).refine((value) => !value.includes(".") && !value.includes("@") && !value.includes("#"), {
3178
- abort: true,
3179
- error: 'Project name cannot contain ".", "@" or "#", try to use A-z, 0-9, _ and -'
3180
- }).transform((value) => value).meta({ description: "Project name, must be unique in the workspace" }),
3181
- title: string().nonempty("Project title cannot be empty if specified").optional().meta({ description: "A human readable title for the project" }),
3182
- contactPerson: string().nonempty("Contact person cannot be empty if specified").optional().meta({ description: "A person who has been involved in creating or maintaining this project" }),
3183
- imageAliases: ImageAliasesSchema.optional(),
3184
- exclude: array(string()).optional().meta({ description: 'List of file patterns to exclude from the project, default is ["**/node_modules/**"]' })
3185
- }).meta({
3186
- description: "LikeC4 project configuration"
3187
- });
3188
- const FunctionType = _instanceof(Function);
3189
- const GeneratorsSchema = record(string(), FunctionType);
3190
- const LikeC4ProjectConfigSchema = LikeC4ProjectJsonConfigSchema.extend({
3191
- generators: GeneratorsSchema.optional()
3192
- });
3193
- function validateProjectConfig(config) {
3194
- const parsed = LikeC4ProjectConfigSchema.safeParse(
3195
- typeof config === "string" ? JSON5.parse(config) : config
3196
- );
3197
- if (!parsed.success) {
3198
- throw new Error("Config validation failed:\n" + prettifyError(parsed.error));
3199
- }
3200
- if (parsed.data.imageAliases) {
3201
- validateImageAliases(parsed.data.imageAliases);
3202
- }
3203
- return parsed.data;
3204
- }
3205
- function serializableLikeC4ProjectConfig({ generators, ...config }) {
3206
- return LikeC4ProjectJsonConfigSchema.parse(config);
3207
- }
3208
-
3209
- const configJsonFilenames = [
3210
- ".likec4rc",
3211
- ".likec4.config.json",
3212
- "likec4.config.json"
3213
- ];
3214
- const configNonJsonFilenames = [
3215
- "likec4.config.js",
3216
- "likec4.config.mjs",
3217
- "likec4.config.ts",
3218
- "likec4.config.mts"
3219
- ];
3220
- const ConfigFilenames = [
3221
- ...configJsonFilenames,
3222
- ...configNonJsonFilenames
3223
- ];
3224
- function isLikeC4JsonConfig(filename) {
3225
- for (const ext of configJsonFilenames) {
3226
- if (filename.endsWith(ext)) {
3227
- return true;
3228
- }
3229
- }
3230
- return false;
3231
- }
3232
- function isLikeC4NonJsonConfig(filename) {
3233
- for (const ext of configNonJsonFilenames) {
3234
- if (filename.endsWith(ext)) {
3235
- return true;
3236
- }
3237
- }
3238
- return false;
3239
- }
3240
- function isLikeC4Config(filename) {
3241
- return isLikeC4JsonConfig(filename) || isLikeC4NonJsonConfig(filename);
3242
- }
3243
-
3244
- function defineConfig(config) {
3245
- return LikeC4ProjectConfigSchema.parse(config);
3246
- }
3247
- function defineGenerators(generators) {
3248
- return GeneratorsSchema.parse(generators);
3249
- }
3250
-
3251
- export { ConfigFilenames as C, isLikeC4JsonConfig as a, isLikeC4NonJsonConfig as b, defineGenerators as c, defineConfig as d, isLikeC4Config as i, serializableLikeC4ProjectConfig as s, validateProjectConfig as v };