@rexeus/typeweaver 0.8.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -6,4307 +6,307 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
8
  var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
- key = keys[i];
12
- if (!__hasOwnProp.call(to, key) && key !== except) {
13
- __defProp(to, key, {
14
- get: ((k) => from[k]).bind(null, key),
15
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
- });
17
- }
18
- }
19
- }
20
- return to;
21
- };
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
- value: mod,
24
- enumerable: true
25
- }) : target, mod));
26
-
27
- //#endregion
28
- let node_fs = require("node:fs");
29
- node_fs = __toESM(node_fs);
30
- let node_path = require("node:path");
31
- node_path = __toESM(node_path);
32
- let node_url = require("node:url");
33
- let commander = require("commander");
34
- let _rexeus_typeweaver_gen = require("@rexeus/typeweaver-gen");
35
- let _rexeus_typeweaver_types = require("@rexeus/typeweaver-types");
36
- _rexeus_typeweaver_types = __toESM(_rexeus_typeweaver_types);
37
- let oxc_transform = require("oxc-transform");
38
- let ejs = require("ejs");
39
- let _rexeus_typeweaver_core = require("@rexeus/typeweaver-core");
40
-
41
- //#region src/generators/errors/DefinitionCompilationError.ts
42
- var DefinitionCompilationError = class extends Error {
43
- constructor(filePath, details) {
44
- super(`Failed to compile definition at \`${filePath}\`. ${details}`);
45
- this.filePath = filePath;
46
- this.details = details;
47
- }
48
- };
49
-
50
- //#endregion
51
- //#region src/generators/DefinitionCompiler.ts
52
- /**
53
- * Compiles TypeScript definition files to JavaScript + declaration stubs.
54
- *
55
- * Definition files contain Zod schemas that cause tsc to exhaust memory
56
- * when type-checking due to Zod v4's deeply recursive type inference.
57
- * By pre-compiling definitions to .js + .d.ts, tsc only sees lightweight
58
- * type stubs (everything typed as `any`) while runtime behavior is preserved.
59
- */
60
- var DefinitionCompiler = class DefinitionCompiler {
61
- static GENERATED_HEADER = [
62
- "/* eslint-disable */",
63
- "/**",
64
- " * This file was automatically generated by typeweaver.",
65
- " * DO NOT EDIT. Instead, modify the source definition file and generate again.",
66
- " *",
67
- " * @generated by @rexeus/typeweaver",
68
- " */"
69
- ].join("\n");
70
- /**
71
- * Compiles all .ts definition files in-place to .js + .d.ts stubs.
72
- * The original .ts files are removed after compilation.
73
- */
74
- compileInPlace(definitionDir) {
75
- const errors = [];
76
- this.processDirectory(definitionDir, errors);
77
- if (errors.length > 0) {
78
- const summary = errors.map((e) => ` - ${e.filePath}: ${e.details}`).join("\n");
79
- throw new DefinitionCompilationError(definitionDir, `${errors.length} file(s) failed to compile:\n${summary}`);
80
- }
81
- }
82
- processDirectory(dir, errors) {
83
- const entries = node_fs.default.readdirSync(dir, { withFileTypes: true });
84
- for (const entry of entries) {
85
- const fullPath = node_path.default.join(dir, entry.name);
86
- if (entry.isDirectory()) {
87
- this.processDirectory(fullPath, errors);
88
- continue;
89
- }
90
- if (entry.isFile() && entry.name.endsWith(".ts") && !entry.name.endsWith(".d.ts")) try {
91
- this.compileFile(fullPath, dir, entry.name);
92
- } catch (error) {
93
- errors.push(error instanceof DefinitionCompilationError ? error : new DefinitionCompilationError(fullPath, String(error)));
94
- }
95
- }
96
- }
97
- compileFile(srcPath, dir, fileName) {
98
- try {
99
- const source = node_fs.default.readFileSync(srcPath, "utf-8");
100
- const baseName = fileName.replace(/\.ts$/, "");
101
- const jsCode = this.transpileToJs(fileName, source);
102
- const dtsCode = this.generateDtsStub(source);
103
- node_fs.default.writeFileSync(node_path.default.join(dir, `${baseName}.js`), jsCode);
104
- node_fs.default.writeFileSync(node_path.default.join(dir, `${baseName}.d.ts`), dtsCode);
105
- node_fs.default.unlinkSync(srcPath);
106
- } catch (error) {
107
- throw new DefinitionCompilationError(srcPath, error instanceof DefinitionCompilationError ? error.details : error instanceof Error ? error.message : String(error));
108
- }
109
- }
110
- transpileToJs(fileName, source) {
111
- const result = (0, oxc_transform.transformSync)(fileName, source, {
112
- lang: "ts",
113
- sourceType: "module"
114
- });
115
- const errors = result.errors.filter((e) => e.severity === "Error");
116
- if (errors.length > 0) throw new DefinitionCompilationError(fileName, errors.map((e) => e.message).join("; "));
117
- return result.code;
118
- }
119
- /**
120
- * Generates a minimal .d.ts stub from TypeScript source.
121
- * All value exports are typed as `any` to avoid pulling in Zod's type system.
122
- * Re-exports are preserved so barrel files chain correctly.
123
- */
124
- generateDtsStub(source) {
125
- if (source.startsWith(DefinitionCompiler.GENERATED_HEADER)) return source;
126
- const lines = [DefinitionCompiler.GENERATED_HEADER];
127
- let hasDefaultExport = false;
128
- let pastLeadingComments = false;
129
- let exportBlock = null;
130
- for (const line of source.split("\n")) {
131
- const trimmed = line.trim();
132
- if (exportBlock !== null) {
133
- exportBlock += " " + trimmed;
134
- if (trimmed.includes("}")) {
135
- lines.push(exportBlock);
136
- exportBlock = null;
137
- }
138
- continue;
139
- }
140
- if (!pastLeadingComments) {
141
- if (trimmed.startsWith("/*") || trimmed.startsWith("//") || trimmed.startsWith("*") || trimmed === "") {
142
- if (trimmed !== "" && !trimmed.includes("@generated")) lines.push(trimmed);
143
- continue;
144
- }
145
- pastLeadingComments = true;
146
- }
147
- if (trimmed.startsWith("export {") || trimmed.startsWith("export *")) {
148
- if (trimmed.startsWith("export {") && !trimmed.includes("}")) {
149
- exportBlock = trimmed;
150
- continue;
151
- }
152
- lines.push(trimmed);
153
- continue;
154
- }
155
- if (trimmed.startsWith("export default") && !hasDefaultExport) {
156
- lines.push("declare const _default: any;");
157
- lines.push("export default _default;");
158
- hasDefaultExport = true;
159
- continue;
160
- }
161
- const constMatch = trimmed.match(/^export\s+(?:const|let|var)\s+(\w+)/);
162
- if (constMatch) {
163
- lines.push(`export declare const ${constMatch[1]}: any;`);
164
- continue;
165
- }
166
- const funcMatch = trimmed.match(/^export\s+(?:async\s+)?function\s*\*?\s+(\w+)/);
167
- if (funcMatch) {
168
- lines.push(`export declare function ${funcMatch[1]}(...args: any[]): any;`);
169
- continue;
170
- }
171
- if (trimmed.startsWith("export") && !trimmed.startsWith("export {") && !trimmed.startsWith("export *") && !trimmed.startsWith("export default") && !trimmed.startsWith("export type")) console.warn(`[DefinitionCompiler] Unrecognized export pattern in definition stub: ${trimmed}`);
172
- }
173
- return lines.join("\n") + "\n";
174
- }
175
- };
176
-
177
- //#endregion
178
- //#region src/generators/Formatter.ts
179
- var Formatter = class {
180
- constructor(outputDir) {
181
- this.outputDir = outputDir;
182
- }
183
- async formatCode(startDir) {
184
- const format = await this.loadFormatter();
185
- if (!format) return;
186
- const targetDir = startDir ?? this.outputDir;
187
- await this.formatDirectory(targetDir, format);
188
- }
189
- async loadFormatter() {
190
- try {
191
- return (await import("oxfmt")).format;
192
- } catch {
193
- console.warn("oxfmt not installed - skipping formatting. Install with: npm install -D oxfmt");
194
- return;
195
- }
196
- }
197
- async formatDirectory(targetDir, format) {
198
- const contents = node_fs.default.readdirSync(targetDir, { withFileTypes: true });
199
- for (const content of contents) if (content.isFile()) {
200
- const filePath = node_path.default.join(targetDir, content.name);
201
- const { code } = await format(filePath, node_fs.default.readFileSync(filePath, "utf8"));
202
- node_fs.default.writeFileSync(filePath, code);
203
- } else if (content.isDirectory()) await this.formatDirectory(node_path.default.join(targetDir, content.name), format);
204
- }
205
- };
206
-
207
- //#endregion
208
- //#region src/generators/IndexFileGenerator.ts
209
- var IndexFileGenerator = class {
210
- constructor(templateDir) {
211
- this.templateDir = templateDir;
212
- }
213
- generate(context) {
214
- const templateFilePath = node_path.default.join(this.templateDir, "Index.ejs");
215
- const template = node_fs.default.readFileSync(templateFilePath, "utf8");
216
- const generatedFiles = context.getGeneratedFiles();
217
- const groups = /* @__PURE__ */ new Map();
218
- const rootFiles = /* @__PURE__ */ new Set();
219
- const existingBarrels = /* @__PURE__ */ new Set();
220
- for (const file of generatedFiles) {
221
- const stripped = file.replace(/\.ts$/, "");
222
- const firstSlash = stripped.indexOf("/");
223
- if (firstSlash === -1) {
224
- rootFiles.add(`./${stripped}`);
225
- continue;
226
- }
227
- const firstSegment = stripped.slice(0, firstSlash);
228
- if (firstSegment === "lib") {
229
- const secondSlash = stripped.indexOf("/", firstSlash + 1);
230
- const groupKey = secondSlash === -1 ? stripped : stripped.slice(0, secondSlash);
231
- const entryName = stripped.slice(groupKey.length + 1);
232
- if (entryName === "index") existingBarrels.add(groupKey);
233
- else {
234
- if (!groups.has(groupKey)) groups.set(groupKey, /* @__PURE__ */ new Set());
235
- groups.get(groupKey).add(`./${entryName}`);
236
- }
237
- } else {
238
- const entryName = stripped.slice(firstSlash + 1);
239
- if (entryName === "index") existingBarrels.add(firstSegment);
240
- else {
241
- if (!groups.has(firstSegment)) groups.set(firstSegment, /* @__PURE__ */ new Set());
242
- groups.get(firstSegment).add(`./${entryName}`);
243
- }
244
- }
245
- }
246
- for (const [groupKey, entries] of groups) {
247
- if (existingBarrels.has(groupKey)) continue;
248
- const domainBarrelContent = (0, ejs.render)(template, { indexPaths: Array.from(entries).sort() });
249
- const domainIndexPath = node_path.default.join(context.outputDir, groupKey, "index.ts");
250
- node_fs.default.mkdirSync(node_path.default.dirname(domainIndexPath), { recursive: true });
251
- node_fs.default.writeFileSync(domainIndexPath, domainBarrelContent);
252
- }
253
- const rootIndexPaths = new Set(rootFiles);
254
- for (const groupKey of groups.keys()) rootIndexPaths.add(`./${groupKey}`);
255
- for (const barrelKey of existingBarrels) rootIndexPaths.add(`./${barrelKey}`);
256
- const rootContent = (0, ejs.render)(template, { indexPaths: Array.from(rootIndexPaths).sort() });
257
- node_fs.default.writeFileSync(node_path.default.join(context.outputDir, "index.ts"), rootContent);
258
- }
259
- };
260
-
261
- //#endregion
262
- //#region src/generators/errors/PluginLoadingFailure.ts
263
- var PluginLoadingFailure = class PluginLoadingFailure extends Error {
264
- constructor(pluginName, attempts) {
265
- super(`Failed to load plugin '${pluginName}'`);
266
- this.pluginName = pluginName;
267
- this.attempts = attempts;
268
- Object.setPrototypeOf(this, PluginLoadingFailure.prototype);
269
- }
270
- };
271
-
272
- //#endregion
273
- //#region src/generators/PluginLoader.ts
274
- /**
275
- * Handles plugin discovery and loading for typeweaver
276
- */
277
- var PluginLoader = class {
278
- constructor(registry, requiredPlugins, strategies = ["npm", "local"]) {
279
- this.registry = registry;
280
- this.requiredPlugins = requiredPlugins;
281
- this.strategies = strategies;
282
- }
283
- /**
284
- * Load all plugins from configuration
285
- */
286
- async loadPlugins(config) {
287
- for (const requiredPlugin of this.requiredPlugins) this.registry.register(requiredPlugin);
288
- if (!config?.plugins) return;
289
- const successful = [];
290
- for (const plugin of config.plugins) {
291
- let result;
292
- if (typeof plugin === "string") result = await this.loadPlugin(plugin);
293
- else result = await this.loadPlugin(plugin[0]);
294
- if (result.success === false) throw new PluginLoadingFailure(result.error.pluginName, result.error.attempts);
295
- successful.push(result.value);
296
- this.registry.register(result.value.plugin);
297
- }
298
- this.reportSuccessfulLoads(successful);
299
- }
300
- /**
301
- * Load a plugin from a string identifier
302
- */
303
- async loadPlugin(pluginName) {
304
- const possiblePaths = this.generatePluginPaths(pluginName);
305
- const attempts = [];
306
- for (const possiblePath of possiblePaths) try {
307
- const pluginPackage = await import(possiblePath);
308
- if (pluginPackage.default) return {
309
- success: true,
310
- value: {
311
- plugin: new pluginPackage.default(),
312
- source: possiblePath
313
- }
314
- };
315
- attempts.push({
316
- path: possiblePath,
317
- error: "No default export found"
318
- });
319
- } catch (error) {
320
- attempts.push({
321
- path: possiblePath,
322
- error: error instanceof Error ? error.message : String(error)
323
- });
324
- }
325
- return {
326
- success: false,
327
- error: {
328
- pluginName,
329
- attempts
330
- }
331
- };
332
- }
333
- /**
334
- * Generate possible plugin paths based on configured strategies
335
- */
336
- generatePluginPaths(pluginName) {
337
- const paths = [];
338
- for (const strategy of this.strategies) switch (strategy) {
339
- case "npm":
340
- paths.push(`@rexeus/typeweaver-${pluginName}`);
341
- paths.push(`@rexeus/${pluginName}`);
342
- break;
343
- case "local":
344
- paths.push(pluginName);
345
- break;
346
- }
347
- return paths;
348
- }
349
- /**
350
- * Report successful plugin loads
351
- */
352
- reportSuccessfulLoads(successful) {
353
- if (successful.length > 0) {
354
- console.info(`Successfully loaded ${successful.length} plugin(s):`);
355
- for (const result of successful) console.info(` - ${result.plugin.name} (from ${result.source})`);
356
- }
357
- }
358
- };
359
-
360
- //#endregion
361
- //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js
362
- /** A special constant with type `never` */
363
- const NEVER = Object.freeze({ status: "aborted" });
364
- function $constructor(name, initializer, params) {
365
- function init(inst, def) {
366
- if (!inst._zod) Object.defineProperty(inst, "_zod", {
367
- value: {
368
- def,
369
- constr: _,
370
- traits: /* @__PURE__ */ new Set()
371
- },
372
- enumerable: false
373
- });
374
- if (inst._zod.traits.has(name)) return;
375
- inst._zod.traits.add(name);
376
- initializer(inst, def);
377
- const proto = _.prototype;
378
- const keys = Object.keys(proto);
379
- for (let i = 0; i < keys.length; i++) {
380
- const k = keys[i];
381
- if (!(k in inst)) inst[k] = proto[k].bind(inst);
382
- }
383
- }
384
- const Parent = params?.Parent ?? Object;
385
- class Definition extends Parent {}
386
- Object.defineProperty(Definition, "name", { value: name });
387
- function _(def) {
388
- var _a;
389
- const inst = params?.Parent ? new Definition() : this;
390
- init(inst, def);
391
- (_a = inst._zod).deferred ?? (_a.deferred = []);
392
- for (const fn of inst._zod.deferred) fn();
393
- return inst;
394
- }
395
- Object.defineProperty(_, "init", { value: init });
396
- Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => {
397
- if (params?.Parent && inst instanceof params.Parent) return true;
398
- return inst?._zod?.traits?.has(name);
399
- } });
400
- Object.defineProperty(_, "name", { value: name });
401
- return _;
402
- }
403
- var $ZodAsyncError = class extends Error {
404
- constructor() {
405
- super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
406
- }
407
- };
408
- var $ZodEncodeError = class extends Error {
409
- constructor(name) {
410
- super(`Encountered unidirectional transform during encode: ${name}`);
411
- this.name = "ZodEncodeError";
412
- }
413
- };
414
- const globalConfig = {};
415
- function config(newConfig) {
416
- if (newConfig) Object.assign(globalConfig, newConfig);
417
- return globalConfig;
418
- }
419
-
420
- //#endregion
421
- //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js
422
- function getEnumValues(entries) {
423
- const numericValues = Object.values(entries).filter((v) => typeof v === "number");
424
- return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
425
- }
426
- function jsonStringifyReplacer(_, value) {
427
- if (typeof value === "bigint") return value.toString();
428
- return value;
429
- }
430
- function cached(getter) {
431
- return { get value() {
432
- {
433
- const value = getter();
434
- Object.defineProperty(this, "value", { value });
435
- return value;
436
- }
437
- throw new Error("cached value already set");
438
- } };
439
- }
440
- function nullish(input) {
441
- return input === null || input === void 0;
442
- }
443
- function cleanRegex(source) {
444
- const start = source.startsWith("^") ? 1 : 0;
445
- const end = source.endsWith("$") ? source.length - 1 : source.length;
446
- return source.slice(start, end);
447
- }
448
- const EVALUATING = Symbol("evaluating");
449
- function defineLazy(object, key, getter) {
450
- let value = void 0;
451
- Object.defineProperty(object, key, {
452
- get() {
453
- if (value === EVALUATING) return;
454
- if (value === void 0) {
455
- value = EVALUATING;
456
- value = getter();
457
- }
458
- return value;
459
- },
460
- set(v) {
461
- Object.defineProperty(object, key, { value: v });
462
- },
463
- configurable: true
464
- });
465
- }
466
- function assignProp(target, prop, value) {
467
- Object.defineProperty(target, prop, {
468
- value,
469
- writable: true,
470
- enumerable: true,
471
- configurable: true
472
- });
473
- }
474
- function mergeDefs(...defs) {
475
- const mergedDescriptors = {};
476
- for (const def of defs) {
477
- const descriptors = Object.getOwnPropertyDescriptors(def);
478
- Object.assign(mergedDescriptors, descriptors);
479
- }
480
- return Object.defineProperties({}, mergedDescriptors);
481
- }
482
- function esc(str) {
483
- return JSON.stringify(str);
484
- }
485
- function slugify(input) {
486
- return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
487
- }
488
- const captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
489
- function isObject(data) {
490
- return typeof data === "object" && data !== null && !Array.isArray(data);
491
- }
492
- const allowsEval = cached(() => {
493
- if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) return false;
494
- try {
495
- new Function("");
496
- return true;
497
- } catch (_) {
498
- return false;
499
- }
500
- });
501
- function isPlainObject(o) {
502
- if (isObject(o) === false) return false;
503
- const ctor = o.constructor;
504
- if (ctor === void 0) return true;
505
- if (typeof ctor !== "function") return true;
506
- const prot = ctor.prototype;
507
- if (isObject(prot) === false) return false;
508
- if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false;
509
- return true;
510
- }
511
- function shallowClone(o) {
512
- if (isPlainObject(o)) return { ...o };
513
- if (Array.isArray(o)) return [...o];
514
- return o;
515
- }
516
- const propertyKeyTypes = new Set([
517
- "string",
518
- "number",
519
- "symbol"
520
- ]);
521
- function escapeRegex(str) {
522
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
523
- }
524
- function clone(inst, def, params) {
525
- const cl = new inst._zod.constr(def ?? inst._zod.def);
526
- if (!def || params?.parent) cl._zod.parent = inst;
527
- return cl;
528
- }
529
- function normalizeParams(_params) {
530
- const params = _params;
531
- if (!params) return {};
532
- if (typeof params === "string") return { error: () => params };
533
- if (params?.message !== void 0) {
534
- if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params");
535
- params.error = params.message;
536
- }
537
- delete params.message;
538
- if (typeof params.error === "string") return {
539
- ...params,
540
- error: () => params.error
541
- };
542
- return params;
543
- }
544
- function optionalKeys(shape) {
545
- return Object.keys(shape).filter((k) => {
546
- return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
547
- });
548
- }
549
- const NUMBER_FORMAT_RANGES = {
550
- safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
551
- int32: [-2147483648, 2147483647],
552
- uint32: [0, 4294967295],
553
- float32: [-34028234663852886e22, 34028234663852886e22],
554
- float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
555
- };
556
- function pick(schema, mask) {
557
- const currDef = schema._zod.def;
558
- const checks = currDef.checks;
559
- if (checks && checks.length > 0) throw new Error(".pick() cannot be used on object schemas containing refinements");
560
- return clone(schema, mergeDefs(schema._zod.def, {
561
- get shape() {
562
- const newShape = {};
563
- for (const key in mask) {
564
- if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
565
- if (!mask[key]) continue;
566
- newShape[key] = currDef.shape[key];
567
- }
568
- assignProp(this, "shape", newShape);
569
- return newShape;
570
- },
571
- checks: []
572
- }));
573
- }
574
- function omit(schema, mask) {
575
- const currDef = schema._zod.def;
576
- const checks = currDef.checks;
577
- if (checks && checks.length > 0) throw new Error(".omit() cannot be used on object schemas containing refinements");
578
- return clone(schema, mergeDefs(schema._zod.def, {
579
- get shape() {
580
- const newShape = { ...schema._zod.def.shape };
581
- for (const key in mask) {
582
- if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
583
- if (!mask[key]) continue;
584
- delete newShape[key];
585
- }
586
- assignProp(this, "shape", newShape);
587
- return newShape;
588
- },
589
- checks: []
590
- }));
591
- }
592
- function extend(schema, shape) {
593
- if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object");
594
- const checks = schema._zod.def.checks;
595
- if (checks && checks.length > 0) {
596
- const existingShape = schema._zod.def.shape;
597
- for (const key in shape) if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
598
- }
599
- return clone(schema, mergeDefs(schema._zod.def, { get shape() {
600
- const _shape = {
601
- ...schema._zod.def.shape,
602
- ...shape
603
- };
604
- assignProp(this, "shape", _shape);
605
- return _shape;
606
- } }));
607
- }
608
- function safeExtend(schema, shape) {
609
- if (!isPlainObject(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
610
- return clone(schema, mergeDefs(schema._zod.def, { get shape() {
611
- const _shape = {
612
- ...schema._zod.def.shape,
613
- ...shape
614
- };
615
- assignProp(this, "shape", _shape);
616
- return _shape;
617
- } }));
618
- }
619
- function merge(a, b) {
620
- return clone(a, mergeDefs(a._zod.def, {
621
- get shape() {
622
- const _shape = {
623
- ...a._zod.def.shape,
624
- ...b._zod.def.shape
625
- };
626
- assignProp(this, "shape", _shape);
627
- return _shape;
628
- },
629
- get catchall() {
630
- return b._zod.def.catchall;
631
- },
632
- checks: []
633
- }));
634
- }
635
- function partial(Class, schema, mask) {
636
- const checks = schema._zod.def.checks;
637
- if (checks && checks.length > 0) throw new Error(".partial() cannot be used on object schemas containing refinements");
638
- return clone(schema, mergeDefs(schema._zod.def, {
639
- get shape() {
640
- const oldShape = schema._zod.def.shape;
641
- const shape = { ...oldShape };
642
- if (mask) for (const key in mask) {
643
- if (!(key in oldShape)) throw new Error(`Unrecognized key: "${key}"`);
644
- if (!mask[key]) continue;
645
- shape[key] = Class ? new Class({
646
- type: "optional",
647
- innerType: oldShape[key]
648
- }) : oldShape[key];
649
- }
650
- else for (const key in oldShape) shape[key] = Class ? new Class({
651
- type: "optional",
652
- innerType: oldShape[key]
653
- }) : oldShape[key];
654
- assignProp(this, "shape", shape);
655
- return shape;
656
- },
657
- checks: []
658
- }));
659
- }
660
- function required(Class, schema, mask) {
661
- return clone(schema, mergeDefs(schema._zod.def, { get shape() {
662
- const oldShape = schema._zod.def.shape;
663
- const shape = { ...oldShape };
664
- if (mask) for (const key in mask) {
665
- if (!(key in shape)) throw new Error(`Unrecognized key: "${key}"`);
666
- if (!mask[key]) continue;
667
- shape[key] = new Class({
668
- type: "nonoptional",
669
- innerType: oldShape[key]
670
- });
671
- }
672
- else for (const key in oldShape) shape[key] = new Class({
673
- type: "nonoptional",
674
- innerType: oldShape[key]
675
- });
676
- assignProp(this, "shape", shape);
677
- return shape;
678
- } }));
679
- }
680
- function aborted(x, startIndex = 0) {
681
- if (x.aborted === true) return true;
682
- for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true;
683
- return false;
684
- }
685
- function prefixIssues(path, issues) {
686
- return issues.map((iss) => {
687
- var _a;
688
- (_a = iss).path ?? (_a.path = []);
689
- iss.path.unshift(path);
690
- return iss;
691
- });
692
- }
693
- function unwrapMessage(message) {
694
- return typeof message === "string" ? message : message?.message;
695
- }
696
- function finalizeIssue(iss, ctx, config) {
697
- const full = {
698
- ...iss,
699
- path: iss.path ?? []
700
- };
701
- if (!iss.message) full.message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
702
- delete full.inst;
703
- delete full.continue;
704
- if (!ctx?.reportInput) delete full.input;
705
- return full;
706
- }
707
- function getLengthableOrigin(input) {
708
- if (Array.isArray(input)) return "array";
709
- if (typeof input === "string") return "string";
710
- return "unknown";
711
- }
712
- function issue(...args) {
713
- const [iss, input, inst] = args;
714
- if (typeof iss === "string") return {
715
- message: iss,
716
- code: "custom",
717
- input,
718
- inst
719
- };
720
- return { ...iss };
721
- }
722
-
723
- //#endregion
724
- //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js
725
- const initializer$1 = (inst, def) => {
726
- inst.name = "$ZodError";
727
- Object.defineProperty(inst, "_zod", {
728
- value: inst._zod,
729
- enumerable: false
730
- });
731
- Object.defineProperty(inst, "issues", {
732
- value: def,
733
- enumerable: false
734
- });
735
- inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
736
- Object.defineProperty(inst, "toString", {
737
- value: () => inst.message,
738
- enumerable: false
739
- });
740
- };
741
- const $ZodError = $constructor("$ZodError", initializer$1);
742
- const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error });
743
- function flattenError(error, mapper = (issue) => issue.message) {
744
- const fieldErrors = {};
745
- const formErrors = [];
746
- for (const sub of error.issues) if (sub.path.length > 0) {
747
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
748
- fieldErrors[sub.path[0]].push(mapper(sub));
749
- } else formErrors.push(mapper(sub));
750
- return {
751
- formErrors,
752
- fieldErrors
753
- };
754
- }
755
- function formatError(error, mapper = (issue) => issue.message) {
756
- const fieldErrors = { _errors: [] };
757
- const processError = (error) => {
758
- for (const issue of error.issues) if (issue.code === "invalid_union" && issue.errors.length) issue.errors.map((issues) => processError({ issues }));
759
- else if (issue.code === "invalid_key") processError({ issues: issue.issues });
760
- else if (issue.code === "invalid_element") processError({ issues: issue.issues });
761
- else if (issue.path.length === 0) fieldErrors._errors.push(mapper(issue));
762
- else {
763
- let curr = fieldErrors;
764
- let i = 0;
765
- while (i < issue.path.length) {
766
- const el = issue.path[i];
767
- if (!(i === issue.path.length - 1)) curr[el] = curr[el] || { _errors: [] };
768
- else {
769
- curr[el] = curr[el] || { _errors: [] };
770
- curr[el]._errors.push(mapper(issue));
771
- }
772
- curr = curr[el];
773
- i++;
774
- }
775
- }
776
- };
777
- processError(error);
778
- return fieldErrors;
779
- }
780
-
781
- //#endregion
782
- //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js
783
- const _parse = (_Err) => (schema, value, _ctx, _params) => {
784
- const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
785
- const result = schema._zod.run({
786
- value,
787
- issues: []
788
- }, ctx);
789
- if (result instanceof Promise) throw new $ZodAsyncError();
790
- if (result.issues.length) {
791
- const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
792
- captureStackTrace(e, _params?.callee);
793
- throw e;
794
- }
795
- return result.value;
796
- };
797
- const parse$1 = /* @__PURE__ */ _parse($ZodRealError);
798
- const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
799
- const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
800
- let result = schema._zod.run({
801
- value,
802
- issues: []
803
- }, ctx);
804
- if (result instanceof Promise) result = await result;
805
- if (result.issues.length) {
806
- const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
807
- captureStackTrace(e, params?.callee);
808
- throw e;
809
- }
810
- return result.value;
811
- };
812
- const parseAsync$1 = /* @__PURE__ */ _parseAsync($ZodRealError);
813
- const _safeParse = (_Err) => (schema, value, _ctx) => {
814
- const ctx = _ctx ? {
815
- ..._ctx,
816
- async: false
817
- } : { async: false };
818
- const result = schema._zod.run({
819
- value,
820
- issues: []
821
- }, ctx);
822
- if (result instanceof Promise) throw new $ZodAsyncError();
823
- return result.issues.length ? {
824
- success: false,
825
- error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
826
- } : {
827
- success: true,
828
- data: result.value
829
- };
830
- };
831
- const safeParse$1 = /* @__PURE__ */ _safeParse($ZodRealError);
832
- const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
833
- const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
834
- let result = schema._zod.run({
835
- value,
836
- issues: []
837
- }, ctx);
838
- if (result instanceof Promise) result = await result;
839
- return result.issues.length ? {
840
- success: false,
841
- error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
842
- } : {
843
- success: true,
844
- data: result.value
845
- };
846
- };
847
- const safeParseAsync$1 = /* @__PURE__ */ _safeParseAsync($ZodRealError);
848
- const _encode = (_Err) => (schema, value, _ctx) => {
849
- const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
850
- return _parse(_Err)(schema, value, ctx);
851
- };
852
- const encode$1 = /* @__PURE__ */ _encode($ZodRealError);
853
- const _decode = (_Err) => (schema, value, _ctx) => {
854
- return _parse(_Err)(schema, value, _ctx);
855
- };
856
- const decode$1 = /* @__PURE__ */ _decode($ZodRealError);
857
- const _encodeAsync = (_Err) => async (schema, value, _ctx) => {
858
- const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
859
- return _parseAsync(_Err)(schema, value, ctx);
860
- };
861
- const encodeAsync$1 = /* @__PURE__ */ _encodeAsync($ZodRealError);
862
- const _decodeAsync = (_Err) => async (schema, value, _ctx) => {
863
- return _parseAsync(_Err)(schema, value, _ctx);
864
- };
865
- const decodeAsync$1 = /* @__PURE__ */ _decodeAsync($ZodRealError);
866
- const _safeEncode = (_Err) => (schema, value, _ctx) => {
867
- const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
868
- return _safeParse(_Err)(schema, value, ctx);
869
- };
870
- const safeEncode$1 = /* @__PURE__ */ _safeEncode($ZodRealError);
871
- const _safeDecode = (_Err) => (schema, value, _ctx) => {
872
- return _safeParse(_Err)(schema, value, _ctx);
873
- };
874
- const safeDecode$1 = /* @__PURE__ */ _safeDecode($ZodRealError);
875
- const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
876
- const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
877
- return _safeParseAsync(_Err)(schema, value, ctx);
878
- };
879
- const safeEncodeAsync$1 = /* @__PURE__ */ _safeEncodeAsync($ZodRealError);
880
- const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
881
- return _safeParseAsync(_Err)(schema, value, _ctx);
882
- };
883
- const safeDecodeAsync$1 = /* @__PURE__ */ _safeDecodeAsync($ZodRealError);
884
-
885
- //#endregion
886
- //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js
887
- const cuid = /^[cC][^\s-]{8,}$/;
888
- const cuid2 = /^[0-9a-z]+$/;
889
- const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
890
- const xid = /^[0-9a-vA-V]{20}$/;
891
- const ksuid = /^[A-Za-z0-9]{27}$/;
892
- const nanoid = /^[a-zA-Z0-9_-]{21}$/;
893
- /** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
894
- 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)?)?)$/;
895
- /** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
896
- 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})$/;
897
- /** Returns a regex for validating an RFC 9562/4122 UUID.
898
- *
899
- * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
900
- const uuid = (version) => {
901
- if (!version) 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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
902
- 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})$`);
903
- };
904
- /** Practical email validation */
905
- const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
906
- const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
907
- function emoji() {
908
- return new RegExp(_emoji$1, "u");
909
- }
910
- 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])$/;
911
- const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
912
- 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])$/;
913
- 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])$/;
914
- const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
915
- const base64url = /^[A-Za-z0-9_-]*$/;
916
- const e164 = /^\+[1-9]\d{6,14}$/;
917
- 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])))`;
918
- const date$1 = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
919
- function timeSource(args) {
920
- const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
921
- return typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
922
- }
923
- function time$1(args) {
924
- return new RegExp(`^${timeSource(args)}$`);
925
- }
926
- function datetime$1(args) {
927
- const time = timeSource({ precision: args.precision });
928
- const opts = ["Z"];
929
- if (args.local) opts.push("");
930
- if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
931
- const timeRegex = `${time}(?:${opts.join("|")})`;
932
- return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
933
- }
934
- const string = (params) => {
935
- const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
936
- return new RegExp(`^${regex}$`);
937
- };
938
- const lowercase = /^[^A-Z]*$/;
939
- const uppercase = /^[^a-z]*$/;
940
-
941
- //#endregion
942
- //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js
943
- const $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
944
- var _a;
945
- inst._zod ?? (inst._zod = {});
946
- inst._zod.def = def;
947
- (_a = inst._zod).onattach ?? (_a.onattach = []);
948
- });
949
- const $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
950
- var _a;
951
- $ZodCheck.init(inst, def);
952
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
953
- const val = payload.value;
954
- return !nullish(val) && val.length !== void 0;
955
- });
956
- inst._zod.onattach.push((inst) => {
957
- const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
958
- if (def.maximum < curr) inst._zod.bag.maximum = def.maximum;
959
- });
960
- inst._zod.check = (payload) => {
961
- const input = payload.value;
962
- if (input.length <= def.maximum) return;
963
- const origin = getLengthableOrigin(input);
964
- payload.issues.push({
965
- origin,
966
- code: "too_big",
967
- maximum: def.maximum,
968
- inclusive: true,
969
- input,
970
- inst,
971
- continue: !def.abort
972
- });
973
- };
974
- });
975
- const $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
976
- var _a;
977
- $ZodCheck.init(inst, def);
978
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
979
- const val = payload.value;
980
- return !nullish(val) && val.length !== void 0;
981
- });
982
- inst._zod.onattach.push((inst) => {
983
- const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
984
- if (def.minimum > curr) inst._zod.bag.minimum = def.minimum;
985
- });
986
- inst._zod.check = (payload) => {
987
- const input = payload.value;
988
- if (input.length >= def.minimum) return;
989
- const origin = getLengthableOrigin(input);
990
- payload.issues.push({
991
- origin,
992
- code: "too_small",
993
- minimum: def.minimum,
994
- inclusive: true,
995
- input,
996
- inst,
997
- continue: !def.abort
998
- });
999
- };
1000
- });
1001
- const $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
1002
- var _a;
1003
- $ZodCheck.init(inst, def);
1004
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
1005
- const val = payload.value;
1006
- return !nullish(val) && val.length !== void 0;
1007
- });
1008
- inst._zod.onattach.push((inst) => {
1009
- const bag = inst._zod.bag;
1010
- bag.minimum = def.length;
1011
- bag.maximum = def.length;
1012
- bag.length = def.length;
1013
- });
1014
- inst._zod.check = (payload) => {
1015
- const input = payload.value;
1016
- const length = input.length;
1017
- if (length === def.length) return;
1018
- const origin = getLengthableOrigin(input);
1019
- const tooBig = length > def.length;
1020
- payload.issues.push({
1021
- origin,
1022
- ...tooBig ? {
1023
- code: "too_big",
1024
- maximum: def.length
1025
- } : {
1026
- code: "too_small",
1027
- minimum: def.length
1028
- },
1029
- inclusive: true,
1030
- exact: true,
1031
- input: payload.value,
1032
- inst,
1033
- continue: !def.abort
1034
- });
1035
- };
1036
- });
1037
- const $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
1038
- var _a, _b;
1039
- $ZodCheck.init(inst, def);
1040
- inst._zod.onattach.push((inst) => {
1041
- const bag = inst._zod.bag;
1042
- bag.format = def.format;
1043
- if (def.pattern) {
1044
- bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
1045
- bag.patterns.add(def.pattern);
1046
- }
1047
- });
1048
- if (def.pattern) (_a = inst._zod).check ?? (_a.check = (payload) => {
1049
- def.pattern.lastIndex = 0;
1050
- if (def.pattern.test(payload.value)) return;
1051
- payload.issues.push({
1052
- origin: "string",
1053
- code: "invalid_format",
1054
- format: def.format,
1055
- input: payload.value,
1056
- ...def.pattern ? { pattern: def.pattern.toString() } : {},
1057
- inst,
1058
- continue: !def.abort
1059
- });
1060
- });
1061
- else (_b = inst._zod).check ?? (_b.check = () => {});
1062
- });
1063
- const $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {
1064
- $ZodCheckStringFormat.init(inst, def);
1065
- inst._zod.check = (payload) => {
1066
- def.pattern.lastIndex = 0;
1067
- if (def.pattern.test(payload.value)) return;
1068
- payload.issues.push({
1069
- origin: "string",
1070
- code: "invalid_format",
1071
- format: "regex",
1072
- input: payload.value,
1073
- pattern: def.pattern.toString(),
1074
- inst,
1075
- continue: !def.abort
1076
- });
1077
- };
1078
- });
1079
- const $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {
1080
- def.pattern ?? (def.pattern = lowercase);
1081
- $ZodCheckStringFormat.init(inst, def);
1082
- });
1083
- const $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
1084
- def.pattern ?? (def.pattern = uppercase);
1085
- $ZodCheckStringFormat.init(inst, def);
1086
- });
1087
- const $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
1088
- $ZodCheck.init(inst, def);
1089
- const escapedRegex = escapeRegex(def.includes);
1090
- const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
1091
- def.pattern = pattern;
1092
- inst._zod.onattach.push((inst) => {
1093
- const bag = inst._zod.bag;
1094
- bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
1095
- bag.patterns.add(pattern);
1096
- });
1097
- inst._zod.check = (payload) => {
1098
- if (payload.value.includes(def.includes, def.position)) return;
1099
- payload.issues.push({
1100
- origin: "string",
1101
- code: "invalid_format",
1102
- format: "includes",
1103
- includes: def.includes,
1104
- input: payload.value,
1105
- inst,
1106
- continue: !def.abort
1107
- });
1108
- };
1109
- });
1110
- const $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
1111
- $ZodCheck.init(inst, def);
1112
- const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
1113
- def.pattern ?? (def.pattern = pattern);
1114
- inst._zod.onattach.push((inst) => {
1115
- const bag = inst._zod.bag;
1116
- bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
1117
- bag.patterns.add(pattern);
1118
- });
1119
- inst._zod.check = (payload) => {
1120
- if (payload.value.startsWith(def.prefix)) return;
1121
- payload.issues.push({
1122
- origin: "string",
1123
- code: "invalid_format",
1124
- format: "starts_with",
1125
- prefix: def.prefix,
1126
- input: payload.value,
1127
- inst,
1128
- continue: !def.abort
1129
- });
1130
- };
1131
- });
1132
- const $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
1133
- $ZodCheck.init(inst, def);
1134
- const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
1135
- def.pattern ?? (def.pattern = pattern);
1136
- inst._zod.onattach.push((inst) => {
1137
- const bag = inst._zod.bag;
1138
- bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
1139
- bag.patterns.add(pattern);
1140
- });
1141
- inst._zod.check = (payload) => {
1142
- if (payload.value.endsWith(def.suffix)) return;
1143
- payload.issues.push({
1144
- origin: "string",
1145
- code: "invalid_format",
1146
- format: "ends_with",
1147
- suffix: def.suffix,
1148
- input: payload.value,
1149
- inst,
1150
- continue: !def.abort
1151
- });
1152
- };
1153
- });
1154
- const $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
1155
- $ZodCheck.init(inst, def);
1156
- inst._zod.check = (payload) => {
1157
- payload.value = def.tx(payload.value);
1158
- };
1159
- });
1160
-
1161
- //#endregion
1162
- //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js
1163
- var Doc = class {
1164
- constructor(args = []) {
1165
- this.content = [];
1166
- this.indent = 0;
1167
- if (this) this.args = args;
1168
- }
1169
- indented(fn) {
1170
- this.indent += 1;
1171
- fn(this);
1172
- this.indent -= 1;
1173
- }
1174
- write(arg) {
1175
- if (typeof arg === "function") {
1176
- arg(this, { execution: "sync" });
1177
- arg(this, { execution: "async" });
1178
- return;
1179
- }
1180
- const lines = arg.split("\n").filter((x) => x);
1181
- const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
1182
- const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
1183
- for (const line of dedented) this.content.push(line);
1184
- }
1185
- compile() {
1186
- const F = Function;
1187
- const args = this?.args;
1188
- const lines = [...(this?.content ?? [``]).map((x) => ` ${x}`)];
1189
- return new F(...args, lines.join("\n"));
1190
- }
1191
- };
1192
-
1193
- //#endregion
1194
- //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js
1195
- const version = {
1196
- major: 4,
1197
- minor: 3,
1198
- patch: 6
1199
- };
1200
-
1201
- //#endregion
1202
- //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js
1203
- const $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
1204
- var _a;
1205
- inst ?? (inst = {});
1206
- inst._zod.def = def;
1207
- inst._zod.bag = inst._zod.bag || {};
1208
- inst._zod.version = version;
1209
- const checks = [...inst._zod.def.checks ?? []];
1210
- if (inst._zod.traits.has("$ZodCheck")) checks.unshift(inst);
1211
- for (const ch of checks) for (const fn of ch._zod.onattach) fn(inst);
1212
- if (checks.length === 0) {
1213
- (_a = inst._zod).deferred ?? (_a.deferred = []);
1214
- inst._zod.deferred?.push(() => {
1215
- inst._zod.run = inst._zod.parse;
1216
- });
1217
- } else {
1218
- const runChecks = (payload, checks, ctx) => {
1219
- let isAborted = aborted(payload);
1220
- let asyncResult;
1221
- for (const ch of checks) {
1222
- if (ch._zod.def.when) {
1223
- if (!ch._zod.def.when(payload)) continue;
1224
- } else if (isAborted) continue;
1225
- const currLen = payload.issues.length;
1226
- const _ = ch._zod.check(payload);
1227
- if (_ instanceof Promise && ctx?.async === false) throw new $ZodAsyncError();
1228
- if (asyncResult || _ instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
1229
- await _;
1230
- if (payload.issues.length === currLen) return;
1231
- if (!isAborted) isAborted = aborted(payload, currLen);
1232
- });
1233
- else {
1234
- if (payload.issues.length === currLen) continue;
1235
- if (!isAborted) isAborted = aborted(payload, currLen);
1236
- }
1237
- }
1238
- if (asyncResult) return asyncResult.then(() => {
1239
- return payload;
1240
- });
1241
- return payload;
1242
- };
1243
- const handleCanaryResult = (canary, payload, ctx) => {
1244
- if (aborted(canary)) {
1245
- canary.aborted = true;
1246
- return canary;
1247
- }
1248
- const checkResult = runChecks(payload, checks, ctx);
1249
- if (checkResult instanceof Promise) {
1250
- if (ctx.async === false) throw new $ZodAsyncError();
1251
- return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));
1252
- }
1253
- return inst._zod.parse(checkResult, ctx);
1254
- };
1255
- inst._zod.run = (payload, ctx) => {
1256
- if (ctx.skipChecks) return inst._zod.parse(payload, ctx);
1257
- if (ctx.direction === "backward") {
1258
- const canary = inst._zod.parse({
1259
- value: payload.value,
1260
- issues: []
1261
- }, {
1262
- ...ctx,
1263
- skipChecks: true
1264
- });
1265
- if (canary instanceof Promise) return canary.then((canary) => {
1266
- return handleCanaryResult(canary, payload, ctx);
1267
- });
1268
- return handleCanaryResult(canary, payload, ctx);
1269
- }
1270
- const result = inst._zod.parse(payload, ctx);
1271
- if (result instanceof Promise) {
1272
- if (ctx.async === false) throw new $ZodAsyncError();
1273
- return result.then((result) => runChecks(result, checks, ctx));
1274
- }
1275
- return runChecks(result, checks, ctx);
1276
- };
1277
- }
1278
- defineLazy(inst, "~standard", () => ({
1279
- validate: (value) => {
1280
- try {
1281
- const r = safeParse$1(inst, value);
1282
- return r.success ? { value: r.data } : { issues: r.error?.issues };
1283
- } catch (_) {
1284
- return safeParseAsync$1(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
1285
- }
1286
- },
1287
- vendor: "zod",
1288
- version: 1
1289
- }));
1290
- });
1291
- const $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
1292
- $ZodType.init(inst, def);
1293
- inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag);
1294
- inst._zod.parse = (payload, _) => {
1295
- if (def.coerce) try {
1296
- payload.value = String(payload.value);
1297
- } catch (_) {}
1298
- if (typeof payload.value === "string") return payload;
1299
- payload.issues.push({
1300
- expected: "string",
1301
- code: "invalid_type",
1302
- input: payload.value,
1303
- inst
1304
- });
1305
- return payload;
1306
- };
1307
- });
1308
- const $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => {
1309
- $ZodCheckStringFormat.init(inst, def);
1310
- $ZodString.init(inst, def);
1311
- });
1312
- const $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {
1313
- def.pattern ?? (def.pattern = guid);
1314
- $ZodStringFormat.init(inst, def);
1315
- });
1316
- const $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
1317
- if (def.version) {
1318
- const v = {
1319
- v1: 1,
1320
- v2: 2,
1321
- v3: 3,
1322
- v4: 4,
1323
- v5: 5,
1324
- v6: 6,
1325
- v7: 7,
1326
- v8: 8
1327
- }[def.version];
1328
- if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`);
1329
- def.pattern ?? (def.pattern = uuid(v));
1330
- } else def.pattern ?? (def.pattern = uuid());
1331
- $ZodStringFormat.init(inst, def);
1332
- });
1333
- const $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
1334
- def.pattern ?? (def.pattern = email);
1335
- $ZodStringFormat.init(inst, def);
1336
- });
1337
- const $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
1338
- $ZodStringFormat.init(inst, def);
1339
- inst._zod.check = (payload) => {
1340
- try {
1341
- const trimmed = payload.value.trim();
1342
- const url = new URL(trimmed);
1343
- if (def.hostname) {
1344
- def.hostname.lastIndex = 0;
1345
- if (!def.hostname.test(url.hostname)) payload.issues.push({
1346
- code: "invalid_format",
1347
- format: "url",
1348
- note: "Invalid hostname",
1349
- pattern: def.hostname.source,
1350
- input: payload.value,
1351
- inst,
1352
- continue: !def.abort
1353
- });
1354
- }
1355
- if (def.protocol) {
1356
- def.protocol.lastIndex = 0;
1357
- if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) payload.issues.push({
1358
- code: "invalid_format",
1359
- format: "url",
1360
- note: "Invalid protocol",
1361
- pattern: def.protocol.source,
1362
- input: payload.value,
1363
- inst,
1364
- continue: !def.abort
1365
- });
1366
- }
1367
- if (def.normalize) payload.value = url.href;
1368
- else payload.value = trimmed;
1369
- return;
1370
- } catch (_) {
1371
- payload.issues.push({
1372
- code: "invalid_format",
1373
- format: "url",
1374
- input: payload.value,
1375
- inst,
1376
- continue: !def.abort
1377
- });
1378
- }
1379
- };
1380
- });
1381
- const $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
1382
- def.pattern ?? (def.pattern = emoji());
1383
- $ZodStringFormat.init(inst, def);
1384
- });
1385
- const $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
1386
- def.pattern ?? (def.pattern = nanoid);
1387
- $ZodStringFormat.init(inst, def);
1388
- });
1389
- const $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
1390
- def.pattern ?? (def.pattern = cuid);
1391
- $ZodStringFormat.init(inst, def);
1392
- });
1393
- const $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {
1394
- def.pattern ?? (def.pattern = cuid2);
1395
- $ZodStringFormat.init(inst, def);
1396
- });
1397
- const $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {
1398
- def.pattern ?? (def.pattern = ulid);
1399
- $ZodStringFormat.init(inst, def);
1400
- });
1401
- const $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {
1402
- def.pattern ?? (def.pattern = xid);
1403
- $ZodStringFormat.init(inst, def);
1404
- });
1405
- const $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
1406
- def.pattern ?? (def.pattern = ksuid);
1407
- $ZodStringFormat.init(inst, def);
1408
- });
1409
- const $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
1410
- def.pattern ?? (def.pattern = datetime$1(def));
1411
- $ZodStringFormat.init(inst, def);
1412
- });
1413
- const $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
1414
- def.pattern ?? (def.pattern = date$1);
1415
- $ZodStringFormat.init(inst, def);
1416
- });
1417
- const $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
1418
- def.pattern ?? (def.pattern = time$1(def));
1419
- $ZodStringFormat.init(inst, def);
1420
- });
1421
- const $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
1422
- def.pattern ?? (def.pattern = duration$1);
1423
- $ZodStringFormat.init(inst, def);
1424
- });
1425
- const $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
1426
- def.pattern ?? (def.pattern = ipv4);
1427
- $ZodStringFormat.init(inst, def);
1428
- inst._zod.bag.format = `ipv4`;
1429
- });
1430
- const $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
1431
- def.pattern ?? (def.pattern = ipv6);
1432
- $ZodStringFormat.init(inst, def);
1433
- inst._zod.bag.format = `ipv6`;
1434
- inst._zod.check = (payload) => {
1435
- try {
1436
- new URL(`http://[${payload.value}]`);
1437
- } catch {
1438
- payload.issues.push({
1439
- code: "invalid_format",
1440
- format: "ipv6",
1441
- input: payload.value,
1442
- inst,
1443
- continue: !def.abort
1444
- });
1445
- }
1446
- };
1447
- });
1448
- const $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
1449
- def.pattern ?? (def.pattern = cidrv4);
1450
- $ZodStringFormat.init(inst, def);
1451
- });
1452
- const $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
1453
- def.pattern ?? (def.pattern = cidrv6);
1454
- $ZodStringFormat.init(inst, def);
1455
- inst._zod.check = (payload) => {
1456
- const parts = payload.value.split("/");
1457
- try {
1458
- if (parts.length !== 2) throw new Error();
1459
- const [address, prefix] = parts;
1460
- if (!prefix) throw new Error();
1461
- const prefixNum = Number(prefix);
1462
- if (`${prefixNum}` !== prefix) throw new Error();
1463
- if (prefixNum < 0 || prefixNum > 128) throw new Error();
1464
- new URL(`http://[${address}]`);
1465
- } catch {
1466
- payload.issues.push({
1467
- code: "invalid_format",
1468
- format: "cidrv6",
1469
- input: payload.value,
1470
- inst,
1471
- continue: !def.abort
1472
- });
1473
- }
1474
- };
1475
- });
1476
- function isValidBase64(data) {
1477
- if (data === "") return true;
1478
- if (data.length % 4 !== 0) return false;
1479
- try {
1480
- atob(data);
1481
- return true;
1482
- } catch {
1483
- return false;
1484
- }
1485
- }
1486
- const $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
1487
- def.pattern ?? (def.pattern = base64);
1488
- $ZodStringFormat.init(inst, def);
1489
- inst._zod.bag.contentEncoding = "base64";
1490
- inst._zod.check = (payload) => {
1491
- if (isValidBase64(payload.value)) return;
1492
- payload.issues.push({
1493
- code: "invalid_format",
1494
- format: "base64",
1495
- input: payload.value,
1496
- inst,
1497
- continue: !def.abort
1498
- });
1499
- };
1500
- });
1501
- function isValidBase64URL(data) {
1502
- if (!base64url.test(data)) return false;
1503
- const base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
1504
- return isValidBase64(base64.padEnd(Math.ceil(base64.length / 4) * 4, "="));
1505
- }
1506
- const $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
1507
- def.pattern ?? (def.pattern = base64url);
1508
- $ZodStringFormat.init(inst, def);
1509
- inst._zod.bag.contentEncoding = "base64url";
1510
- inst._zod.check = (payload) => {
1511
- if (isValidBase64URL(payload.value)) return;
1512
- payload.issues.push({
1513
- code: "invalid_format",
1514
- format: "base64url",
1515
- input: payload.value,
1516
- inst,
1517
- continue: !def.abort
1518
- });
1519
- };
1520
- });
1521
- const $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {
1522
- def.pattern ?? (def.pattern = e164);
1523
- $ZodStringFormat.init(inst, def);
1524
- });
1525
- function isValidJWT(token, algorithm = null) {
1526
- try {
1527
- const tokensParts = token.split(".");
1528
- if (tokensParts.length !== 3) return false;
1529
- const [header] = tokensParts;
1530
- if (!header) return false;
1531
- const parsedHeader = JSON.parse(atob(header));
1532
- if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false;
1533
- if (!parsedHeader.alg) return false;
1534
- if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false;
1535
- return true;
1536
- } catch {
1537
- return false;
1538
- }
1539
- }
1540
- const $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
1541
- $ZodStringFormat.init(inst, def);
1542
- inst._zod.check = (payload) => {
1543
- if (isValidJWT(payload.value, def.alg)) return;
1544
- payload.issues.push({
1545
- code: "invalid_format",
1546
- format: "jwt",
1547
- input: payload.value,
1548
- inst,
1549
- continue: !def.abort
1550
- });
1551
- };
1552
- });
1553
- const $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
1554
- $ZodType.init(inst, def);
1555
- inst._zod.parse = (payload) => payload;
1556
- });
1557
- const $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
1558
- $ZodType.init(inst, def);
1559
- inst._zod.parse = (payload, _ctx) => {
1560
- payload.issues.push({
1561
- expected: "never",
1562
- code: "invalid_type",
1563
- input: payload.value,
1564
- inst
1565
- });
1566
- return payload;
1567
- };
1568
- });
1569
- function handleArrayResult(result, final, index) {
1570
- if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues));
1571
- final.value[index] = result.value;
1572
- }
1573
- const $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
1574
- $ZodType.init(inst, def);
1575
- inst._zod.parse = (payload, ctx) => {
1576
- const input = payload.value;
1577
- if (!Array.isArray(input)) {
1578
- payload.issues.push({
1579
- expected: "array",
1580
- code: "invalid_type",
1581
- input,
1582
- inst
1583
- });
1584
- return payload;
1585
- }
1586
- payload.value = Array(input.length);
1587
- const proms = [];
1588
- for (let i = 0; i < input.length; i++) {
1589
- const item = input[i];
1590
- const result = def.element._zod.run({
1591
- value: item,
1592
- issues: []
1593
- }, ctx);
1594
- if (result instanceof Promise) proms.push(result.then((result) => handleArrayResult(result, payload, i)));
1595
- else handleArrayResult(result, payload, i);
1596
- }
1597
- if (proms.length) return Promise.all(proms).then(() => payload);
1598
- return payload;
1599
- };
1600
- });
1601
- function handlePropertyResult(result, final, key, input, isOptionalOut) {
1602
- if (result.issues.length) {
1603
- if (isOptionalOut && !(key in input)) return;
1604
- final.issues.push(...prefixIssues(key, result.issues));
1605
- }
1606
- if (result.value === void 0) {
1607
- if (key in input) final.value[key] = void 0;
1608
- } else final.value[key] = result.value;
1609
- }
1610
- function normalizeDef(def) {
1611
- const keys = Object.keys(def.shape);
1612
- for (const k of keys) if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
1613
- const okeys = optionalKeys(def.shape);
1614
- return {
1615
- ...def,
1616
- keys,
1617
- keySet: new Set(keys),
1618
- numKeys: keys.length,
1619
- optionalKeys: new Set(okeys)
1620
- };
1621
- }
1622
- function handleCatchall(proms, input, payload, ctx, def, inst) {
1623
- const unrecognized = [];
1624
- const keySet = def.keySet;
1625
- const _catchall = def.catchall._zod;
1626
- const t = _catchall.def.type;
1627
- const isOptionalOut = _catchall.optout === "optional";
1628
- for (const key in input) {
1629
- if (keySet.has(key)) continue;
1630
- if (t === "never") {
1631
- unrecognized.push(key);
1632
- continue;
1633
- }
1634
- const r = _catchall.run({
1635
- value: input[key],
1636
- issues: []
1637
- }, ctx);
1638
- if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));
1639
- else handlePropertyResult(r, payload, key, input, isOptionalOut);
1640
- }
1641
- if (unrecognized.length) payload.issues.push({
1642
- code: "unrecognized_keys",
1643
- keys: unrecognized,
1644
- input,
1645
- inst
1646
- });
1647
- if (!proms.length) return payload;
1648
- return Promise.all(proms).then(() => {
1649
- return payload;
1650
- });
1651
- }
1652
- const $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
1653
- $ZodType.init(inst, def);
1654
- if (!Object.getOwnPropertyDescriptor(def, "shape")?.get) {
1655
- const sh = def.shape;
1656
- Object.defineProperty(def, "shape", { get: () => {
1657
- const newSh = { ...sh };
1658
- Object.defineProperty(def, "shape", { value: newSh });
1659
- return newSh;
1660
- } });
1661
- }
1662
- const _normalized = cached(() => normalizeDef(def));
1663
- defineLazy(inst._zod, "propValues", () => {
1664
- const shape = def.shape;
1665
- const propValues = {};
1666
- for (const key in shape) {
1667
- const field = shape[key]._zod;
1668
- if (field.values) {
1669
- propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
1670
- for (const v of field.values) propValues[key].add(v);
1671
- }
1672
- }
1673
- return propValues;
1674
- });
1675
- const isObject$2 = isObject;
1676
- const catchall = def.catchall;
1677
- let value;
1678
- inst._zod.parse = (payload, ctx) => {
1679
- value ?? (value = _normalized.value);
1680
- const input = payload.value;
1681
- if (!isObject$2(input)) {
1682
- payload.issues.push({
1683
- expected: "object",
1684
- code: "invalid_type",
1685
- input,
1686
- inst
1687
- });
1688
- return payload;
1689
- }
1690
- payload.value = {};
1691
- const proms = [];
1692
- const shape = value.shape;
1693
- for (const key of value.keys) {
1694
- const el = shape[key];
1695
- const isOptionalOut = el._zod.optout === "optional";
1696
- const r = el._zod.run({
1697
- value: input[key],
1698
- issues: []
1699
- }, ctx);
1700
- if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));
1701
- else handlePropertyResult(r, payload, key, input, isOptionalOut);
1702
- }
1703
- if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload;
1704
- return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
1705
- };
1706
- });
1707
- const $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
1708
- $ZodObject.init(inst, def);
1709
- const superParse = inst._zod.parse;
1710
- const _normalized = cached(() => normalizeDef(def));
1711
- const generateFastpass = (shape) => {
1712
- const doc = new Doc([
1713
- "shape",
1714
- "payload",
1715
- "ctx"
1716
- ]);
1717
- const normalized = _normalized.value;
1718
- const parseStr = (key) => {
1719
- const k = esc(key);
1720
- return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
1721
- };
1722
- doc.write(`const input = payload.value;`);
1723
- const ids = Object.create(null);
1724
- let counter = 0;
1725
- for (const key of normalized.keys) ids[key] = `key_${counter++}`;
1726
- doc.write(`const newResult = {};`);
1727
- for (const key of normalized.keys) {
1728
- const id = ids[key];
1729
- const k = esc(key);
1730
- const isOptionalOut = shape[key]?._zod?.optout === "optional";
1731
- doc.write(`const ${id} = ${parseStr(key)};`);
1732
- if (isOptionalOut) doc.write(`
1733
- if (${id}.issues.length) {
1734
- if (${k} in input) {
1735
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
1736
- ...iss,
1737
- path: iss.path ? [${k}, ...iss.path] : [${k}]
1738
- })));
1739
- }
1740
- }
1741
-
1742
- if (${id}.value === undefined) {
1743
- if (${k} in input) {
1744
- newResult[${k}] = undefined;
1745
- }
1746
- } else {
1747
- newResult[${k}] = ${id}.value;
1748
- }
1749
-
1750
- `);
1751
- else doc.write(`
1752
- if (${id}.issues.length) {
1753
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
1754
- ...iss,
1755
- path: iss.path ? [${k}, ...iss.path] : [${k}]
1756
- })));
1757
- }
1758
-
1759
- if (${id}.value === undefined) {
1760
- if (${k} in input) {
1761
- newResult[${k}] = undefined;
1762
- }
1763
- } else {
1764
- newResult[${k}] = ${id}.value;
1765
- }
1766
-
1767
- `);
1768
- }
1769
- doc.write(`payload.value = newResult;`);
1770
- doc.write(`return payload;`);
1771
- const fn = doc.compile();
1772
- return (payload, ctx) => fn(shape, payload, ctx);
1773
- };
1774
- let fastpass;
1775
- const isObject$1 = isObject;
1776
- const jit = !globalConfig.jitless;
1777
- const allowsEval$1 = allowsEval;
1778
- const fastEnabled = jit && allowsEval$1.value;
1779
- const catchall = def.catchall;
1780
- let value;
1781
- inst._zod.parse = (payload, ctx) => {
1782
- value ?? (value = _normalized.value);
1783
- const input = payload.value;
1784
- if (!isObject$1(input)) {
1785
- payload.issues.push({
1786
- expected: "object",
1787
- code: "invalid_type",
1788
- input,
1789
- inst
1790
- });
1791
- return payload;
1792
- }
1793
- if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
1794
- if (!fastpass) fastpass = generateFastpass(def.shape);
1795
- payload = fastpass(payload, ctx);
1796
- if (!catchall) return payload;
1797
- return handleCatchall([], input, payload, ctx, value, inst);
1798
- }
1799
- return superParse(payload, ctx);
1800
- };
1801
- });
1802
- function handleUnionResults(results, final, inst, ctx) {
1803
- for (const result of results) if (result.issues.length === 0) {
1804
- final.value = result.value;
1805
- return final;
1806
- }
1807
- const nonaborted = results.filter((r) => !aborted(r));
1808
- if (nonaborted.length === 1) {
1809
- final.value = nonaborted[0].value;
1810
- return nonaborted[0];
1811
- }
1812
- final.issues.push({
1813
- code: "invalid_union",
1814
- input: final.value,
1815
- inst,
1816
- errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
1817
- });
1818
- return final;
1819
- }
1820
- const $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
1821
- $ZodType.init(inst, def);
1822
- defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0);
1823
- defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
1824
- defineLazy(inst._zod, "values", () => {
1825
- if (def.options.every((o) => o._zod.values)) return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
1826
- });
1827
- defineLazy(inst._zod, "pattern", () => {
1828
- if (def.options.every((o) => o._zod.pattern)) {
1829
- const patterns = def.options.map((o) => o._zod.pattern);
1830
- return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
1831
- }
1832
- });
1833
- const single = def.options.length === 1;
1834
- const first = def.options[0]._zod.run;
1835
- inst._zod.parse = (payload, ctx) => {
1836
- if (single) return first(payload, ctx);
1837
- let async = false;
1838
- const results = [];
1839
- for (const option of def.options) {
1840
- const result = option._zod.run({
1841
- value: payload.value,
1842
- issues: []
1843
- }, ctx);
1844
- if (result instanceof Promise) {
1845
- results.push(result);
1846
- async = true;
1847
- } else {
1848
- if (result.issues.length === 0) return result;
1849
- results.push(result);
1850
- }
1851
- }
1852
- if (!async) return handleUnionResults(results, payload, inst, ctx);
1853
- return Promise.all(results).then((results) => {
1854
- return handleUnionResults(results, payload, inst, ctx);
1855
- });
1856
- };
1857
- });
1858
- const $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => {
1859
- $ZodType.init(inst, def);
1860
- inst._zod.parse = (payload, ctx) => {
1861
- const input = payload.value;
1862
- const left = def.left._zod.run({
1863
- value: input,
1864
- issues: []
1865
- }, ctx);
1866
- const right = def.right._zod.run({
1867
- value: input,
1868
- issues: []
1869
- }, ctx);
1870
- if (left instanceof Promise || right instanceof Promise) return Promise.all([left, right]).then(([left, right]) => {
1871
- return handleIntersectionResults(payload, left, right);
1872
- });
1873
- return handleIntersectionResults(payload, left, right);
1874
- };
1875
- });
1876
- function mergeValues(a, b) {
1877
- if (a === b) return {
1878
- valid: true,
1879
- data: a
1880
- };
1881
- if (a instanceof Date && b instanceof Date && +a === +b) return {
1882
- valid: true,
1883
- data: a
1884
- };
1885
- if (isPlainObject(a) && isPlainObject(b)) {
1886
- const bKeys = Object.keys(b);
1887
- const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
1888
- const newObj = {
1889
- ...a,
1890
- ...b
1891
- };
1892
- for (const key of sharedKeys) {
1893
- const sharedValue = mergeValues(a[key], b[key]);
1894
- if (!sharedValue.valid) return {
1895
- valid: false,
1896
- mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
1897
- };
1898
- newObj[key] = sharedValue.data;
1899
- }
1900
- return {
1901
- valid: true,
1902
- data: newObj
1903
- };
1904
- }
1905
- if (Array.isArray(a) && Array.isArray(b)) {
1906
- if (a.length !== b.length) return {
1907
- valid: false,
1908
- mergeErrorPath: []
1909
- };
1910
- const newArray = [];
1911
- for (let index = 0; index < a.length; index++) {
1912
- const itemA = a[index];
1913
- const itemB = b[index];
1914
- const sharedValue = mergeValues(itemA, itemB);
1915
- if (!sharedValue.valid) return {
1916
- valid: false,
1917
- mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
1918
- };
1919
- newArray.push(sharedValue.data);
1920
- }
1921
- return {
1922
- valid: true,
1923
- data: newArray
1924
- };
1925
- }
1926
- return {
1927
- valid: false,
1928
- mergeErrorPath: []
1929
- };
1930
- }
1931
- function handleIntersectionResults(result, left, right) {
1932
- const unrecKeys = /* @__PURE__ */ new Map();
1933
- let unrecIssue;
1934
- for (const iss of left.issues) if (iss.code === "unrecognized_keys") {
1935
- unrecIssue ?? (unrecIssue = iss);
1936
- for (const k of iss.keys) {
1937
- if (!unrecKeys.has(k)) unrecKeys.set(k, {});
1938
- unrecKeys.get(k).l = true;
1939
- }
1940
- } else result.issues.push(iss);
1941
- for (const iss of right.issues) if (iss.code === "unrecognized_keys") for (const k of iss.keys) {
1942
- if (!unrecKeys.has(k)) unrecKeys.set(k, {});
1943
- unrecKeys.get(k).r = true;
1944
- }
1945
- else result.issues.push(iss);
1946
- const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
1947
- if (bothKeys.length && unrecIssue) result.issues.push({
1948
- ...unrecIssue,
1949
- keys: bothKeys
1950
- });
1951
- if (aborted(result)) return result;
1952
- const merged = mergeValues(left.value, right.value);
1953
- if (!merged.valid) throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
1954
- result.value = merged.data;
1955
- return result;
1956
- }
1957
- const $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
1958
- $ZodType.init(inst, def);
1959
- const values = getEnumValues(def.entries);
1960
- const valuesSet = new Set(values);
1961
- inst._zod.values = valuesSet;
1962
- inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
1963
- inst._zod.parse = (payload, _ctx) => {
1964
- const input = payload.value;
1965
- if (valuesSet.has(input)) return payload;
1966
- payload.issues.push({
1967
- code: "invalid_value",
1968
- values,
1969
- input,
1970
- inst
1971
- });
1972
- return payload;
1973
- };
1974
- });
1975
- const $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
1976
- $ZodType.init(inst, def);
1977
- if (def.values.length === 0) throw new Error("Cannot create literal schema with no valid values");
1978
- const values = new Set(def.values);
1979
- inst._zod.values = values;
1980
- inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
1981
- inst._zod.parse = (payload, _ctx) => {
1982
- const input = payload.value;
1983
- if (values.has(input)) return payload;
1984
- payload.issues.push({
1985
- code: "invalid_value",
1986
- values: def.values,
1987
- input,
1988
- inst
1989
- });
1990
- return payload;
1991
- };
1992
- });
1993
- const $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
1994
- $ZodType.init(inst, def);
1995
- inst._zod.parse = (payload, ctx) => {
1996
- if (ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name);
1997
- const _out = def.transform(payload.value, payload);
1998
- if (ctx.async) return (_out instanceof Promise ? _out : Promise.resolve(_out)).then((output) => {
1999
- payload.value = output;
2000
- return payload;
2001
- });
2002
- if (_out instanceof Promise) throw new $ZodAsyncError();
2003
- payload.value = _out;
2004
- return payload;
2005
- };
2006
- });
2007
- function handleOptionalResult(result, input) {
2008
- if (result.issues.length && input === void 0) return {
2009
- issues: [],
2010
- value: void 0
2011
- };
2012
- return result;
2013
- }
2014
- const $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
2015
- $ZodType.init(inst, def);
2016
- inst._zod.optin = "optional";
2017
- inst._zod.optout = "optional";
2018
- defineLazy(inst._zod, "values", () => {
2019
- return def.innerType._zod.values ? new Set([...def.innerType._zod.values, void 0]) : void 0;
2020
- });
2021
- defineLazy(inst._zod, "pattern", () => {
2022
- const pattern = def.innerType._zod.pattern;
2023
- return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;
2024
- });
2025
- inst._zod.parse = (payload, ctx) => {
2026
- if (def.innerType._zod.optin === "optional") {
2027
- const result = def.innerType._zod.run(payload, ctx);
2028
- if (result instanceof Promise) return result.then((r) => handleOptionalResult(r, payload.value));
2029
- return handleOptionalResult(result, payload.value);
2030
- }
2031
- if (payload.value === void 0) return payload;
2032
- return def.innerType._zod.run(payload, ctx);
2033
- };
2034
- });
2035
- const $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => {
2036
- $ZodOptional.init(inst, def);
2037
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2038
- defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern);
2039
- inst._zod.parse = (payload, ctx) => {
2040
- return def.innerType._zod.run(payload, ctx);
2041
- };
2042
- });
2043
- const $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
2044
- $ZodType.init(inst, def);
2045
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
2046
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
2047
- defineLazy(inst._zod, "pattern", () => {
2048
- const pattern = def.innerType._zod.pattern;
2049
- return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;
2050
- });
2051
- defineLazy(inst._zod, "values", () => {
2052
- return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : void 0;
2053
- });
2054
- inst._zod.parse = (payload, ctx) => {
2055
- if (payload.value === null) return payload;
2056
- return def.innerType._zod.run(payload, ctx);
2057
- };
2058
- });
2059
- const $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
2060
- $ZodType.init(inst, def);
2061
- inst._zod.optin = "optional";
2062
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2063
- inst._zod.parse = (payload, ctx) => {
2064
- if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
2065
- if (payload.value === void 0) {
2066
- payload.value = def.defaultValue;
2067
- /**
2068
- * $ZodDefault returns the default value immediately in forward direction.
2069
- * 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. */
2070
- return payload;
2071
- }
2072
- const result = def.innerType._zod.run(payload, ctx);
2073
- if (result instanceof Promise) return result.then((result) => handleDefaultResult(result, def));
2074
- return handleDefaultResult(result, def);
2075
- };
2076
- });
2077
- function handleDefaultResult(payload, def) {
2078
- if (payload.value === void 0) payload.value = def.defaultValue;
2079
- return payload;
2080
- }
2081
- const $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {
2082
- $ZodType.init(inst, def);
2083
- inst._zod.optin = "optional";
2084
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2085
- inst._zod.parse = (payload, ctx) => {
2086
- if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
2087
- if (payload.value === void 0) payload.value = def.defaultValue;
2088
- return def.innerType._zod.run(payload, ctx);
2089
- };
2090
- });
2091
- const $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
2092
- $ZodType.init(inst, def);
2093
- defineLazy(inst._zod, "values", () => {
2094
- const v = def.innerType._zod.values;
2095
- return v ? new Set([...v].filter((x) => x !== void 0)) : void 0;
2096
- });
2097
- inst._zod.parse = (payload, ctx) => {
2098
- const result = def.innerType._zod.run(payload, ctx);
2099
- if (result instanceof Promise) return result.then((result) => handleNonOptionalResult(result, inst));
2100
- return handleNonOptionalResult(result, inst);
2101
- };
2102
- });
2103
- function handleNonOptionalResult(payload, inst) {
2104
- if (!payload.issues.length && payload.value === void 0) payload.issues.push({
2105
- code: "invalid_type",
2106
- expected: "nonoptional",
2107
- input: payload.value,
2108
- inst
2109
- });
2110
- return payload;
2111
- }
2112
- const $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
2113
- $ZodType.init(inst, def);
2114
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
2115
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
2116
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2117
- inst._zod.parse = (payload, ctx) => {
2118
- if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
2119
- const result = def.innerType._zod.run(payload, ctx);
2120
- if (result instanceof Promise) return result.then((result) => {
2121
- payload.value = result.value;
2122
- if (result.issues.length) {
2123
- payload.value = def.catchValue({
2124
- ...payload,
2125
- error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) },
2126
- input: payload.value
2127
- });
2128
- payload.issues = [];
2129
- }
2130
- return payload;
2131
- });
2132
- payload.value = result.value;
2133
- if (result.issues.length) {
2134
- payload.value = def.catchValue({
2135
- ...payload,
2136
- error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) },
2137
- input: payload.value
2138
- });
2139
- payload.issues = [];
2140
- }
2141
- return payload;
2142
- };
2143
- });
2144
- const $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
2145
- $ZodType.init(inst, def);
2146
- defineLazy(inst._zod, "values", () => def.in._zod.values);
2147
- defineLazy(inst._zod, "optin", () => def.in._zod.optin);
2148
- defineLazy(inst._zod, "optout", () => def.out._zod.optout);
2149
- defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
2150
- inst._zod.parse = (payload, ctx) => {
2151
- if (ctx.direction === "backward") {
2152
- const right = def.out._zod.run(payload, ctx);
2153
- if (right instanceof Promise) return right.then((right) => handlePipeResult(right, def.in, ctx));
2154
- return handlePipeResult(right, def.in, ctx);
2155
- }
2156
- const left = def.in._zod.run(payload, ctx);
2157
- if (left instanceof Promise) return left.then((left) => handlePipeResult(left, def.out, ctx));
2158
- return handlePipeResult(left, def.out, ctx);
2159
- };
2160
- });
2161
- function handlePipeResult(left, next, ctx) {
2162
- if (left.issues.length) {
2163
- left.aborted = true;
2164
- return left;
2165
- }
2166
- return next._zod.run({
2167
- value: left.value,
2168
- issues: left.issues
2169
- }, ctx);
2170
- }
2171
- const $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
2172
- $ZodType.init(inst, def);
2173
- defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
2174
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2175
- defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin);
2176
- defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout);
2177
- inst._zod.parse = (payload, ctx) => {
2178
- if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
2179
- const result = def.innerType._zod.run(payload, ctx);
2180
- if (result instanceof Promise) return result.then(handleReadonlyResult);
2181
- return handleReadonlyResult(result);
2182
- };
2183
- });
2184
- function handleReadonlyResult(payload) {
2185
- payload.value = Object.freeze(payload.value);
2186
- return payload;
2187
- }
2188
- const $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
2189
- $ZodCheck.init(inst, def);
2190
- $ZodType.init(inst, def);
2191
- inst._zod.parse = (payload, _) => {
2192
- return payload;
2193
- };
2194
- inst._zod.check = (payload) => {
2195
- const input = payload.value;
2196
- const r = def.fn(input);
2197
- if (r instanceof Promise) return r.then((r) => handleRefineResult(r, payload, input, inst));
2198
- handleRefineResult(r, payload, input, inst);
2199
- };
2200
- });
2201
- function handleRefineResult(result, payload, input, inst) {
2202
- if (!result) {
2203
- const _iss = {
2204
- code: "custom",
2205
- input,
2206
- inst,
2207
- path: [...inst._zod.def.path ?? []],
2208
- continue: !inst._zod.def.abort
2209
- };
2210
- if (inst._zod.def.params) _iss.params = inst._zod.def.params;
2211
- payload.issues.push(issue(_iss));
2212
- }
2213
- }
2214
-
2215
- //#endregion
2216
- //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js
2217
- var _a;
2218
- var $ZodRegistry = class {
2219
- constructor() {
2220
- this._map = /* @__PURE__ */ new WeakMap();
2221
- this._idmap = /* @__PURE__ */ new Map();
2222
- }
2223
- add(schema, ..._meta) {
2224
- const meta = _meta[0];
2225
- this._map.set(schema, meta);
2226
- if (meta && typeof meta === "object" && "id" in meta) this._idmap.set(meta.id, schema);
2227
- return this;
2228
- }
2229
- clear() {
2230
- this._map = /* @__PURE__ */ new WeakMap();
2231
- this._idmap = /* @__PURE__ */ new Map();
2232
- return this;
2233
- }
2234
- remove(schema) {
2235
- const meta = this._map.get(schema);
2236
- if (meta && typeof meta === "object" && "id" in meta) this._idmap.delete(meta.id);
2237
- this._map.delete(schema);
2238
- return this;
2239
- }
2240
- get(schema) {
2241
- const p = schema._zod.parent;
2242
- if (p) {
2243
- const pm = { ...this.get(p) ?? {} };
2244
- delete pm.id;
2245
- const f = {
2246
- ...pm,
2247
- ...this._map.get(schema)
2248
- };
2249
- return Object.keys(f).length ? f : void 0;
2250
- }
2251
- return this._map.get(schema);
2252
- }
2253
- has(schema) {
2254
- return this._map.has(schema);
2255
- }
2256
- };
2257
- function registry() {
2258
- return new $ZodRegistry();
2259
- }
2260
- (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
2261
- const globalRegistry = globalThis.__zod_globalRegistry;
2262
-
2263
- //#endregion
2264
- //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js
2265
- /* @__NO_SIDE_EFFECTS__ */
2266
- function _email(Class, params) {
2267
- return new Class({
2268
- type: "string",
2269
- format: "email",
2270
- check: "string_format",
2271
- abort: false,
2272
- ...normalizeParams(params)
2273
- });
2274
- }
2275
- /* @__NO_SIDE_EFFECTS__ */
2276
- function _guid(Class, params) {
2277
- return new Class({
2278
- type: "string",
2279
- format: "guid",
2280
- check: "string_format",
2281
- abort: false,
2282
- ...normalizeParams(params)
2283
- });
2284
- }
2285
- /* @__NO_SIDE_EFFECTS__ */
2286
- function _uuid(Class, params) {
2287
- return new Class({
2288
- type: "string",
2289
- format: "uuid",
2290
- check: "string_format",
2291
- abort: false,
2292
- ...normalizeParams(params)
2293
- });
2294
- }
2295
- /* @__NO_SIDE_EFFECTS__ */
2296
- function _uuidv4(Class, params) {
2297
- return new Class({
2298
- type: "string",
2299
- format: "uuid",
2300
- check: "string_format",
2301
- abort: false,
2302
- version: "v4",
2303
- ...normalizeParams(params)
2304
- });
2305
- }
2306
- /* @__NO_SIDE_EFFECTS__ */
2307
- function _uuidv6(Class, params) {
2308
- return new Class({
2309
- type: "string",
2310
- format: "uuid",
2311
- check: "string_format",
2312
- abort: false,
2313
- version: "v6",
2314
- ...normalizeParams(params)
2315
- });
2316
- }
2317
- /* @__NO_SIDE_EFFECTS__ */
2318
- function _uuidv7(Class, params) {
2319
- return new Class({
2320
- type: "string",
2321
- format: "uuid",
2322
- check: "string_format",
2323
- abort: false,
2324
- version: "v7",
2325
- ...normalizeParams(params)
2326
- });
2327
- }
2328
- /* @__NO_SIDE_EFFECTS__ */
2329
- function _url(Class, params) {
2330
- return new Class({
2331
- type: "string",
2332
- format: "url",
2333
- check: "string_format",
2334
- abort: false,
2335
- ...normalizeParams(params)
2336
- });
2337
- }
2338
- /* @__NO_SIDE_EFFECTS__ */
2339
- function _emoji(Class, params) {
2340
- return new Class({
2341
- type: "string",
2342
- format: "emoji",
2343
- check: "string_format",
2344
- abort: false,
2345
- ...normalizeParams(params)
2346
- });
2347
- }
2348
- /* @__NO_SIDE_EFFECTS__ */
2349
- function _nanoid(Class, params) {
2350
- return new Class({
2351
- type: "string",
2352
- format: "nanoid",
2353
- check: "string_format",
2354
- abort: false,
2355
- ...normalizeParams(params)
2356
- });
2357
- }
2358
- /* @__NO_SIDE_EFFECTS__ */
2359
- function _cuid(Class, params) {
2360
- return new Class({
2361
- type: "string",
2362
- format: "cuid",
2363
- check: "string_format",
2364
- abort: false,
2365
- ...normalizeParams(params)
2366
- });
2367
- }
2368
- /* @__NO_SIDE_EFFECTS__ */
2369
- function _cuid2(Class, params) {
2370
- return new Class({
2371
- type: "string",
2372
- format: "cuid2",
2373
- check: "string_format",
2374
- abort: false,
2375
- ...normalizeParams(params)
2376
- });
2377
- }
2378
- /* @__NO_SIDE_EFFECTS__ */
2379
- function _ulid(Class, params) {
2380
- return new Class({
2381
- type: "string",
2382
- format: "ulid",
2383
- check: "string_format",
2384
- abort: false,
2385
- ...normalizeParams(params)
2386
- });
2387
- }
2388
- /* @__NO_SIDE_EFFECTS__ */
2389
- function _xid(Class, params) {
2390
- return new Class({
2391
- type: "string",
2392
- format: "xid",
2393
- check: "string_format",
2394
- abort: false,
2395
- ...normalizeParams(params)
2396
- });
2397
- }
2398
- /* @__NO_SIDE_EFFECTS__ */
2399
- function _ksuid(Class, params) {
2400
- return new Class({
2401
- type: "string",
2402
- format: "ksuid",
2403
- check: "string_format",
2404
- abort: false,
2405
- ...normalizeParams(params)
2406
- });
2407
- }
2408
- /* @__NO_SIDE_EFFECTS__ */
2409
- function _ipv4(Class, params) {
2410
- return new Class({
2411
- type: "string",
2412
- format: "ipv4",
2413
- check: "string_format",
2414
- abort: false,
2415
- ...normalizeParams(params)
2416
- });
2417
- }
2418
- /* @__NO_SIDE_EFFECTS__ */
2419
- function _ipv6(Class, params) {
2420
- return new Class({
2421
- type: "string",
2422
- format: "ipv6",
2423
- check: "string_format",
2424
- abort: false,
2425
- ...normalizeParams(params)
2426
- });
2427
- }
2428
- /* @__NO_SIDE_EFFECTS__ */
2429
- function _cidrv4(Class, params) {
2430
- return new Class({
2431
- type: "string",
2432
- format: "cidrv4",
2433
- check: "string_format",
2434
- abort: false,
2435
- ...normalizeParams(params)
2436
- });
2437
- }
2438
- /* @__NO_SIDE_EFFECTS__ */
2439
- function _cidrv6(Class, params) {
2440
- return new Class({
2441
- type: "string",
2442
- format: "cidrv6",
2443
- check: "string_format",
2444
- abort: false,
2445
- ...normalizeParams(params)
2446
- });
2447
- }
2448
- /* @__NO_SIDE_EFFECTS__ */
2449
- function _base64(Class, params) {
2450
- return new Class({
2451
- type: "string",
2452
- format: "base64",
2453
- check: "string_format",
2454
- abort: false,
2455
- ...normalizeParams(params)
2456
- });
2457
- }
2458
- /* @__NO_SIDE_EFFECTS__ */
2459
- function _base64url(Class, params) {
2460
- return new Class({
2461
- type: "string",
2462
- format: "base64url",
2463
- check: "string_format",
2464
- abort: false,
2465
- ...normalizeParams(params)
2466
- });
2467
- }
2468
- /* @__NO_SIDE_EFFECTS__ */
2469
- function _e164(Class, params) {
2470
- return new Class({
2471
- type: "string",
2472
- format: "e164",
2473
- check: "string_format",
2474
- abort: false,
2475
- ...normalizeParams(params)
2476
- });
2477
- }
2478
- /* @__NO_SIDE_EFFECTS__ */
2479
- function _jwt(Class, params) {
2480
- return new Class({
2481
- type: "string",
2482
- format: "jwt",
2483
- check: "string_format",
2484
- abort: false,
2485
- ...normalizeParams(params)
2486
- });
2487
- }
2488
- /* @__NO_SIDE_EFFECTS__ */
2489
- function _isoDateTime(Class, params) {
2490
- return new Class({
2491
- type: "string",
2492
- format: "datetime",
2493
- check: "string_format",
2494
- offset: false,
2495
- local: false,
2496
- precision: null,
2497
- ...normalizeParams(params)
2498
- });
2499
- }
2500
- /* @__NO_SIDE_EFFECTS__ */
2501
- function _isoDate(Class, params) {
2502
- return new Class({
2503
- type: "string",
2504
- format: "date",
2505
- check: "string_format",
2506
- ...normalizeParams(params)
2507
- });
2508
- }
2509
- /* @__NO_SIDE_EFFECTS__ */
2510
- function _isoTime(Class, params) {
2511
- return new Class({
2512
- type: "string",
2513
- format: "time",
2514
- check: "string_format",
2515
- precision: null,
2516
- ...normalizeParams(params)
2517
- });
2518
- }
2519
- /* @__NO_SIDE_EFFECTS__ */
2520
- function _isoDuration(Class, params) {
2521
- return new Class({
2522
- type: "string",
2523
- format: "duration",
2524
- check: "string_format",
2525
- ...normalizeParams(params)
2526
- });
2527
- }
2528
- /* @__NO_SIDE_EFFECTS__ */
2529
- function _unknown(Class) {
2530
- return new Class({ type: "unknown" });
2531
- }
2532
- /* @__NO_SIDE_EFFECTS__ */
2533
- function _never(Class, params) {
2534
- return new Class({
2535
- type: "never",
2536
- ...normalizeParams(params)
2537
- });
2538
- }
2539
- /* @__NO_SIDE_EFFECTS__ */
2540
- function _maxLength(maximum, params) {
2541
- return new $ZodCheckMaxLength({
2542
- check: "max_length",
2543
- ...normalizeParams(params),
2544
- maximum
2545
- });
2546
- }
2547
- /* @__NO_SIDE_EFFECTS__ */
2548
- function _minLength(minimum, params) {
2549
- return new $ZodCheckMinLength({
2550
- check: "min_length",
2551
- ...normalizeParams(params),
2552
- minimum
2553
- });
2554
- }
2555
- /* @__NO_SIDE_EFFECTS__ */
2556
- function _length(length, params) {
2557
- return new $ZodCheckLengthEquals({
2558
- check: "length_equals",
2559
- ...normalizeParams(params),
2560
- length
2561
- });
2562
- }
2563
- /* @__NO_SIDE_EFFECTS__ */
2564
- function _regex(pattern, params) {
2565
- return new $ZodCheckRegex({
2566
- check: "string_format",
2567
- format: "regex",
2568
- ...normalizeParams(params),
2569
- pattern
2570
- });
2571
- }
2572
- /* @__NO_SIDE_EFFECTS__ */
2573
- function _lowercase(params) {
2574
- return new $ZodCheckLowerCase({
2575
- check: "string_format",
2576
- format: "lowercase",
2577
- ...normalizeParams(params)
2578
- });
2579
- }
2580
- /* @__NO_SIDE_EFFECTS__ */
2581
- function _uppercase(params) {
2582
- return new $ZodCheckUpperCase({
2583
- check: "string_format",
2584
- format: "uppercase",
2585
- ...normalizeParams(params)
2586
- });
2587
- }
2588
- /* @__NO_SIDE_EFFECTS__ */
2589
- function _includes(includes, params) {
2590
- return new $ZodCheckIncludes({
2591
- check: "string_format",
2592
- format: "includes",
2593
- ...normalizeParams(params),
2594
- includes
2595
- });
2596
- }
2597
- /* @__NO_SIDE_EFFECTS__ */
2598
- function _startsWith(prefix, params) {
2599
- return new $ZodCheckStartsWith({
2600
- check: "string_format",
2601
- format: "starts_with",
2602
- ...normalizeParams(params),
2603
- prefix
2604
- });
2605
- }
2606
- /* @__NO_SIDE_EFFECTS__ */
2607
- function _endsWith(suffix, params) {
2608
- return new $ZodCheckEndsWith({
2609
- check: "string_format",
2610
- format: "ends_with",
2611
- ...normalizeParams(params),
2612
- suffix
2613
- });
2614
- }
2615
- /* @__NO_SIDE_EFFECTS__ */
2616
- function _overwrite(tx) {
2617
- return new $ZodCheckOverwrite({
2618
- check: "overwrite",
2619
- tx
2620
- });
2621
- }
2622
- /* @__NO_SIDE_EFFECTS__ */
2623
- function _normalize(form) {
2624
- return /* @__PURE__ */ _overwrite((input) => input.normalize(form));
2625
- }
2626
- /* @__NO_SIDE_EFFECTS__ */
2627
- function _trim() {
2628
- return /* @__PURE__ */ _overwrite((input) => input.trim());
2629
- }
2630
- /* @__NO_SIDE_EFFECTS__ */
2631
- function _toLowerCase() {
2632
- return /* @__PURE__ */ _overwrite((input) => input.toLowerCase());
2633
- }
2634
- /* @__NO_SIDE_EFFECTS__ */
2635
- function _toUpperCase() {
2636
- return /* @__PURE__ */ _overwrite((input) => input.toUpperCase());
2637
- }
2638
- /* @__NO_SIDE_EFFECTS__ */
2639
- function _slugify() {
2640
- return /* @__PURE__ */ _overwrite((input) => slugify(input));
2641
- }
2642
- /* @__NO_SIDE_EFFECTS__ */
2643
- function _array(Class, element, params) {
2644
- return new Class({
2645
- type: "array",
2646
- element,
2647
- ...normalizeParams(params)
2648
- });
2649
- }
2650
- /* @__NO_SIDE_EFFECTS__ */
2651
- function _refine(Class, fn, _params) {
2652
- return new Class({
2653
- type: "custom",
2654
- check: "custom",
2655
- fn,
2656
- ...normalizeParams(_params)
2657
- });
2658
- }
2659
- /* @__NO_SIDE_EFFECTS__ */
2660
- function _superRefine(fn) {
2661
- const ch = /* @__PURE__ */ _check((payload) => {
2662
- payload.addIssue = (issue$2) => {
2663
- if (typeof issue$2 === "string") payload.issues.push(issue(issue$2, payload.value, ch._zod.def));
2664
- else {
2665
- const _issue = issue$2;
2666
- if (_issue.fatal) _issue.continue = false;
2667
- _issue.code ?? (_issue.code = "custom");
2668
- _issue.input ?? (_issue.input = payload.value);
2669
- _issue.inst ?? (_issue.inst = ch);
2670
- _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
2671
- payload.issues.push(issue(_issue));
2672
- }
2673
- };
2674
- return fn(payload.value, payload);
2675
- });
2676
- return ch;
2677
- }
2678
- /* @__NO_SIDE_EFFECTS__ */
2679
- function _check(fn, params) {
2680
- const ch = new $ZodCheck({
2681
- check: "custom",
2682
- ...normalizeParams(params)
2683
- });
2684
- ch._zod.check = fn;
2685
- return ch;
2686
- }
2687
- /* @__NO_SIDE_EFFECTS__ */
2688
- function describe$1(description) {
2689
- const ch = new $ZodCheck({ check: "describe" });
2690
- ch._zod.onattach = [(inst) => {
2691
- const existing = globalRegistry.get(inst) ?? {};
2692
- globalRegistry.add(inst, {
2693
- ...existing,
2694
- description
2695
- });
2696
- }];
2697
- ch._zod.check = () => {};
2698
- return ch;
2699
- }
2700
- /* @__NO_SIDE_EFFECTS__ */
2701
- function meta$1(metadata) {
2702
- const ch = new $ZodCheck({ check: "meta" });
2703
- ch._zod.onattach = [(inst) => {
2704
- const existing = globalRegistry.get(inst) ?? {};
2705
- globalRegistry.add(inst, {
2706
- ...existing,
2707
- ...metadata
2708
- });
2709
- }];
2710
- ch._zod.check = () => {};
2711
- return ch;
2712
- }
2713
-
2714
- //#endregion
2715
- //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js
2716
- function initializeContext(params) {
2717
- let target = params?.target ?? "draft-2020-12";
2718
- if (target === "draft-4") target = "draft-04";
2719
- if (target === "draft-7") target = "draft-07";
2720
- return {
2721
- processors: params.processors ?? {},
2722
- metadataRegistry: params?.metadata ?? globalRegistry,
2723
- target,
2724
- unrepresentable: params?.unrepresentable ?? "throw",
2725
- override: params?.override ?? (() => {}),
2726
- io: params?.io ?? "output",
2727
- counter: 0,
2728
- seen: /* @__PURE__ */ new Map(),
2729
- cycles: params?.cycles ?? "ref",
2730
- reused: params?.reused ?? "inline",
2731
- external: params?.external ?? void 0
2732
- };
2733
- }
2734
- function process$1(schema, ctx, _params = {
2735
- path: [],
2736
- schemaPath: []
2737
- }) {
2738
- var _a;
2739
- const def = schema._zod.def;
2740
- const seen = ctx.seen.get(schema);
2741
- if (seen) {
2742
- seen.count++;
2743
- if (_params.schemaPath.includes(schema)) seen.cycle = _params.path;
2744
- return seen.schema;
2745
- }
2746
- const result = {
2747
- schema: {},
2748
- count: 1,
2749
- cycle: void 0,
2750
- path: _params.path
2751
- };
2752
- ctx.seen.set(schema, result);
2753
- const overrideSchema = schema._zod.toJSONSchema?.();
2754
- if (overrideSchema) result.schema = overrideSchema;
2755
- else {
2756
- const params = {
2757
- ..._params,
2758
- schemaPath: [..._params.schemaPath, schema],
2759
- path: _params.path
2760
- };
2761
- if (schema._zod.processJSONSchema) schema._zod.processJSONSchema(ctx, result.schema, params);
2762
- else {
2763
- const _json = result.schema;
2764
- const processor = ctx.processors[def.type];
2765
- if (!processor) throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
2766
- processor(schema, ctx, _json, params);
2767
- }
2768
- const parent = schema._zod.parent;
2769
- if (parent) {
2770
- if (!result.ref) result.ref = parent;
2771
- process$1(parent, ctx, params);
2772
- ctx.seen.get(parent).isParent = true;
2773
- }
2774
- }
2775
- const meta = ctx.metadataRegistry.get(schema);
2776
- if (meta) Object.assign(result.schema, meta);
2777
- if (ctx.io === "input" && isTransforming(schema)) {
2778
- delete result.schema.examples;
2779
- delete result.schema.default;
2780
- }
2781
- if (ctx.io === "input" && result.schema._prefault) (_a = result.schema).default ?? (_a.default = result.schema._prefault);
2782
- delete result.schema._prefault;
2783
- return ctx.seen.get(schema).schema;
2784
- }
2785
- function extractDefs(ctx, schema) {
2786
- const root = ctx.seen.get(schema);
2787
- if (!root) throw new Error("Unprocessed schema. This is a bug in Zod.");
2788
- const idToSchema = /* @__PURE__ */ new Map();
2789
- for (const entry of ctx.seen.entries()) {
2790
- const id = ctx.metadataRegistry.get(entry[0])?.id;
2791
- if (id) {
2792
- const existing = idToSchema.get(id);
2793
- if (existing && existing !== entry[0]) throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
2794
- idToSchema.set(id, entry[0]);
2795
- }
2796
- }
2797
- const makeURI = (entry) => {
2798
- const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
2799
- if (ctx.external) {
2800
- const externalId = ctx.external.registry.get(entry[0])?.id;
2801
- const uriGenerator = ctx.external.uri ?? ((id) => id);
2802
- if (externalId) return { ref: uriGenerator(externalId) };
2803
- const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
2804
- entry[1].defId = id;
2805
- return {
2806
- defId: id,
2807
- ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}`
2808
- };
2809
- }
2810
- if (entry[1] === root) return { ref: "#" };
2811
- const defUriPrefix = `#/${defsSegment}/`;
2812
- const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
2813
- return {
2814
- defId,
2815
- ref: defUriPrefix + defId
2816
- };
2817
- };
2818
- const extractToDef = (entry) => {
2819
- if (entry[1].schema.$ref) return;
2820
- const seen = entry[1];
2821
- const { ref, defId } = makeURI(entry);
2822
- seen.def = { ...seen.schema };
2823
- if (defId) seen.defId = defId;
2824
- const schema = seen.schema;
2825
- for (const key in schema) delete schema[key];
2826
- schema.$ref = ref;
2827
- };
2828
- if (ctx.cycles === "throw") for (const entry of ctx.seen.entries()) {
2829
- const seen = entry[1];
2830
- if (seen.cycle) throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
2831
-
2832
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);
2833
- }
2834
- for (const entry of ctx.seen.entries()) {
2835
- const seen = entry[1];
2836
- if (schema === entry[0]) {
2837
- extractToDef(entry);
2838
- continue;
2839
- }
2840
- if (ctx.external) {
2841
- const ext = ctx.external.registry.get(entry[0])?.id;
2842
- if (schema !== entry[0] && ext) {
2843
- extractToDef(entry);
2844
- continue;
2845
- }
2846
- }
2847
- if (ctx.metadataRegistry.get(entry[0])?.id) {
2848
- extractToDef(entry);
2849
- continue;
2850
- }
2851
- if (seen.cycle) {
2852
- extractToDef(entry);
2853
- continue;
2854
- }
2855
- if (seen.count > 1) {
2856
- if (ctx.reused === "ref") {
2857
- extractToDef(entry);
2858
- continue;
2859
- }
2860
- }
2861
- }
2862
- }
2863
- function finalize(ctx, schema) {
2864
- const root = ctx.seen.get(schema);
2865
- if (!root) throw new Error("Unprocessed schema. This is a bug in Zod.");
2866
- const flattenRef = (zodSchema) => {
2867
- const seen = ctx.seen.get(zodSchema);
2868
- if (seen.ref === null) return;
2869
- const schema = seen.def ?? seen.schema;
2870
- const _cached = { ...schema };
2871
- const ref = seen.ref;
2872
- seen.ref = null;
2873
- if (ref) {
2874
- flattenRef(ref);
2875
- const refSeen = ctx.seen.get(ref);
2876
- const refSchema = refSeen.schema;
2877
- if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
2878
- schema.allOf = schema.allOf ?? [];
2879
- schema.allOf.push(refSchema);
2880
- } else Object.assign(schema, refSchema);
2881
- Object.assign(schema, _cached);
2882
- if (zodSchema._zod.parent === ref) for (const key in schema) {
2883
- if (key === "$ref" || key === "allOf") continue;
2884
- if (!(key in _cached)) delete schema[key];
2885
- }
2886
- if (refSchema.$ref && refSeen.def) for (const key in schema) {
2887
- if (key === "$ref" || key === "allOf") continue;
2888
- if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) delete schema[key];
2889
- }
2890
- }
2891
- const parent = zodSchema._zod.parent;
2892
- if (parent && parent !== ref) {
2893
- flattenRef(parent);
2894
- const parentSeen = ctx.seen.get(parent);
2895
- if (parentSeen?.schema.$ref) {
2896
- schema.$ref = parentSeen.schema.$ref;
2897
- if (parentSeen.def) for (const key in schema) {
2898
- if (key === "$ref" || key === "allOf") continue;
2899
- if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) delete schema[key];
2900
- }
2901
- }
2902
- }
2903
- ctx.override({
2904
- zodSchema,
2905
- jsonSchema: schema,
2906
- path: seen.path ?? []
2907
- });
2908
- };
2909
- for (const entry of [...ctx.seen.entries()].reverse()) flattenRef(entry[0]);
2910
- const result = {};
2911
- if (ctx.target === "draft-2020-12") result.$schema = "https://json-schema.org/draft/2020-12/schema";
2912
- else if (ctx.target === "draft-07") result.$schema = "http://json-schema.org/draft-07/schema#";
2913
- else if (ctx.target === "draft-04") result.$schema = "http://json-schema.org/draft-04/schema#";
2914
- else if (ctx.target === "openapi-3.0") {}
2915
- if (ctx.external?.uri) {
2916
- const id = ctx.external.registry.get(schema)?.id;
2917
- if (!id) throw new Error("Schema is missing an `id` property");
2918
- result.$id = ctx.external.uri(id);
2919
- }
2920
- Object.assign(result, root.def ?? root.schema);
2921
- const defs = ctx.external?.defs ?? {};
2922
- for (const entry of ctx.seen.entries()) {
2923
- const seen = entry[1];
2924
- if (seen.def && seen.defId) defs[seen.defId] = seen.def;
2925
- }
2926
- if (ctx.external) {} else if (Object.keys(defs).length > 0) if (ctx.target === "draft-2020-12") result.$defs = defs;
2927
- else result.definitions = defs;
2928
- try {
2929
- const finalized = JSON.parse(JSON.stringify(result));
2930
- Object.defineProperty(finalized, "~standard", {
2931
- value: {
2932
- ...schema["~standard"],
2933
- jsonSchema: {
2934
- input: createStandardJSONSchemaMethod(schema, "input", ctx.processors),
2935
- output: createStandardJSONSchemaMethod(schema, "output", ctx.processors)
2936
- }
2937
- },
2938
- enumerable: false,
2939
- writable: false
2940
- });
2941
- return finalized;
2942
- } catch (_err) {
2943
- throw new Error("Error converting schema to JSON.");
2944
- }
2945
- }
2946
- function isTransforming(_schema, _ctx) {
2947
- const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() };
2948
- if (ctx.seen.has(_schema)) return false;
2949
- ctx.seen.add(_schema);
2950
- const def = _schema._zod.def;
2951
- if (def.type === "transform") return true;
2952
- if (def.type === "array") return isTransforming(def.element, ctx);
2953
- if (def.type === "set") return isTransforming(def.valueType, ctx);
2954
- if (def.type === "lazy") return isTransforming(def.getter(), ctx);
2955
- if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") return isTransforming(def.innerType, ctx);
2956
- if (def.type === "intersection") return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
2957
- if (def.type === "record" || def.type === "map") return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
2958
- if (def.type === "pipe") return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
2959
- if (def.type === "object") {
2960
- for (const key in def.shape) if (isTransforming(def.shape[key], ctx)) return true;
2961
- return false;
2962
- }
2963
- if (def.type === "union") {
2964
- for (const option of def.options) if (isTransforming(option, ctx)) return true;
2965
- return false;
2966
- }
2967
- if (def.type === "tuple") {
2968
- for (const item of def.items) if (isTransforming(item, ctx)) return true;
2969
- if (def.rest && isTransforming(def.rest, ctx)) return true;
2970
- return false;
2971
- }
2972
- return false;
2973
- }
2974
- /**
2975
- * Creates a toJSONSchema method for a schema instance.
2976
- * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.
2977
- */
2978
- const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
2979
- const ctx = initializeContext({
2980
- ...params,
2981
- processors
2982
- });
2983
- process$1(schema, ctx);
2984
- extractDefs(ctx, schema);
2985
- return finalize(ctx, schema);
2986
- };
2987
- const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
2988
- const { libraryOptions, target } = params ?? {};
2989
- const ctx = initializeContext({
2990
- ...libraryOptions ?? {},
2991
- target,
2992
- io,
2993
- processors
2994
- });
2995
- process$1(schema, ctx);
2996
- extractDefs(ctx, schema);
2997
- return finalize(ctx, schema);
2998
- };
2999
-
3000
- //#endregion
3001
- //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js
3002
- const formatMap = {
3003
- guid: "uuid",
3004
- url: "uri",
3005
- datetime: "date-time",
3006
- json_string: "json-string",
3007
- regex: ""
3008
- };
3009
- const stringProcessor = (schema, ctx, _json, _params) => {
3010
- const json = _json;
3011
- json.type = "string";
3012
- const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag;
3013
- if (typeof minimum === "number") json.minLength = minimum;
3014
- if (typeof maximum === "number") json.maxLength = maximum;
3015
- if (format) {
3016
- json.format = formatMap[format] ?? format;
3017
- if (json.format === "") delete json.format;
3018
- if (format === "time") delete json.format;
3019
- }
3020
- if (contentEncoding) json.contentEncoding = contentEncoding;
3021
- if (patterns && patterns.size > 0) {
3022
- const regexes = [...patterns];
3023
- if (regexes.length === 1) json.pattern = regexes[0].source;
3024
- else if (regexes.length > 1) json.allOf = [...regexes.map((regex) => ({
3025
- ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {},
3026
- pattern: regex.source
3027
- }))];
3028
- }
3029
- };
3030
- const neverProcessor = (_schema, _ctx, json, _params) => {
3031
- json.not = {};
3032
- };
3033
- const unknownProcessor = (_schema, _ctx, _json, _params) => {};
3034
- const enumProcessor = (schema, _ctx, json, _params) => {
3035
- const def = schema._zod.def;
3036
- const values = getEnumValues(def.entries);
3037
- if (values.every((v) => typeof v === "number")) json.type = "number";
3038
- if (values.every((v) => typeof v === "string")) json.type = "string";
3039
- json.enum = values;
3040
- };
3041
- const literalProcessor = (schema, ctx, json, _params) => {
3042
- const def = schema._zod.def;
3043
- const vals = [];
3044
- for (const val of def.values) if (val === void 0) {
3045
- if (ctx.unrepresentable === "throw") throw new Error("Literal `undefined` cannot be represented in JSON Schema");
3046
- } else if (typeof val === "bigint") if (ctx.unrepresentable === "throw") throw new Error("BigInt literals cannot be represented in JSON Schema");
3047
- else vals.push(Number(val));
3048
- else vals.push(val);
3049
- if (vals.length === 0) {} else if (vals.length === 1) {
3050
- const val = vals[0];
3051
- json.type = val === null ? "null" : typeof val;
3052
- if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") json.enum = [val];
3053
- else json.const = val;
3054
- } else {
3055
- if (vals.every((v) => typeof v === "number")) json.type = "number";
3056
- if (vals.every((v) => typeof v === "string")) json.type = "string";
3057
- if (vals.every((v) => typeof v === "boolean")) json.type = "boolean";
3058
- if (vals.every((v) => v === null)) json.type = "null";
3059
- json.enum = vals;
3060
- }
3061
- };
3062
- const customProcessor = (_schema, ctx, _json, _params) => {
3063
- if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
3064
- };
3065
- const transformProcessor = (_schema, ctx, _json, _params) => {
3066
- if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
3067
- };
3068
- const arrayProcessor = (schema, ctx, _json, params) => {
3069
- const json = _json;
3070
- const def = schema._zod.def;
3071
- const { minimum, maximum } = schema._zod.bag;
3072
- if (typeof minimum === "number") json.minItems = minimum;
3073
- if (typeof maximum === "number") json.maxItems = maximum;
3074
- json.type = "array";
3075
- json.items = process$1(def.element, ctx, {
3076
- ...params,
3077
- path: [...params.path, "items"]
3078
- });
3079
- };
3080
- const objectProcessor = (schema, ctx, _json, params) => {
3081
- const json = _json;
3082
- const def = schema._zod.def;
3083
- json.type = "object";
3084
- json.properties = {};
3085
- const shape = def.shape;
3086
- for (const key in shape) json.properties[key] = process$1(shape[key], ctx, {
3087
- ...params,
3088
- path: [
3089
- ...params.path,
3090
- "properties",
3091
- key
3092
- ]
3093
- });
3094
- const allKeys = new Set(Object.keys(shape));
3095
- const requiredKeys = new Set([...allKeys].filter((key) => {
3096
- const v = def.shape[key]._zod;
3097
- if (ctx.io === "input") return v.optin === void 0;
3098
- else return v.optout === void 0;
3099
- }));
3100
- if (requiredKeys.size > 0) json.required = Array.from(requiredKeys);
3101
- if (def.catchall?._zod.def.type === "never") json.additionalProperties = false;
3102
- else if (!def.catchall) {
3103
- if (ctx.io === "output") json.additionalProperties = false;
3104
- } else if (def.catchall) json.additionalProperties = process$1(def.catchall, ctx, {
3105
- ...params,
3106
- path: [...params.path, "additionalProperties"]
3107
- });
3108
- };
3109
- const unionProcessor = (schema, ctx, json, params) => {
3110
- const def = schema._zod.def;
3111
- const isExclusive = def.inclusive === false;
3112
- const options = def.options.map((x, i) => process$1(x, ctx, {
3113
- ...params,
3114
- path: [
3115
- ...params.path,
3116
- isExclusive ? "oneOf" : "anyOf",
3117
- i
3118
- ]
3119
- }));
3120
- if (isExclusive) json.oneOf = options;
3121
- else json.anyOf = options;
3122
- };
3123
- const intersectionProcessor = (schema, ctx, json, params) => {
3124
- const def = schema._zod.def;
3125
- const a = process$1(def.left, ctx, {
3126
- ...params,
3127
- path: [
3128
- ...params.path,
3129
- "allOf",
3130
- 0
3131
- ]
3132
- });
3133
- const b = process$1(def.right, ctx, {
3134
- ...params,
3135
- path: [
3136
- ...params.path,
3137
- "allOf",
3138
- 1
3139
- ]
3140
- });
3141
- const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
3142
- json.allOf = [...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b]];
3143
- };
3144
- const nullableProcessor = (schema, ctx, json, params) => {
3145
- const def = schema._zod.def;
3146
- const inner = process$1(def.innerType, ctx, params);
3147
- const seen = ctx.seen.get(schema);
3148
- if (ctx.target === "openapi-3.0") {
3149
- seen.ref = def.innerType;
3150
- json.nullable = true;
3151
- } else json.anyOf = [inner, { type: "null" }];
3152
- };
3153
- const nonoptionalProcessor = (schema, ctx, _json, params) => {
3154
- const def = schema._zod.def;
3155
- process$1(def.innerType, ctx, params);
3156
- const seen = ctx.seen.get(schema);
3157
- seen.ref = def.innerType;
3158
- };
3159
- const defaultProcessor = (schema, ctx, json, params) => {
3160
- const def = schema._zod.def;
3161
- process$1(def.innerType, ctx, params);
3162
- const seen = ctx.seen.get(schema);
3163
- seen.ref = def.innerType;
3164
- json.default = JSON.parse(JSON.stringify(def.defaultValue));
3165
- };
3166
- const prefaultProcessor = (schema, ctx, json, params) => {
3167
- const def = schema._zod.def;
3168
- process$1(def.innerType, ctx, params);
3169
- const seen = ctx.seen.get(schema);
3170
- seen.ref = def.innerType;
3171
- if (ctx.io === "input") json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
3172
- };
3173
- const catchProcessor = (schema, ctx, json, params) => {
3174
- const def = schema._zod.def;
3175
- process$1(def.innerType, ctx, params);
3176
- const seen = ctx.seen.get(schema);
3177
- seen.ref = def.innerType;
3178
- let catchValue;
3179
- try {
3180
- catchValue = def.catchValue(void 0);
3181
- } catch {
3182
- throw new Error("Dynamic catch values are not supported in JSON Schema");
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
3183
15
  }
3184
- json.default = catchValue;
3185
- };
3186
- const pipeProcessor = (schema, ctx, _json, params) => {
3187
- const def = schema._zod.def;
3188
- const innerType = ctx.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out;
3189
- process$1(innerType, ctx, params);
3190
- const seen = ctx.seen.get(schema);
3191
- seen.ref = innerType;
3192
- };
3193
- const readonlyProcessor = (schema, ctx, json, params) => {
3194
- const def = schema._zod.def;
3195
- process$1(def.innerType, ctx, params);
3196
- const seen = ctx.seen.get(schema);
3197
- seen.ref = def.innerType;
3198
- json.readOnly = true;
3199
- };
3200
- const optionalProcessor = (schema, ctx, _json, params) => {
3201
- const def = schema._zod.def;
3202
- process$1(def.innerType, ctx, params);
3203
- const seen = ctx.seen.get(schema);
3204
- seen.ref = def.innerType;
3205
- };
3206
-
3207
- //#endregion
3208
- //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js
3209
- const ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
3210
- $ZodISODateTime.init(inst, def);
3211
- ZodStringFormat.init(inst, def);
3212
- });
3213
- function datetime(params) {
3214
- return _isoDateTime(ZodISODateTime, params);
3215
- }
3216
- const ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
3217
- $ZodISODate.init(inst, def);
3218
- ZodStringFormat.init(inst, def);
3219
- });
3220
- function date(params) {
3221
- return _isoDate(ZodISODate, params);
3222
- }
3223
- const ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
3224
- $ZodISOTime.init(inst, def);
3225
- ZodStringFormat.init(inst, def);
3226
- });
3227
- function time(params) {
3228
- return _isoTime(ZodISOTime, params);
3229
- }
3230
- const ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
3231
- $ZodISODuration.init(inst, def);
3232
- ZodStringFormat.init(inst, def);
3233
- });
3234
- function duration(params) {
3235
- return _isoDuration(ZodISODuration, params);
3236
- }
3237
-
3238
- //#endregion
3239
- //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js
3240
- const initializer = (inst, issues) => {
3241
- $ZodError.init(inst, issues);
3242
- inst.name = "ZodError";
3243
- Object.defineProperties(inst, {
3244
- format: { value: (mapper) => formatError(inst, mapper) },
3245
- flatten: { value: (mapper) => flattenError(inst, mapper) },
3246
- addIssue: { value: (issue) => {
3247
- inst.issues.push(issue);
3248
- inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
3249
- } },
3250
- addIssues: { value: (issues) => {
3251
- inst.issues.push(...issues);
3252
- inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
3253
- } },
3254
- isEmpty: { get() {
3255
- return inst.issues.length === 0;
3256
- } }
3257
- });
16
+ return to;
3258
17
  };
3259
- const ZodError = $constructor("ZodError", initializer);
3260
- const ZodRealError = $constructor("ZodError", initializer, { Parent: Error });
3261
-
3262
- //#endregion
3263
- //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js
3264
- const parse = /* @__PURE__ */ _parse(ZodRealError);
3265
- const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
3266
- const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
3267
- const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
3268
- const encode = /* @__PURE__ */ _encode(ZodRealError);
3269
- const decode = /* @__PURE__ */ _decode(ZodRealError);
3270
- const encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError);
3271
- const decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError);
3272
- const safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError);
3273
- const safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError);
3274
- const safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
3275
- const safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
3276
-
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
3277
22
  //#endregion
3278
- //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js
3279
- const ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
3280
- $ZodType.init(inst, def);
3281
- Object.assign(inst["~standard"], { jsonSchema: {
3282
- input: createStandardJSONSchemaMethod(inst, "input"),
3283
- output: createStandardJSONSchemaMethod(inst, "output")
3284
- } });
3285
- inst.toJSONSchema = createToJSONSchemaMethod(inst, {});
3286
- inst.def = def;
3287
- inst.type = def.type;
3288
- Object.defineProperty(inst, "_def", { value: def });
3289
- inst.check = (...checks) => {
3290
- return inst.clone(mergeDefs(def, { checks: [...def.checks ?? [], ...checks.map((ch) => typeof ch === "function" ? { _zod: {
3291
- check: ch,
3292
- def: { check: "custom" },
3293
- onattach: []
3294
- } } : ch)] }), { parent: true });
3295
- };
3296
- inst.with = inst.check;
3297
- inst.clone = (def, params) => clone(inst, def, params);
3298
- inst.brand = () => inst;
3299
- inst.register = ((reg, meta) => {
3300
- reg.add(inst, meta);
3301
- return inst;
3302
- });
3303
- inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });
3304
- inst.safeParse = (data, params) => safeParse(inst, data, params);
3305
- inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
3306
- inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
3307
- inst.spa = inst.safeParseAsync;
3308
- inst.encode = (data, params) => encode(inst, data, params);
3309
- inst.decode = (data, params) => decode(inst, data, params);
3310
- inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params);
3311
- inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params);
3312
- inst.safeEncode = (data, params) => safeEncode(inst, data, params);
3313
- inst.safeDecode = (data, params) => safeDecode(inst, data, params);
3314
- inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params);
3315
- inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params);
3316
- inst.refine = (check, params) => inst.check(refine(check, params));
3317
- inst.superRefine = (refinement) => inst.check(superRefine(refinement));
3318
- inst.overwrite = (fn) => inst.check(_overwrite(fn));
3319
- inst.optional = () => optional(inst);
3320
- inst.exactOptional = () => exactOptional(inst);
3321
- inst.nullable = () => nullable(inst);
3322
- inst.nullish = () => optional(nullable(inst));
3323
- inst.nonoptional = (params) => nonoptional(inst, params);
3324
- inst.array = () => array(inst);
3325
- inst.or = (arg) => union([inst, arg]);
3326
- inst.and = (arg) => intersection(inst, arg);
3327
- inst.transform = (tx) => pipe(inst, transform(tx));
3328
- inst.default = (def) => _default(inst, def);
3329
- inst.prefault = (def) => prefault(inst, def);
3330
- inst.catch = (params) => _catch(inst, params);
3331
- inst.pipe = (target) => pipe(inst, target);
3332
- inst.readonly = () => readonly(inst);
3333
- inst.describe = (description) => {
3334
- const cl = inst.clone();
3335
- globalRegistry.add(cl, { description });
3336
- return cl;
3337
- };
3338
- Object.defineProperty(inst, "description", {
3339
- get() {
3340
- return globalRegistry.get(inst)?.description;
3341
- },
3342
- configurable: true
3343
- });
3344
- inst.meta = (...args) => {
3345
- if (args.length === 0) return globalRegistry.get(inst);
3346
- const cl = inst.clone();
3347
- globalRegistry.add(cl, args[0]);
3348
- return cl;
3349
- };
3350
- inst.isOptional = () => inst.safeParse(void 0).success;
3351
- inst.isNullable = () => inst.safeParse(null).success;
3352
- inst.apply = (fn) => fn(inst);
3353
- return inst;
3354
- });
3355
- /** @internal */
3356
- const _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
3357
- $ZodString.init(inst, def);
3358
- ZodType.init(inst, def);
3359
- inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params);
3360
- const bag = inst._zod.bag;
3361
- inst.format = bag.format ?? null;
3362
- inst.minLength = bag.minimum ?? null;
3363
- inst.maxLength = bag.maximum ?? null;
3364
- inst.regex = (...args) => inst.check(_regex(...args));
3365
- inst.includes = (...args) => inst.check(_includes(...args));
3366
- inst.startsWith = (...args) => inst.check(_startsWith(...args));
3367
- inst.endsWith = (...args) => inst.check(_endsWith(...args));
3368
- inst.min = (...args) => inst.check(_minLength(...args));
3369
- inst.max = (...args) => inst.check(_maxLength(...args));
3370
- inst.length = (...args) => inst.check(_length(...args));
3371
- inst.nonempty = (...args) => inst.check(_minLength(1, ...args));
3372
- inst.lowercase = (params) => inst.check(_lowercase(params));
3373
- inst.uppercase = (params) => inst.check(_uppercase(params));
3374
- inst.trim = () => inst.check(_trim());
3375
- inst.normalize = (...args) => inst.check(_normalize(...args));
3376
- inst.toLowerCase = () => inst.check(_toLowerCase());
3377
- inst.toUpperCase = () => inst.check(_toUpperCase());
3378
- inst.slugify = () => inst.check(_slugify());
3379
- });
3380
- const ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
3381
- $ZodString.init(inst, def);
3382
- _ZodString.init(inst, def);
3383
- inst.email = (params) => inst.check(_email(ZodEmail, params));
3384
- inst.url = (params) => inst.check(_url(ZodURL, params));
3385
- inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
3386
- inst.emoji = (params) => inst.check(_emoji(ZodEmoji, params));
3387
- inst.guid = (params) => inst.check(_guid(ZodGUID, params));
3388
- inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
3389
- inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
3390
- inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
3391
- inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
3392
- inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
3393
- inst.guid = (params) => inst.check(_guid(ZodGUID, params));
3394
- inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
3395
- inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
3396
- inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
3397
- inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
3398
- inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
3399
- inst.xid = (params) => inst.check(_xid(ZodXID, params));
3400
- inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
3401
- inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
3402
- inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
3403
- inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
3404
- inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
3405
- inst.e164 = (params) => inst.check(_e164(ZodE164, params));
3406
- inst.datetime = (params) => inst.check(datetime(params));
3407
- inst.date = (params) => inst.check(date(params));
3408
- inst.time = (params) => inst.check(time(params));
3409
- inst.duration = (params) => inst.check(duration(params));
3410
- });
3411
- const ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {
3412
- $ZodStringFormat.init(inst, def);
3413
- _ZodString.init(inst, def);
3414
- });
3415
- const ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
3416
- $ZodEmail.init(inst, def);
3417
- ZodStringFormat.init(inst, def);
3418
- });
3419
- const ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {
3420
- $ZodGUID.init(inst, def);
3421
- ZodStringFormat.init(inst, def);
3422
- });
3423
- const ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {
3424
- $ZodUUID.init(inst, def);
3425
- ZodStringFormat.init(inst, def);
3426
- });
3427
- const ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
3428
- $ZodURL.init(inst, def);
3429
- ZodStringFormat.init(inst, def);
3430
- });
3431
- const ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
3432
- $ZodEmoji.init(inst, def);
3433
- ZodStringFormat.init(inst, def);
3434
- });
3435
- const ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {
3436
- $ZodNanoID.init(inst, def);
3437
- ZodStringFormat.init(inst, def);
3438
- });
3439
- const ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {
3440
- $ZodCUID.init(inst, def);
3441
- ZodStringFormat.init(inst, def);
3442
- });
3443
- const ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {
3444
- $ZodCUID2.init(inst, def);
3445
- ZodStringFormat.init(inst, def);
3446
- });
3447
- const ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {
3448
- $ZodULID.init(inst, def);
3449
- ZodStringFormat.init(inst, def);
3450
- });
3451
- const ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {
3452
- $ZodXID.init(inst, def);
3453
- ZodStringFormat.init(inst, def);
3454
- });
3455
- const ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {
3456
- $ZodKSUID.init(inst, def);
3457
- ZodStringFormat.init(inst, def);
3458
- });
3459
- const ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {
3460
- $ZodIPv4.init(inst, def);
3461
- ZodStringFormat.init(inst, def);
3462
- });
3463
- const ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {
3464
- $ZodIPv6.init(inst, def);
3465
- ZodStringFormat.init(inst, def);
3466
- });
3467
- const ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {
3468
- $ZodCIDRv4.init(inst, def);
3469
- ZodStringFormat.init(inst, def);
3470
- });
3471
- const ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {
3472
- $ZodCIDRv6.init(inst, def);
3473
- ZodStringFormat.init(inst, def);
3474
- });
3475
- const ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {
3476
- $ZodBase64.init(inst, def);
3477
- ZodStringFormat.init(inst, def);
3478
- });
3479
- const ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {
3480
- $ZodBase64URL.init(inst, def);
3481
- ZodStringFormat.init(inst, def);
3482
- });
3483
- const ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {
3484
- $ZodE164.init(inst, def);
3485
- ZodStringFormat.init(inst, def);
3486
- });
3487
- const ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {
3488
- $ZodJWT.init(inst, def);
3489
- ZodStringFormat.init(inst, def);
3490
- });
3491
- const ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
3492
- $ZodUnknown.init(inst, def);
3493
- ZodType.init(inst, def);
3494
- inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params);
3495
- });
3496
- function unknown() {
3497
- return _unknown(ZodUnknown);
3498
- }
3499
- const ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
3500
- $ZodNever.init(inst, def);
3501
- ZodType.init(inst, def);
3502
- inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params);
3503
- });
3504
- function never(params) {
3505
- return _never(ZodNever, params);
3506
- }
3507
- const ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
3508
- $ZodArray.init(inst, def);
3509
- ZodType.init(inst, def);
3510
- inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params);
3511
- inst.element = def.element;
3512
- inst.min = (minLength, params) => inst.check(_minLength(minLength, params));
3513
- inst.nonempty = (params) => inst.check(_minLength(1, params));
3514
- inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params));
3515
- inst.length = (len, params) => inst.check(_length(len, params));
3516
- inst.unwrap = () => inst.element;
3517
- });
3518
- function array(element, params) {
3519
- return _array(ZodArray, element, params);
3520
- }
3521
- const ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
3522
- $ZodObjectJIT.init(inst, def);
3523
- ZodType.init(inst, def);
3524
- inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params);
3525
- defineLazy(inst, "shape", () => {
3526
- return def.shape;
3527
- });
3528
- inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
3529
- inst.catchall = (catchall) => inst.clone({
3530
- ...inst._zod.def,
3531
- catchall
3532
- });
3533
- inst.passthrough = () => inst.clone({
3534
- ...inst._zod.def,
3535
- catchall: unknown()
3536
- });
3537
- inst.loose = () => inst.clone({
3538
- ...inst._zod.def,
3539
- catchall: unknown()
3540
- });
3541
- inst.strict = () => inst.clone({
3542
- ...inst._zod.def,
3543
- catchall: never()
3544
- });
3545
- inst.strip = () => inst.clone({
3546
- ...inst._zod.def,
3547
- catchall: void 0
3548
- });
3549
- inst.extend = (incoming) => {
3550
- return extend(inst, incoming);
3551
- };
3552
- inst.safeExtend = (incoming) => {
3553
- return safeExtend(inst, incoming);
3554
- };
3555
- inst.merge = (other) => merge(inst, other);
3556
- inst.pick = (mask) => pick(inst, mask);
3557
- inst.omit = (mask) => omit(inst, mask);
3558
- inst.partial = (...args) => partial(ZodOptional, inst, args[0]);
3559
- inst.required = (...args) => required(ZodNonOptional, inst, args[0]);
3560
- });
3561
- const ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
3562
- $ZodUnion.init(inst, def);
3563
- ZodType.init(inst, def);
3564
- inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params);
3565
- inst.options = def.options;
3566
- });
3567
- function union(options, params) {
3568
- return new ZodUnion({
3569
- type: "union",
3570
- options,
3571
- ...normalizeParams(params)
3572
- });
3573
- }
3574
- const ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {
3575
- $ZodIntersection.init(inst, def);
3576
- ZodType.init(inst, def);
3577
- inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params);
3578
- });
3579
- function intersection(left, right) {
3580
- return new ZodIntersection({
3581
- type: "intersection",
3582
- left,
3583
- right
3584
- });
3585
- }
3586
- const ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
3587
- $ZodEnum.init(inst, def);
3588
- ZodType.init(inst, def);
3589
- inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params);
3590
- inst.enum = def.entries;
3591
- inst.options = Object.values(def.entries);
3592
- const keys = new Set(Object.keys(def.entries));
3593
- inst.extract = (values, params) => {
3594
- const newEntries = {};
3595
- for (const value of values) if (keys.has(value)) newEntries[value] = def.entries[value];
3596
- else throw new Error(`Key ${value} not found in enum`);
3597
- return new ZodEnum({
3598
- ...def,
3599
- checks: [],
3600
- ...normalizeParams(params),
3601
- entries: newEntries
3602
- });
3603
- };
3604
- inst.exclude = (values, params) => {
3605
- const newEntries = { ...def.entries };
3606
- for (const value of values) if (keys.has(value)) delete newEntries[value];
3607
- else throw new Error(`Key ${value} not found in enum`);
3608
- return new ZodEnum({
3609
- ...def,
3610
- checks: [],
3611
- ...normalizeParams(params),
3612
- entries: newEntries
3613
- });
3614
- };
3615
- });
3616
- function _enum(values, params) {
3617
- return new ZodEnum({
3618
- type: "enum",
3619
- entries: Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values,
3620
- ...normalizeParams(params)
3621
- });
23
+ let node_fs = require("node:fs");
24
+ node_fs = __toESM(node_fs);
25
+ let node_path = require("node:path");
26
+ node_path = __toESM(node_path);
27
+ let node_url = require("node:url");
28
+ let commander = require("commander");
29
+ let _rexeus_typeweaver_gen = require("@rexeus/typeweaver-gen");
30
+ let _rexeus_typeweaver_types = require("@rexeus/typeweaver-types");
31
+ _rexeus_typeweaver_types = __toESM(_rexeus_typeweaver_types);
32
+ let ejs = require("ejs");
33
+ ejs = __toESM(ejs);
34
+ let node_os = require("node:os");
35
+ node_os = __toESM(node_os);
36
+ let tsdown = require("tsdown");
37
+ let _rexeus_typeweaver_core = require("@rexeus/typeweaver-core");
38
+ //#region src/generators/formatter.ts
39
+ async function formatCode(outputDir, startDir) {
40
+ const format = await loadFormatter();
41
+ if (!format) return;
42
+ await formatDirectory(startDir ?? outputDir, format);
3622
43
  }
3623
- const ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
3624
- $ZodLiteral.init(inst, def);
3625
- ZodType.init(inst, def);
3626
- inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params);
3627
- inst.values = new Set(def.values);
3628
- Object.defineProperty(inst, "value", { get() {
3629
- if (def.values.length > 1) throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
3630
- return def.values[0];
3631
- } });
3632
- });
3633
- const ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
3634
- $ZodTransform.init(inst, def);
3635
- ZodType.init(inst, def);
3636
- inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params);
3637
- inst._zod.parse = (payload, _ctx) => {
3638
- if (_ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name);
3639
- payload.addIssue = (issue$1) => {
3640
- if (typeof issue$1 === "string") payload.issues.push(issue(issue$1, payload.value, def));
44
+ async function loadFormatter() {
45
+ try {
46
+ return (await import("oxfmt")).format;
47
+ } catch {
48
+ console.warn("oxfmt not installed - skipping formatting. Install with: npm install -D oxfmt");
49
+ return;
50
+ }
51
+ }
52
+ async function formatDirectory(targetDir, format) {
53
+ const contents = node_fs.default.readdirSync(targetDir, { withFileTypes: true });
54
+ for (const content of contents) if (content.isFile()) {
55
+ const filePath = node_path.default.join(targetDir, content.name);
56
+ const { code } = await format(filePath, node_fs.default.readFileSync(filePath, "utf8"));
57
+ node_fs.default.writeFileSync(filePath, code);
58
+ } else if (content.isDirectory()) await formatDirectory(node_path.default.join(targetDir, content.name), format);
59
+ }
60
+ //#endregion
61
+ //#region src/generators/indexFileGenerator.ts
62
+ function generateIndexFiles(templateDir, context) {
63
+ const templateFilePath = node_path.default.join(templateDir, "Index.ejs");
64
+ const template = node_fs.default.readFileSync(templateFilePath, "utf8");
65
+ const generatedFiles = context.getGeneratedFiles();
66
+ const groups = /* @__PURE__ */ new Map();
67
+ const rootFiles = /* @__PURE__ */ new Set();
68
+ const existingBarrels = /* @__PURE__ */ new Set();
69
+ for (const file of generatedFiles) {
70
+ const stripped = file.replace(/\.ts$/, "");
71
+ const firstSlash = stripped.indexOf("/");
72
+ if (firstSlash === -1) {
73
+ rootFiles.add(`./${stripped}`);
74
+ continue;
75
+ }
76
+ const firstSegment = stripped.slice(0, firstSlash);
77
+ if (firstSegment === "lib") {
78
+ const secondSlash = stripped.indexOf("/", firstSlash + 1);
79
+ const groupKey = secondSlash === -1 ? stripped : stripped.slice(0, secondSlash);
80
+ const entryName = stripped.slice(groupKey.length + 1);
81
+ if (entryName === "index") existingBarrels.add(groupKey);
3641
82
  else {
3642
- const _issue = issue$1;
3643
- if (_issue.fatal) _issue.continue = false;
3644
- _issue.code ?? (_issue.code = "custom");
3645
- _issue.input ?? (_issue.input = payload.value);
3646
- _issue.inst ?? (_issue.inst = inst);
3647
- payload.issues.push(issue(_issue));
83
+ if (!groups.has(groupKey)) groups.set(groupKey, /* @__PURE__ */ new Set());
84
+ groups.get(groupKey).add(`./${entryName}`);
85
+ }
86
+ } else {
87
+ const entryName = stripped.slice(firstSlash + 1);
88
+ if (entryName === "index") existingBarrels.add(firstSegment);
89
+ else {
90
+ if (!groups.has(firstSegment)) groups.set(firstSegment, /* @__PURE__ */ new Set());
91
+ groups.get(firstSegment).add(`./${entryName}`);
3648
92
  }
3649
- };
3650
- const output = def.transform(payload.value, payload);
3651
- if (output instanceof Promise) return output.then((output) => {
3652
- payload.value = output;
3653
- return payload;
3654
- });
3655
- payload.value = output;
3656
- return payload;
3657
- };
3658
- });
3659
- function transform(fn) {
3660
- return new ZodTransform({
3661
- type: "transform",
3662
- transform: fn
3663
- });
3664
- }
3665
- const ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
3666
- $ZodOptional.init(inst, def);
3667
- ZodType.init(inst, def);
3668
- inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params);
3669
- inst.unwrap = () => inst._zod.def.innerType;
3670
- });
3671
- function optional(innerType) {
3672
- return new ZodOptional({
3673
- type: "optional",
3674
- innerType
3675
- });
3676
- }
3677
- const ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => {
3678
- $ZodExactOptional.init(inst, def);
3679
- ZodType.init(inst, def);
3680
- inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params);
3681
- inst.unwrap = () => inst._zod.def.innerType;
3682
- });
3683
- function exactOptional(innerType) {
3684
- return new ZodExactOptional({
3685
- type: "optional",
3686
- innerType
3687
- });
3688
- }
3689
- const ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
3690
- $ZodNullable.init(inst, def);
3691
- ZodType.init(inst, def);
3692
- inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params);
3693
- inst.unwrap = () => inst._zod.def.innerType;
3694
- });
3695
- function nullable(innerType) {
3696
- return new ZodNullable({
3697
- type: "nullable",
3698
- innerType
3699
- });
3700
- }
3701
- const ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {
3702
- $ZodDefault.init(inst, def);
3703
- ZodType.init(inst, def);
3704
- inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params);
3705
- inst.unwrap = () => inst._zod.def.innerType;
3706
- inst.removeDefault = inst.unwrap;
3707
- });
3708
- function _default(innerType, defaultValue) {
3709
- return new ZodDefault({
3710
- type: "default",
3711
- innerType,
3712
- get defaultValue() {
3713
- return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
3714
- }
3715
- });
3716
- }
3717
- const ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
3718
- $ZodPrefault.init(inst, def);
3719
- ZodType.init(inst, def);
3720
- inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params);
3721
- inst.unwrap = () => inst._zod.def.innerType;
3722
- });
3723
- function prefault(innerType, defaultValue) {
3724
- return new ZodPrefault({
3725
- type: "prefault",
3726
- innerType,
3727
- get defaultValue() {
3728
- return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
3729
93
  }
3730
- });
3731
- }
3732
- const ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
3733
- $ZodNonOptional.init(inst, def);
3734
- ZodType.init(inst, def);
3735
- inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params);
3736
- inst.unwrap = () => inst._zod.def.innerType;
3737
- });
3738
- function nonoptional(innerType, params) {
3739
- return new ZodNonOptional({
3740
- type: "nonoptional",
3741
- innerType,
3742
- ...normalizeParams(params)
3743
- });
3744
- }
3745
- const ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
3746
- $ZodCatch.init(inst, def);
3747
- ZodType.init(inst, def);
3748
- inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params);
3749
- inst.unwrap = () => inst._zod.def.innerType;
3750
- inst.removeCatch = inst.unwrap;
3751
- });
3752
- function _catch(innerType, catchValue) {
3753
- return new ZodCatch({
3754
- type: "catch",
3755
- innerType,
3756
- catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
3757
- });
3758
- }
3759
- const ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
3760
- $ZodPipe.init(inst, def);
3761
- ZodType.init(inst, def);
3762
- inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params);
3763
- inst.in = def.in;
3764
- inst.out = def.out;
3765
- });
3766
- function pipe(in_, out) {
3767
- return new ZodPipe({
3768
- type: "pipe",
3769
- in: in_,
3770
- out
3771
- });
3772
- }
3773
- const ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
3774
- $ZodReadonly.init(inst, def);
3775
- ZodType.init(inst, def);
3776
- inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params);
3777
- inst.unwrap = () => inst._zod.def.innerType;
3778
- });
3779
- function readonly(innerType) {
3780
- return new ZodReadonly({
3781
- type: "readonly",
3782
- innerType
3783
- });
3784
- }
3785
- const ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
3786
- $ZodCustom.init(inst, def);
3787
- ZodType.init(inst, def);
3788
- inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params);
3789
- });
3790
- function refine(fn, _params = {}) {
3791
- return _refine(ZodCustom, fn, _params);
3792
- }
3793
- function superRefine(fn) {
3794
- return _superRefine(fn);
3795
- }
3796
- const describe = describe$1;
3797
- const meta = meta$1;
3798
-
3799
- //#endregion
3800
- //#region src/generators/errors/DuplicateOperationIdError.ts
3801
- var DuplicateOperationIdError = class extends Error {
3802
- constructor(operationId, firstFile, duplicateFile) {
3803
- super(`Duplicate operation ID '${operationId}' found.\n First defined in: \`${firstFile}\`\n Duplicate found in: \`${duplicateFile}\``);
3804
- this.operationId = operationId;
3805
- this.firstFile = firstFile;
3806
- this.duplicateFile = duplicateFile;
3807
94
  }
3808
- };
3809
-
3810
- //#endregion
3811
- //#region src/generators/errors/DuplicateResponseNameError.ts
3812
- var DuplicateResponseNameError = class extends Error {
3813
- constructor(responseName, firstFile, duplicateFile) {
3814
- super(`Duplicate response name '${responseName}' found.\n First defined in: \`${firstFile}\`\n Duplicate found in: \`${duplicateFile}\``);
3815
- this.responseName = responseName;
3816
- this.firstFile = firstFile;
3817
- this.duplicateFile = duplicateFile;
95
+ for (const [groupKey, entries] of groups) {
96
+ if (existingBarrels.has(groupKey)) continue;
97
+ const domainBarrelContent = ejs.default.render(template, { indexPaths: Array.from(entries).sort() });
98
+ const domainIndexPath = node_path.default.join(context.outputDir, groupKey, "index.ts");
99
+ node_fs.default.mkdirSync(node_path.default.dirname(domainIndexPath), { recursive: true });
100
+ node_fs.default.writeFileSync(domainIndexPath, domainBarrelContent);
3818
101
  }
3819
- };
3820
-
102
+ const rootIndexPaths = new Set(rootFiles);
103
+ for (const groupKey of groups.keys()) rootIndexPaths.add(`./${groupKey}`);
104
+ for (const barrelKey of existingBarrels) rootIndexPaths.add(`./${barrelKey}`);
105
+ const rootContent = ejs.default.render(template, { indexPaths: Array.from(rootIndexPaths).sort() });
106
+ node_fs.default.writeFileSync(node_path.default.join(context.outputDir, "index.ts"), rootContent);
107
+ }
3821
108
  //#endregion
3822
- //#region src/generators/errors/DuplicateRouteError.ts
3823
- var DuplicateRouteError = class extends Error {
3824
- constructor(path, method, firstOperationId, firstFile, duplicateOperationId, duplicateFile) {
3825
- super(`Duplicate route '${method} ${path}' found.\n First defined by operation '${firstOperationId}' in: \`${firstFile}\`\n Duplicate defined by operation '${duplicateOperationId}' in: \`${duplicateFile}\``);
3826
- this.path = path;
3827
- this.method = method;
3828
- this.firstOperationId = firstOperationId;
3829
- this.firstFile = firstFile;
3830
- this.duplicateOperationId = duplicateOperationId;
3831
- this.duplicateFile = duplicateFile;
109
+ //#region src/generators/errors/PluginLoadingFailure.ts
110
+ var PluginLoadingFailure = class PluginLoadingFailure extends Error {
111
+ constructor(pluginName, attempts) {
112
+ super(`Failed to load plugin '${pluginName}'`);
113
+ this.pluginName = pluginName;
114
+ this.attempts = attempts;
115
+ Object.setPrototypeOf(this, PluginLoadingFailure.prototype);
3832
116
  }
3833
117
  };
3834
-
3835
118
  //#endregion
3836
- //#region src/generators/DefinitionRegistry.ts
3837
- var DefinitionRegistry = class {
3838
- operationIds = /* @__PURE__ */ new Map();
3839
- responseNames = /* @__PURE__ */ new Map();
3840
- routes = /* @__PURE__ */ new Map();
3841
- registerOperation(operation, sourceFile) {
3842
- const existingFile = this.operationIds.get(operation.operationId);
3843
- if (existingFile) throw new DuplicateOperationIdError(operation.operationId, existingFile, sourceFile);
3844
- this.operationIds.set(operation.operationId, sourceFile);
3845
- const normalizedPath = this.normalizePath(operation.path);
3846
- const routeKey = `${operation.method} ${normalizedPath}`;
3847
- const existingRoute = this.routes.get(routeKey);
3848
- if (existingRoute) throw new DuplicateRouteError(operation.path, operation.method, existingRoute.operationId, existingRoute.file, operation.operationId, sourceFile);
3849
- this.routes.set(routeKey, {
3850
- operationId: operation.operationId,
3851
- file: sourceFile
119
+ //#region src/generators/pluginLoader.ts
120
+ async function loadPlugins(registry, requiredPlugins, strategies, config) {
121
+ for (const requiredPlugin of requiredPlugins) registry.register(requiredPlugin);
122
+ if (!config?.plugins) return;
123
+ const successful = [];
124
+ for (const plugin of config.plugins) {
125
+ let result;
126
+ if (typeof plugin === "string") result = await loadPlugin(plugin, strategies);
127
+ else result = await loadPlugin(plugin[0], strategies);
128
+ if (result.success === false) throw new PluginLoadingFailure(result.error.pluginName, result.error.attempts);
129
+ successful.push(result.value);
130
+ registry.register(result.value.plugin);
131
+ }
132
+ reportSuccessfulLoads(successful);
133
+ }
134
+ async function loadPlugin(pluginName, strategies) {
135
+ const possiblePaths = generatePluginPaths(pluginName, strategies);
136
+ const attempts = [];
137
+ for (const possiblePath of possiblePaths) try {
138
+ const pluginPackage = await import(possiblePath);
139
+ if (pluginPackage.default) return {
140
+ success: true,
141
+ value: {
142
+ plugin: new pluginPackage.default(),
143
+ source: possiblePath
144
+ }
145
+ };
146
+ attempts.push({
147
+ path: possiblePath,
148
+ error: "No default export found"
3852
149
  });
3853
- }
3854
- registerResponse(response, sourceFile) {
3855
- const existingFile = this.responseNames.get(response.name);
3856
- if (existingFile) throw new DuplicateResponseNameError(response.name, existingFile, sourceFile);
3857
- this.responseNames.set(response.name, sourceFile);
3858
- }
3859
- hasOperationId(operationId) {
3860
- return this.operationIds.has(operationId);
3861
- }
3862
- hasResponseName(name) {
3863
- return this.responseNames.has(name);
3864
- }
3865
- hasRoute(method, path) {
3866
- const routeKey = `${method} ${this.normalizePath(path)}`;
3867
- return this.routes.has(routeKey);
3868
- }
3869
- getOperationFile(operationId) {
3870
- return this.operationIds.get(operationId);
3871
- }
3872
- getResponseFile(name) {
3873
- return this.responseNames.get(name);
3874
- }
3875
- getRouteInfo(method, path) {
3876
- const routeKey = `${method} ${this.normalizePath(path)}`;
3877
- return this.routes.get(routeKey);
3878
- }
3879
- normalizePath(path) {
3880
- let paramIndex = 1;
3881
- return path.replace(/:([a-zA-Z0-9_]+)/g, () => {
3882
- return `:param${paramIndex++}`;
150
+ } catch (error) {
151
+ attempts.push({
152
+ path: possiblePath,
153
+ error: error instanceof Error ? error.message : String(error)
3883
154
  });
3884
155
  }
3885
- };
3886
-
3887
- //#endregion
3888
- //#region src/generators/errors/EmptyResponseArrayError.ts
3889
- var EmptyResponseArrayError = class extends Error {
3890
- constructor(operationId, file) {
3891
- super(`Operation '${operationId}' has no responses defined at \`${file}\`\n Operations must have at least one response definition`);
3892
- this.operationId = operationId;
3893
- this.file = file;
3894
- }
3895
- };
3896
-
3897
- //#endregion
3898
- //#region src/generators/errors/InvalidHttpMethodError.ts
3899
- var InvalidHttpMethodError = class extends Error {
3900
- constructor(operationId, method, file) {
3901
- const validMethods = Object.values(_rexeus_typeweaver_core.HttpMethod).join(", ");
3902
- super(`Invalid HTTP method '${method}' in operation '${operationId}' at \`${file}\`\n Valid methods: ${validMethods}`);
3903
- this.operationId = operationId;
3904
- this.method = method;
3905
- this.file = file;
156
+ return {
157
+ success: false,
158
+ error: {
159
+ pluginName,
160
+ attempts
161
+ }
162
+ };
163
+ }
164
+ function generatePluginPaths(pluginName, strategies) {
165
+ const paths = [];
166
+ for (const strategy of strategies) switch (strategy) {
167
+ case "npm":
168
+ paths.push(`@rexeus/typeweaver-${pluginName}`);
169
+ paths.push(`@rexeus/${pluginName}`);
170
+ break;
171
+ case "local":
172
+ paths.push(pluginName);
173
+ break;
174
+ }
175
+ return paths;
176
+ }
177
+ function reportSuccessfulLoads(successful) {
178
+ if (successful.length > 0) {
179
+ console.info(`Successfully loaded ${successful.length} plugin(s):`);
180
+ for (const result of successful) console.info(` - ${result.plugin.name} (from ${result.source})`);
181
+ }
182
+ }
183
+ //#endregion
184
+ //#region src/generators/spec/specBundler.ts
185
+ const WINDOWS_ABSOLUTE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
186
+ const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
187
+ function createWrapperImportSpecifier(wrapperFile, inputFile) {
188
+ const absoluteInputFile = resolveBundledInputFile(inputFile);
189
+ const useWindowsPathSemantics = usesWindowsPathSemantics(wrapperFile, absoluteInputFile);
190
+ const pathModule = useWindowsPathSemantics ? node_path.default.win32 : node_path.default.posix;
191
+ const wrapperDir = useWindowsPathSemantics ? pathModule.dirname(wrapperFile) : resolveRealFilePath(pathModule.dirname(wrapperFile));
192
+ const resolvedInputFile = useWindowsPathSemantics ? absoluteInputFile : resolveRealFilePath(absoluteInputFile);
193
+ const relativeInputFile = pathModule.relative(wrapperDir, resolvedInputFile).replaceAll(pathModule.sep, "/");
194
+ if (relativeInputFile.startsWith(".") || relativeInputFile.startsWith("..")) return relativeInputFile;
195
+ return `./${relativeInputFile}`;
196
+ }
197
+ async function bundle(config) {
198
+ const tempDir = node_fs.default.mkdtempSync(node_path.default.join(node_os.default.tmpdir(), "typeweaver-spec-loader-"));
199
+ const wrapperFile = node_path.default.join(tempDir, "spec-entrypoint.ts");
200
+ const bundledSpecFile = node_path.default.join(config.specOutputDir, "spec.js");
201
+ const wrapperImportSpecifier = createWrapperImportSpecifier(wrapperFile, config.inputFile);
202
+ node_fs.default.writeFileSync(wrapperFile, [
203
+ `import * as specModule from ${JSON.stringify(wrapperImportSpecifier)};`,
204
+ "const resolvedSpec =",
205
+ " Reflect.get(specModule, \"default\") ??",
206
+ " Reflect.get(specModule, \"spec\") ??",
207
+ " specModule;",
208
+ "",
209
+ "export default resolvedSpec;",
210
+ "export const spec = resolvedSpec;",
211
+ ""
212
+ ].join("\n"));
213
+ try {
214
+ await tsdown.Rolldown.build({
215
+ cwd: tempDir,
216
+ input: wrapperFile,
217
+ treeshake: true,
218
+ experimental: { attachDebugInfo: "none" },
219
+ external: (source) => {
220
+ if (source.startsWith("node:")) return true;
221
+ return !source.startsWith(".") && !node_path.default.isAbsolute(source);
222
+ },
223
+ output: {
224
+ file: bundledSpecFile,
225
+ format: "esm"
226
+ }
227
+ });
228
+ } finally {
229
+ node_fs.default.rmSync(tempDir, {
230
+ recursive: true,
231
+ force: true
232
+ });
3906
233
  }
3907
- };
3908
-
234
+ if (!node_fs.default.existsSync(bundledSpecFile)) throw new Error(`Failed to bundle spec entrypoint '${config.inputFile}' to '${bundledSpecFile}'.`);
235
+ return bundledSpecFile;
236
+ }
237
+ function resolveBundledInputFile(inputFile) {
238
+ if (node_path.default.isAbsolute(inputFile)) return inputFile;
239
+ if (WINDOWS_ABSOLUTE_PATH_PATTERN.test(inputFile)) return node_path.default.win32.normalize(inputFile);
240
+ if (WINDOWS_UNC_PATH_PATTERN.test(inputFile)) return node_path.default.win32.normalize(inputFile);
241
+ return node_path.default.resolve(inputFile);
242
+ }
243
+ function usesWindowsPathSemantics(...filePaths) {
244
+ return filePaths.some((filePath) => {
245
+ return WINDOWS_ABSOLUTE_PATH_PATTERN.test(filePath) || WINDOWS_UNC_PATH_PATTERN.test(filePath);
246
+ });
247
+ }
248
+ function resolveRealFilePath(filePath) {
249
+ if (!node_fs.default.existsSync(filePath)) return filePath;
250
+ return node_fs.default.realpathSync.native(filePath);
251
+ }
3909
252
  //#endregion
3910
- //#region src/generators/errors/InvalidPathParameterError.ts
3911
- var InvalidPathParameterError = class extends Error {
3912
- constructor(operationId, path, issue, file) {
3913
- super(`Invalid path parameters in operation '${operationId}' at \`${file}\`\n Path: ${path}\n Issue: ${issue}`);
3914
- this.operationId = operationId;
3915
- this.path = path;
3916
- this.issue = issue;
3917
- this.file = file;
253
+ //#region src/generators/spec/InvalidSpecEntrypointError.ts
254
+ var InvalidSpecEntrypointError = class extends Error {
255
+ constructor(specEntrypoint) {
256
+ super(`Spec entrypoint '${specEntrypoint}' must export a SpecDefinition as its default export, named 'spec' export, or module namespace.`);
257
+ this.name = "InvalidSpecEntrypointError";
3918
258
  }
3919
259
  };
3920
-
3921
260
  //#endregion
3922
- //#region src/generators/errors/InvalidSchemaError.ts
3923
- var InvalidSchemaError = class extends Error {
3924
- constructor(schemaType, definitionName, context, file) {
3925
- super(`Invalid ${schemaType} schema in ${context} '${definitionName}' at \`${file}\`. ${schemaType === "body" ? "Must be a Zod schema" : "Must be a Zod object schema"}.`);
3926
- this.schemaType = schemaType;
3927
- this.definitionName = definitionName;
3928
- this.context = context;
3929
- this.file = file;
3930
- }
261
+ //#region src/generators/spec/specGuards.ts
262
+ const validHttpStatusCodes = new Set(Object.values(_rexeus_typeweaver_core.HttpStatusCode).filter((statusCode) => typeof statusCode === "number"));
263
+ const isRecord = (value) => {
264
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3931
265
  };
3932
-
3933
- //#endregion
3934
- //#region src/generators/errors/InvalidSchemaShapeError.ts
3935
- var InvalidSchemaShapeError = class extends Error {
3936
- constructor(schemaType, definitionName, context, propertyName, invalidType, file) {
3937
- super(`Invalid ${schemaType} schema shape in ${context} '${definitionName}' at \`${file}\`\n Property '${propertyName}' has invalid type: ${invalidType}\n Allowed types: ${schemaType === "param" ? "string-based types (ZodString, ZodLiteral<string>, ZodEnum) or ZodOptional of these types" : "string-based types (ZodString, ZodLiteral<string>, ZodEnum), ZodOptional, or ZodArray of these types"}`);
3938
- this.schemaType = schemaType;
3939
- this.definitionName = definitionName;
3940
- this.context = context;
3941
- this.propertyName = propertyName;
3942
- this.invalidType = invalidType;
3943
- this.file = file;
3944
- }
266
+ const isResponseDefinition = (value) => {
267
+ if (!isRecord(value)) return false;
268
+ return typeof value.name === "string" && value.name.length > 0 && typeof value.description === "string" && value.description.length > 0 && validHttpStatusCodes.has(value.statusCode);
3945
269
  };
3946
-
3947
- //#endregion
3948
- //#region src/generators/errors/InvalidStatusCodeError.ts
3949
- var InvalidStatusCodeError = class extends Error {
3950
- constructor(statusCode, responseName, file) {
3951
- const validStatusCodes = Object.values(_rexeus_typeweaver_core.HttpStatusCode).join(", ");
3952
- super(`Invalid status code '${statusCode}' in response '${responseName}' at \`${file}\`\n Valid status codes: ${validStatusCodes}`);
3953
- this.statusCode = statusCode;
3954
- this.responseName = responseName;
3955
- this.file = file;
3956
- }
270
+ const isOperationDefinition = (value) => {
271
+ if (!isRecord(value) || !Array.isArray(value.responses)) return false;
272
+ return typeof value.operationId === "string" && value.operationId.length > 0 && typeof value.path === "string" && value.path.length > 0 && typeof value.summary === "string" && value.summary.length > 0 && Object.values(_rexeus_typeweaver_core.HttpMethod).includes(value.method) && isRecord(value.request) && value.responses.length > 0 && value.responses.every((response) => isResponseDefinition(response));
3957
273
  };
3958
-
3959
- //#endregion
3960
- //#region src/generators/errors/MissingRequiredFieldError.ts
3961
- var MissingRequiredFieldError = class extends Error {
3962
- constructor(entityType, entityName, missingField, file) {
3963
- super(`Missing required field '${missingField}' in ${entityType} '${entityName}' at \`${file}\``);
3964
- this.entityType = entityType;
3965
- this.entityName = entityName;
3966
- this.missingField = missingField;
3967
- this.file = file;
3968
- }
274
+ const isResourceDefinition = (value) => {
275
+ return isRecord(value) && Array.isArray(value.operations) && value.operations.every(isOperationDefinition);
3969
276
  };
3970
-
3971
- //#endregion
3972
- //#region src/generators/DefinitionValidator.ts
3973
- var DefinitionValidator = class {
3974
- registry;
3975
- constructor(registry) {
3976
- this.registry = registry ?? new DefinitionRegistry();
3977
- }
3978
- validateOperation(operation, sourceFile) {
3979
- this.registry.registerOperation(operation, sourceFile);
3980
- this.validateOperationRequiredFields(operation, sourceFile);
3981
- this.validateHttpMethod(operation, sourceFile);
3982
- if (operation.request) this.validateRequestSchemas(operation, sourceFile);
3983
- this.validateOperationResponses(operation, sourceFile);
3984
- this.validatePathParameters(operation, sourceFile);
3985
- }
3986
- validateResponse(response, sourceFile) {
3987
- this.registry.registerResponse(response, sourceFile);
3988
- this.validateResponseRequiredFields(response, sourceFile);
3989
- this.validateStatusCode(response, sourceFile);
3990
- this.validateResponseSchemas(response, sourceFile);
3991
- }
3992
- validateOperationRequiredFields(operation, sourceFile) {
3993
- if (!operation.operationId) throw new MissingRequiredFieldError("operation", "unknown", "operationId", sourceFile);
3994
- if (!operation.path) throw new MissingRequiredFieldError("operation", operation.operationId, "path", sourceFile);
3995
- if (!operation.method) throw new MissingRequiredFieldError("operation", operation.operationId, "method", sourceFile);
3996
- if (!operation.summary) throw new MissingRequiredFieldError("operation", operation.operationId, "summary", sourceFile);
3997
- }
3998
- validateHttpMethod(operation, sourceFile) {
3999
- if (!Object.values(_rexeus_typeweaver_core.HttpMethod).includes(operation.method)) throw new InvalidHttpMethodError(operation.operationId, operation.method, sourceFile);
4000
- }
4001
- validateRequestSchemas(operation, sourceFile) {
4002
- const request = operation.request;
4003
- if (request.header) this.validateSchema(request.header, "header", operation.operationId, "request", sourceFile);
4004
- if (request.query) this.validateSchema(request.query, "query", operation.operationId, "request", sourceFile);
4005
- if (request.body) this.validateSchema(request.body, "body", operation.operationId, "request", sourceFile);
4006
- if (request.param) this.validateSchema(request.param, "param", operation.operationId, "request", sourceFile);
4007
- }
4008
- validateOperationResponses(operation, sourceFile) {
4009
- if (!operation.responses || operation.responses.length === 0) throw new EmptyResponseArrayError(operation.operationId, sourceFile);
4010
- for (const response of operation.responses) {
4011
- if (response instanceof _rexeus_typeweaver_core.HttpResponseDefinition) continue;
4012
- this.validateResponse(response, sourceFile);
4013
- }
4014
- }
4015
- validateResponseRequiredFields(response, sourceFile) {
4016
- if (!response.name) throw new MissingRequiredFieldError("response", "unknown", "name", sourceFile);
4017
- if (response.statusCode === void 0 || response.statusCode === null) throw new MissingRequiredFieldError("response", response.name, "statusCode", sourceFile);
4018
- if (!response.description) throw new MissingRequiredFieldError("response", response.name, "description", sourceFile);
4019
- }
4020
- validateStatusCode(response, sourceFile) {
4021
- if (!Object.values(_rexeus_typeweaver_core.HttpStatusCode).includes(response.statusCode)) throw new InvalidStatusCodeError(response.statusCode, response.name, sourceFile);
4022
- }
4023
- validateResponseSchemas(response, sourceFile) {
4024
- if (response.header) this.validateSchema(response.header, "header", response.name, "response", sourceFile);
4025
- if (response.body) this.validateSchema(response.body, "body", response.name, "response", sourceFile);
4026
- }
4027
- validateSchema(schema, schemaType, definitionName, context, sourceFile) {
4028
- if (schemaType === "body") {
4029
- if (!(schema instanceof ZodType)) throw new InvalidSchemaError(schemaType, definitionName, context, sourceFile);
4030
- return;
4031
- }
4032
- if (schemaType === "query" || schemaType === "header") {
4033
- if (!(schema instanceof ZodObject) && !(schema instanceof ZodOptional && schema.unwrap() instanceof ZodObject)) throw new InvalidSchemaError(schemaType, definitionName, context, sourceFile);
4034
- this.validateHeaderOrQueryShape(schema, schemaType, definitionName, context, sourceFile);
4035
- }
4036
- if (schemaType === "param") {
4037
- if (!(schema instanceof ZodObject)) throw new InvalidSchemaError(schemaType, definitionName, context, sourceFile);
4038
- this.validateParamShape(schema, definitionName, sourceFile);
4039
- }
4040
- }
4041
- validatePathParameters(operation, sourceFile) {
4042
- const pathParamMatches = operation.path.matchAll(/:([a-zA-Z0-9_]+)/g);
4043
- const pathParamsSet = /* @__PURE__ */ new Set();
4044
- for (const match of pathParamMatches) {
4045
- const paramName = match[1];
4046
- if (pathParamsSet.has(paramName)) throw new InvalidPathParameterError(operation.operationId, operation.path, `Duplicate parameter name '${paramName}' in path`, sourceFile);
4047
- pathParamsSet.add(paramName);
4048
- }
4049
- const paramSchema = operation.request?.param;
4050
- if (pathParamsSet.size > 0 && !paramSchema) throw new InvalidPathParameterError(operation.operationId, operation.path, `Path contains parameters [${Array.from(pathParamsSet).join(", ")}] but request.param is not defined`, sourceFile);
4051
- if (paramSchema && paramSchema instanceof ZodObject) {
4052
- const paramShape = paramSchema.shape;
4053
- const paramKeys = new Set(Object.keys(paramShape));
4054
- for (const pathParam of pathParamsSet) if (!paramKeys.has(pathParam)) throw new InvalidPathParameterError(operation.operationId, operation.path, `Path parameter ':${pathParam}' is not defined in request.param`, sourceFile);
4055
- for (const paramKey of paramKeys) if (!pathParamsSet.has(paramKey)) throw new InvalidPathParameterError(operation.operationId, operation.path, `Parameter '${paramKey}' is defined in request.param but not used in the path`, sourceFile);
4056
- }
4057
- }
4058
- validateHeaderOrQueryShape(schema, schemaType, definitionName, context, sourceFile) {
4059
- const shape = schema instanceof ZodObject ? schema.shape : schema.unwrap().shape;
4060
- for (const [propName, propSchema] of Object.entries(shape)) if (!this.isValidHeaderOrQueryValue(propSchema)) throw new InvalidSchemaShapeError(schemaType, definitionName, context, propName, this.getZodTypeName(propSchema), sourceFile);
4061
- }
4062
- validateParamShape(schema, operationId, sourceFile) {
4063
- const shape = schema instanceof ZodObject ? schema.shape : schema.unwrap().shape;
4064
- for (const [propName, propSchema] of Object.entries(shape)) if (!this.isValidParamValue(propSchema)) throw new InvalidSchemaShapeError("param", operationId, "request", propName, this.getZodTypeName(propSchema), sourceFile);
4065
- }
4066
- isValidHeaderOrQueryValue(schema) {
4067
- if (this.isStringBasedType(schema)) return true;
4068
- if (schema instanceof ZodOptional) return this.isValidHeaderOrQueryValue(schema.unwrap());
4069
- if (schema instanceof ZodArray) return this.isStringBasedType(schema.element);
4070
- return false;
4071
- }
4072
- isValidParamValue(schema) {
4073
- if (this.isStringBasedType(schema)) return true;
4074
- if (schema instanceof ZodOptional) return this.isStringBasedType(schema.unwrap());
4075
- return false;
4076
- }
4077
- isStringBasedType(schema) {
4078
- if (schema instanceof ZodString) return true;
4079
- if (schema instanceof ZodLiteral && typeof schema.value === "string") return true;
4080
- if (schema instanceof ZodEnum) return true;
4081
- const typeName = schema.constructor.name;
4082
- if ([
4083
- "ZodULID",
4084
- "ZodUUID",
4085
- "ZodUUIDv4",
4086
- "ZodUUIDv7",
4087
- "ZodUUIDv8",
4088
- "ZodEmail",
4089
- "ZodURL",
4090
- "ZodCUID",
4091
- "ZodCUID2",
4092
- "ZodNanoID",
4093
- "ZodBase64",
4094
- "ZodBase64URL",
4095
- "ZodEmoji",
4096
- "ZodIPv4",
4097
- "ZodIPv6",
4098
- "ZodCIDRv4",
4099
- "ZodCIDRv6",
4100
- "ZodE164",
4101
- "ZodJWT",
4102
- "ZodASCII",
4103
- "ZodUTF8",
4104
- "ZodLowercase",
4105
- "ZodGUID",
4106
- "ZodISODate",
4107
- "ZodISOTime",
4108
- "ZodISODateTime",
4109
- "ZodISODuration"
4110
- ].includes(typeName)) return true;
4111
- if (schema._def && schema._def.typeName && schema._def.typeName.includes("String")) return true;
4112
- return false;
4113
- }
4114
- getZodTypeName(schema) {
4115
- const typeName = schema.constructor.name;
4116
- if (schema instanceof ZodOptional) return `ZodOptional<${this.getZodTypeName(schema.unwrap())}>`;
4117
- if (schema instanceof ZodArray) return `ZodArray<${this.getZodTypeName(schema.element)}>`;
4118
- if (schema instanceof ZodLiteral) return `ZodLiteral<${typeof schema.value}>`;
4119
- return typeName;
4120
- }
4121
- getRegistry() {
4122
- return this.registry;
4123
- }
277
+ const isSpecDefinition = (value) => {
278
+ if (!isRecord(value) || !isRecord(value.resources)) return false;
279
+ return Object.values(value.resources).every(isResourceDefinition);
4124
280
  };
4125
-
4126
281
  //#endregion
4127
- //#region src/generators/errors/InvalidSharedDirError.ts
4128
- var InvalidSharedDirError = class extends Error {
4129
- constructor(explanation) {
4130
- super("Invalid shared dir");
4131
- this.explanation = explanation;
4132
- }
4133
- };
4134
-
282
+ //#region src/generators/spec/specImporter.ts
283
+ async function importDefinition(bundledSpecFile) {
284
+ const specModule = await import((0, node_url.pathToFileURL)(bundledSpecFile).toString());
285
+ const definition = specModule.default ?? specModule.spec ?? specModule;
286
+ if (!isSpecDefinition(definition)) throw new InvalidSpecEntrypointError(bundledSpecFile);
287
+ return definition;
288
+ }
4135
289
  //#endregion
4136
- //#region src/generators/ResourceReader.ts
4137
- var ResourceReader = class {
4138
- constructor(config) {
4139
- this.config = config;
4140
- }
4141
- async getResources() {
4142
- const contents = node_fs.default.readdirSync(this.config.sourceDir, { withFileTypes: true });
4143
- const result = {
4144
- entityResources: {},
4145
- sharedResponseResources: []
4146
- };
4147
- const validator = new DefinitionValidator();
4148
- if (node_fs.default.existsSync(this.config.sharedSourceDir)) {
4149
- if (!node_fs.default.statSync(this.config.sharedSourceDir).isDirectory()) throw new InvalidSharedDirError(`'${this.config.sharedSourceDir}' is a file, not a directory`);
4150
- result.sharedResponseResources = await this.getSharedResponseResources(validator);
4151
- console.info(`Found '${result.sharedResponseResources.length}' shared responses in '${this.config.sharedSourceDir}'`);
4152
- } else console.info(`No shared directory found at '${this.config.sharedSourceDir}'`);
4153
- const normalizedSharedPath = node_path.default.resolve(this.config.sharedSourceDir);
4154
- for (const content of contents) {
4155
- if (!content.isDirectory()) {
4156
- console.info(`Skipping '${content.name}' as it is not a directory`);
4157
- continue;
4158
- }
4159
- const entityName = content.name;
4160
- const entitySourceDir = node_path.default.resolve(this.config.sourceDir, entityName);
4161
- if (entitySourceDir === normalizedSharedPath || normalizedSharedPath.startsWith(entitySourceDir + node_path.default.sep)) {
4162
- console.info(`Skipping '${content.name}' as it is or contains the shared directory`);
4163
- continue;
4164
- }
4165
- const responseResources = await this.getEntityResponseResources(entitySourceDir, entityName, validator);
4166
- const operationResources = await this.getEntityOperationResources(entitySourceDir, entityName, validator, [...result.sharedResponseResources, ...responseResources]);
4167
- result.entityResources[entityName] = {
4168
- operations: operationResources,
4169
- responses: responseResources
4170
- };
4171
- console.info(`Found '${operationResources.length}' operation definitions for entity '${entityName}'`);
4172
- if (responseResources.length > 0) console.info(`Found '${responseResources.length}' response definitions for entity '${entityName}'`);
4173
- }
4174
- return result;
4175
- }
4176
- scanDirectoryRecursively(dir) {
4177
- const files = [];
4178
- const contents = node_fs.default.readdirSync(dir, { withFileTypes: true });
4179
- for (const content of contents) {
4180
- const fullPath = node_path.default.join(dir, content.name);
4181
- if (content.isDirectory()) files.push(...this.scanDirectoryRecursively(fullPath));
4182
- else if (content.isFile() && content.name.endsWith(".ts")) files.push(fullPath);
4183
- }
4184
- return files;
4185
- }
4186
- async getSharedResponseResources(validator) {
4187
- const files = this.scanDirectoryRecursively(this.config.sharedSourceDir);
4188
- const sharedResponseResources = [];
4189
- for (const sourceFile of files) {
4190
- const sourceFileName = node_path.default.basename(sourceFile);
4191
- const definition = await import(sourceFile);
4192
- if (!definition.default) {
4193
- console.info(`Skipping '${sourceFile}' as it does not have a default export`);
4194
- continue;
4195
- }
4196
- if (!(definition.default instanceof _rexeus_typeweaver_core.HttpResponseDefinition)) {
4197
- console.info(`Skipping '${sourceFile}' as it is not an instance of HttpResponseDefinition`);
4198
- continue;
4199
- }
4200
- validator.validateResponse(definition.default, sourceFile);
4201
- const outputDir = this.config.sharedOutputDir;
4202
- const outputFileName = `${definition.default.name}Response.ts`;
4203
- const outputFile = node_path.default.join(outputDir, outputFileName);
4204
- sharedResponseResources.push({
4205
- ...definition.default,
4206
- sourceDir: this.config.sharedSourceDir,
4207
- sourceFile,
4208
- sourceFileName,
4209
- outputFile,
4210
- outputFileName,
4211
- outputDir
4212
- });
4213
- }
4214
- return sharedResponseResources;
4215
- }
4216
- async getEntityOperationResources(sourceDir, entityName, validator, referencedResponses) {
4217
- const files = this.scanDirectoryRecursively(sourceDir);
4218
- const definitions = [];
4219
- for (const sourceFile of files) {
4220
- const sourceFileName = node_path.default.basename(sourceFile);
4221
- const definition = await import(sourceFile);
4222
- if (!definition.default) {
4223
- console.info(`Skipping '${sourceFile}' as it does not have a default export`);
4224
- continue;
4225
- }
4226
- if (!(definition.default instanceof _rexeus_typeweaver_core.HttpOperationDefinition)) {
4227
- console.info(`Skipping '${sourceFile}' as it is not an instance of HttpOperationDefinition`);
4228
- continue;
4229
- }
4230
- validator.validateOperation(definition.default, sourceFile);
4231
- const { operationId } = definition.default;
4232
- const outputDir = node_path.default.join(this.config.outputDir, entityName);
4233
- const outputRequestFileName = `${operationId}Request.ts`;
4234
- const outputRequestFile = node_path.default.join(outputDir, outputRequestFileName);
4235
- const outputResponseFileName = `${operationId}Response.ts`;
4236
- const outputResponseFile = node_path.default.join(outputDir, outputResponseFileName);
4237
- const outputRequestValidationFileName = `${operationId}RequestValidator.ts`;
4238
- const outputRequestValidationFile = node_path.default.join(outputDir, outputRequestValidationFileName);
4239
- const outputResponseValidationFileName = `${operationId}ResponseValidator.ts`;
4240
- const outputResponseValidationFile = node_path.default.join(outputDir, outputResponseValidationFileName);
4241
- const outputClientFileName = `${operationId}Client.ts`;
4242
- const outputClientFile = node_path.default.join(outputDir, outputClientFileName);
4243
- const operationResource = {
4244
- sourceDir,
4245
- sourceFile,
4246
- sourceFileName,
4247
- definition: {
4248
- ...definition.default,
4249
- responses: []
4250
- },
4251
- outputDir,
4252
- entityName,
4253
- outputRequestFile,
4254
- outputResponseFile,
4255
- outputResponseValidationFile,
4256
- outputRequestValidationFile,
4257
- outputRequestFileName,
4258
- outputRequestValidationFileName,
4259
- outputResponseFileName,
4260
- outputResponseValidationFileName,
4261
- outputClientFile,
4262
- outputClientFileName
4263
- };
4264
- if (!definition.default.responses) throw new Error(`Operation '${operationId}' does not have any responses`);
4265
- for (const response of definition.default.responses) if (referencedResponses.some((ref) => ref.name === response.name)) {
4266
- const referencedResponse = {
4267
- ...response,
4268
- statusCodeName: _rexeus_typeweaver_core.HttpStatusCodeNameMap[response.statusCode],
4269
- isReference: true
4270
- };
4271
- operationResource.definition.responses.push(referencedResponse);
4272
- } else {
4273
- const extendedResponse = {
4274
- ...response,
4275
- statusCodeName: _rexeus_typeweaver_core.HttpStatusCodeNameMap[response.statusCode],
4276
- isReference: false
4277
- };
4278
- operationResource.definition.responses.push(extendedResponse);
4279
- }
4280
- definitions.push(operationResource);
4281
- }
4282
- return definitions;
4283
- }
4284
- async getEntityResponseResources(sourceDir, entityName, validator) {
4285
- const files = this.scanDirectoryRecursively(sourceDir);
4286
- const responseResources = [];
4287
- for (const sourceFile of files) {
4288
- const sourceFileName = node_path.default.basename(sourceFile);
4289
- const definition = await import(sourceFile);
4290
- if (!definition.default) continue;
4291
- if (!(definition.default instanceof _rexeus_typeweaver_core.HttpResponseDefinition)) continue;
4292
- validator.validateResponse(definition.default, sourceFile);
4293
- const outputFileName = `${definition.default.name}Response.ts`;
4294
- const outputFile = node_path.default.join(this.config.outputDir, entityName, outputFileName);
4295
- responseResources.push({
4296
- ...definition.default,
4297
- sourceDir,
4298
- sourceFile,
4299
- sourceFileName,
4300
- outputFile,
4301
- outputFileName,
4302
- outputDir: node_path.default.join(this.config.outputDir, entityName),
4303
- entityName
4304
- });
4305
- }
4306
- return responseResources;
4307
- }
4308
- };
4309
-
290
+ //#region src/generators/specLoader.ts
291
+ async function loadSpec(config) {
292
+ node_fs.default.mkdirSync(config.specOutputDir, { recursive: true });
293
+ const bundledSpecFile = await bundle(config);
294
+ writeSpecDeclarationFile(config.specOutputDir);
295
+ const definition = await importDefinition(bundledSpecFile);
296
+ return {
297
+ definition,
298
+ normalizedSpec: (0, _rexeus_typeweaver_gen.normalizeSpec)(definition)
299
+ };
300
+ }
301
+ function writeSpecDeclarationFile(specOutputDir) {
302
+ node_fs.default.writeFileSync(`${specOutputDir}/spec.d.ts`, [
303
+ "import type { SpecDefinition } from \"@rexeus/typeweaver-core\";",
304
+ "declare const _default: SpecDefinition;",
305
+ "export default _default;",
306
+ "export declare const spec: SpecDefinition;",
307
+ ""
308
+ ].join("\n"));
309
+ }
4310
310
  //#endregion
4311
311
  //#region src/generators/Generator.ts
4312
312
  const moduleDir$1 = node_path.default.dirname((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
@@ -4317,32 +317,24 @@ const moduleDir$1 = node_path.default.dirname((0, node_url.fileURLToPath)(requir
4317
317
  var Generator = class {
4318
318
  coreDir = "@rexeus/typeweaver-core";
4319
319
  templateDir = node_path.default.join(moduleDir$1, "templates");
4320
- registry;
4321
- contextBuilder;
4322
- pluginLoader;
4323
- indexFileGenerator;
4324
- definitionCompiler;
4325
- resourceReader = null;
4326
- formatter = null;
4327
- inputDir = "";
4328
- sharedInputDir = "";
320
+ registry = (0, _rexeus_typeweaver_gen.createPluginRegistry)();
321
+ contextBuilder = (0, _rexeus_typeweaver_gen.createPluginContextBuilder)();
322
+ requiredPlugins;
323
+ strategies;
324
+ inputFile = "";
4329
325
  outputDir = "";
4330
- sourceDir = "";
4331
- sharedSourceDir = "";
4332
- sharedOutputDir = "";
4333
- constructor(registry, contextBuilder, pluginLoader, indexFileGenerator, requiredPlugins = [new _rexeus_typeweaver_types.default()]) {
4334
- this.registry = registry ?? new _rexeus_typeweaver_gen.PluginRegistry();
4335
- this.contextBuilder = contextBuilder ?? new _rexeus_typeweaver_gen.PluginContextBuilder();
4336
- this.pluginLoader = pluginLoader ?? new PluginLoader(this.registry, requiredPlugins);
4337
- this.indexFileGenerator = indexFileGenerator ?? new IndexFileGenerator(this.templateDir);
4338
- this.definitionCompiler = new DefinitionCompiler();
326
+ specOutputDir = "";
327
+ responsesOutputDir = "";
328
+ constructor(requiredPlugins = [new _rexeus_typeweaver_types.default()], strategies) {
329
+ this.requiredPlugins = requiredPlugins;
330
+ this.strategies = strategies ?? ["npm", "local"];
4339
331
  }
4340
332
  /**
4341
333
  * Generate code using the plugin system
4342
334
  */
4343
- async generate(definitionDir, outputDir, config) {
335
+ async generate(specFile, outputDir, config) {
4344
336
  console.info("Starting generation...");
4345
- this.initializeDirectories(definitionDir, outputDir, config?.shared);
337
+ this.initializeDirectories(specFile, outputDir);
4346
338
  if (config?.clean ?? true) {
4347
339
  console.info("Cleaning output directory...");
4348
340
  node_fs.default.rmSync(this.outputDir, {
@@ -4351,66 +343,52 @@ var Generator = class {
4351
343
  });
4352
344
  }
4353
345
  node_fs.default.mkdirSync(this.outputDir, { recursive: true });
4354
- node_fs.default.mkdirSync(this.sharedOutputDir, { recursive: true });
4355
- console.info(`Copying definitions from '${this.inputDir}' to '${this.sourceDir}'...`);
4356
- node_fs.default.cpSync(this.inputDir, this.sourceDir, {
4357
- recursive: true,
4358
- filter: (src) => {
4359
- return src.endsWith(".ts") || src.endsWith(".js") || src.endsWith(".json") || src.endsWith(".mjs") || src.endsWith(".cjs") || node_fs.default.statSync(src).isDirectory();
4360
- }
4361
- });
4362
- await this.pluginLoader.loadPlugins(config);
4363
- this.resourceReader = new ResourceReader({
4364
- sourceDir: this.sourceDir,
4365
- outputDir: this.outputDir,
4366
- sharedSourceDir: this.sharedSourceDir,
4367
- sharedOutputDir: this.sharedOutputDir
346
+ node_fs.default.mkdirSync(this.responsesOutputDir, { recursive: true });
347
+ node_fs.default.mkdirSync(this.specOutputDir, { recursive: true });
348
+ await loadPlugins(this.registry, this.requiredPlugins, this.strategies, config);
349
+ console.info(`Bundling spec from '${this.inputFile}' to '${this.specOutputDir}'...`);
350
+ let { normalizedSpec } = await loadSpec({
351
+ inputFile: this.inputFile,
352
+ specOutputDir: this.specOutputDir
4368
353
  });
4369
- this.formatter = new Formatter(this.outputDir);
4370
- console.info("Reading definitions...");
4371
- let resources = await this.resourceReader.getResources();
4372
354
  const pluginContext = this.contextBuilder.createPluginContext({
4373
355
  outputDir: this.outputDir,
4374
- inputDir: this.sourceDir,
356
+ inputDir: node_path.default.dirname(this.inputFile),
4375
357
  config: config ?? {}
4376
358
  });
4377
359
  console.info("Initializing plugins...");
4378
360
  for (const registration of this.registry.getAll()) if (registration.plugin.initialize) await registration.plugin.initialize(pluginContext);
4379
361
  console.info("Collecting resources...");
4380
- for (const registration of this.registry.getAll()) if (registration.plugin.collectResources) resources = await registration.plugin.collectResources(resources);
362
+ for (const registration of this.registry.getAll()) if (registration.plugin.collectResources) normalizedSpec = await registration.plugin.collectResources(normalizedSpec);
4381
363
  const generatorContext = this.contextBuilder.createGeneratorContext({
4382
364
  outputDir: this.outputDir,
4383
- inputDir: this.sourceDir,
365
+ inputDir: node_path.default.dirname(this.inputFile),
4384
366
  config: config ?? {},
4385
- resources,
367
+ normalizedSpec,
4386
368
  templateDir: this.templateDir,
4387
- coreDir: this.coreDir
369
+ coreDir: this.coreDir,
370
+ responsesOutputDir: this.responsesOutputDir,
371
+ specOutputDir: this.specOutputDir
4388
372
  });
4389
373
  console.info("Generating code...");
4390
374
  for (const registration of this.registry.getAll()) {
4391
375
  console.info(`Running plugin: ${registration.plugin.name}`);
4392
376
  if (registration.plugin.generate) await registration.plugin.generate(generatorContext);
4393
377
  }
4394
- this.indexFileGenerator.generate(generatorContext);
378
+ generateIndexFiles(this.templateDir, generatorContext);
4395
379
  console.info("Finalizing plugins...");
4396
380
  for (const registration of this.registry.getAll()) if (registration.plugin.finalize) await registration.plugin.finalize(pluginContext);
4397
- console.info("Compiling definitions...");
4398
- this.definitionCompiler.compileInPlace(this.sourceDir);
4399
- if (config?.format ?? true) await this.formatter.formatCode();
381
+ if (config?.format ?? true) await formatCode(this.outputDir);
4400
382
  console.info("Generation complete!");
4401
383
  console.info(`Generated files: ${this.contextBuilder.getGeneratedFiles().length}`);
4402
384
  }
4403
- initializeDirectories(definitionDir, outputDir, sharedDir) {
4404
- this.inputDir = definitionDir;
4405
- this.sharedInputDir = sharedDir ?? node_path.default.join(definitionDir, "shared");
385
+ initializeDirectories(specFile, outputDir) {
386
+ this.inputFile = specFile;
4406
387
  this.outputDir = outputDir;
4407
- this.sharedOutputDir = node_path.default.join(outputDir, "shared");
4408
- this.sourceDir = node_path.default.join(this.outputDir, "definition");
4409
- const inputToSharedDirRelative = node_path.default.relative(this.inputDir, this.sharedInputDir);
4410
- this.sharedSourceDir = node_path.default.join(this.sourceDir, inputToSharedDirRelative);
388
+ this.responsesOutputDir = node_path.default.join(outputDir, "responses");
389
+ this.specOutputDir = node_path.default.join(this.outputDir, "spec");
4411
390
  }
4412
391
  };
4413
-
4414
392
  //#endregion
4415
393
  //#region src/cli.ts
4416
394
  const moduleDir = node_path.default.dirname((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
@@ -4418,7 +396,7 @@ const packageJson = JSON.parse(node_fs.default.readFileSync(node_path.default.jo
4418
396
  const program = new commander.Command();
4419
397
  const execDir = process.cwd();
4420
398
  program.name("@rexeus/typeweaver").description("Type-safe API framework with code generation for TypeScript").version(packageJson.version);
4421
- program.command("generate").description("Generate types, validators, and clients from API definitions").option("-i, --input <inputDir>", "path to definition directory").option("-o, --output <outputDir>", "output directory for generated files").option("-s, --shared <path>", "path to shared definitions directory").option("-c, --config <configFile>", "path to configuration file").option("-p, --plugins <plugins>", "comma-separated list of plugins to use").option("--format", "format generated code with oxfmt (default: true)").option("--no-format", "disable code formatting").option("--clean", "clean output directory before generation (default: true)").option("--no-clean", "disable cleaning output directory").action(async (options) => {
399
+ program.command("generate").description("Generate types, validators, and clients from an API spec").option("-i, --input <inputPath>", "path to spec entrypoint file").option("-o, --output <outputDir>", "output directory for generated files").option("-c, --config <configFile>", "path to configuration file").option("-p, --plugins <plugins>", "comma-separated list of plugins to use").option("--format", "format generated code with oxfmt (default: true)").option("--no-format", "disable code formatting").option("--clean", "clean output directory before generation (default: true)").option("--no-clean", "disable cleaning output directory").action(async (options) => {
4422
400
  let config = {};
4423
401
  if (options.config) {
4424
402
  const configPath = node_path.default.isAbsolute(options.config) ? options.config : node_path.default.join(execDir, options.config);
@@ -4432,27 +410,24 @@ program.command("generate").description("Generate types, validators, and clients
4432
410
  process.exit(1);
4433
411
  }
4434
412
  }
4435
- const inputDir = options.input ?? config.input;
413
+ const inputPath = options.input ?? config.input;
4436
414
  const outputDir = options.output ?? config.output;
4437
- const sharedDir = options.shared ?? config.shared;
4438
- if (!inputDir) throw new Error("No input directory provided. Use --input or specify in config file.");
415
+ if (!inputPath) throw new Error("No input spec entrypoint provided. Use --input or specify in config file.");
4439
416
  if (!outputDir) throw new Error("No output directory provided. Use --output or specify in config file.");
4440
- const resolvedInputDir = node_path.default.isAbsolute(inputDir) ? inputDir : node_path.default.join(execDir, inputDir);
417
+ const resolvedInputPath = node_path.default.isAbsolute(inputPath) ? inputPath : node_path.default.join(execDir, inputPath);
4441
418
  const resolvedOutputDir = node_path.default.isAbsolute(outputDir) ? outputDir : node_path.default.join(execDir, outputDir);
4442
419
  const finalConfig = {
4443
- input: resolvedInputDir,
420
+ input: resolvedInputPath,
4444
421
  output: resolvedOutputDir,
4445
- shared: sharedDir ? node_path.default.isAbsolute(sharedDir) ? sharedDir : node_path.default.join(execDir, sharedDir) : void 0,
4446
422
  format: options.format ?? config.format ?? true,
4447
423
  clean: options.clean ?? config.clean ?? true
4448
424
  };
4449
425
  if (options.plugins) finalConfig.plugins = options.plugins.split(",").map((p) => p.trim());
4450
426
  else if (config.plugins) finalConfig.plugins = config.plugins;
4451
- return new Generator().generate(resolvedInputDir, resolvedOutputDir, finalConfig);
427
+ return new Generator().generate(resolvedInputPath, resolvedOutputDir, finalConfig);
4452
428
  });
4453
429
  program.command("init").description("Initialize a new typeweaver project (coming soon)").action(() => {
4454
430
  console.log("The init command is coming soon!");
4455
431
  });
4456
432
  program.parse(process.argv);
4457
-
4458
- //#endregion
433
+ //#endregion