@kubb/plugin-zod 5.0.0-alpha.9 → 5.0.0-beta.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +25 -7
  3. package/dist/index.cjs +1129 -105
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.ts +369 -4
  6. package/dist/index.js +1116 -105
  7. package/dist/index.js.map +1 -1
  8. package/extension.yaml +505 -0
  9. package/package.json +43 -73
  10. package/src/components/Operations.tsx +25 -18
  11. package/src/components/Zod.tsx +21 -121
  12. package/src/constants.ts +5 -0
  13. package/src/generators/zodGenerator.tsx +213 -166
  14. package/src/index.ts +11 -2
  15. package/src/plugin.ts +67 -156
  16. package/src/printers/printerZod.ts +368 -0
  17. package/src/printers/printerZodMini.ts +313 -0
  18. package/src/resolvers/resolverZod.ts +57 -0
  19. package/src/types.ts +130 -115
  20. package/src/utils.ts +222 -0
  21. package/dist/components-B7zUFnAm.cjs +0 -890
  22. package/dist/components-B7zUFnAm.cjs.map +0 -1
  23. package/dist/components-eECfXVou.js +0 -842
  24. package/dist/components-eECfXVou.js.map +0 -1
  25. package/dist/components.cjs +0 -4
  26. package/dist/components.d.ts +0 -56
  27. package/dist/components.js +0 -2
  28. package/dist/generators-BjPDdJUz.cjs +0 -301
  29. package/dist/generators-BjPDdJUz.cjs.map +0 -1
  30. package/dist/generators-lTWPS6oN.js +0 -290
  31. package/dist/generators-lTWPS6oN.js.map +0 -1
  32. package/dist/generators.cjs +0 -4
  33. package/dist/generators.d.ts +0 -508
  34. package/dist/generators.js +0 -2
  35. package/dist/templates/ToZod.source.cjs +0 -7
  36. package/dist/templates/ToZod.source.cjs.map +0 -1
  37. package/dist/templates/ToZod.source.d.ts +0 -7
  38. package/dist/templates/ToZod.source.js +0 -6
  39. package/dist/templates/ToZod.source.js.map +0 -1
  40. package/dist/types-CoCoOc2u.d.ts +0 -172
  41. package/src/components/index.ts +0 -2
  42. package/src/generators/index.ts +0 -2
  43. package/src/generators/operationsGenerator.tsx +0 -50
  44. package/src/parser.ts +0 -909
  45. package/src/templates/ToZod.source.ts +0 -4
  46. package/templates/ToZod.ts +0 -61
package/dist/index.cjs CHANGED
@@ -1,12 +1,17 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_components = require("./components-B7zUFnAm.cjs");
3
- const require_generators = require("./generators-BjPDdJUz.cjs");
4
- const require_templates_ToZod_source = require("./templates/ToZod.source.cjs");
5
- let node_path = require("node:path");
6
- node_path = require_components.__toESM(node_path);
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ //#region \0rolldown/runtime.js
6
+ var __defProp = Object.defineProperty;
7
+ var __name = (target, value) => __defProp(target, "name", {
8
+ value,
9
+ configurable: true
10
+ });
11
+ //#endregion
7
12
  let _kubb_core = require("@kubb/core");
8
- let _kubb_plugin_oas = require("@kubb/plugin-oas");
9
- let _kubb_plugin_ts = require("@kubb/plugin-ts");
13
+ let _kubb_renderer_jsx = require("@kubb/renderer-jsx");
14
+ let _kubb_renderer_jsx_jsx_runtime = require("@kubb/renderer-jsx/jsx-runtime");
10
15
  //#region ../../internals/utils/src/casing.ts
11
16
  /**
12
17
  * Shared implementation for camelCase and PascalCase conversion.
@@ -26,9 +31,12 @@ function toCamelOrPascal(text, pascal) {
26
31
  * Splits `text` on `.` and applies `transformPart` to each segment.
27
32
  * The last segment receives `isLast = true`, all earlier segments receive `false`.
28
33
  * Segments are joined with `/` to form a file path.
34
+ *
35
+ * Only splits on dots followed by a letter so that version numbers
36
+ * embedded in operationIds (e.g. `v2025.0`) are kept intact.
29
37
  */
30
38
  function applyToFileParts(text, transformPart) {
31
- const parts = text.split(".");
39
+ const parts = text.split(/\.(?=[a-zA-Z])/);
32
40
  return parts.map((part, i) => transformPart(part, i === parts.length - 1)).join("/");
33
41
  }
34
42
  /**
@@ -62,117 +70,1133 @@ function pascalCase(text, { isFile, prefix = "", suffix = "" } = {}) {
62
70
  return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
63
71
  }
64
72
  //#endregion
73
+ //#region ../../internals/utils/src/string.ts
74
+ /**
75
+ * Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
76
+ * Returns the string unchanged when no balanced quote pair is found.
77
+ *
78
+ * @example
79
+ * trimQuotes('"hello"') // 'hello'
80
+ * trimQuotes('hello') // 'hello'
81
+ */
82
+ function trimQuotes(text) {
83
+ if (text.length >= 2) {
84
+ const first = text[0];
85
+ const last = text[text.length - 1];
86
+ if (first === "\"" && last === "\"" || first === "'" && last === "'" || first === "`" && last === "`") return text.slice(1, -1);
87
+ }
88
+ return text;
89
+ }
90
+ //#endregion
91
+ //#region ../../internals/utils/src/object.ts
92
+ /**
93
+ * Serializes a primitive value to a JSON string literal, stripping any surrounding quote characters first.
94
+ *
95
+ * @example
96
+ * stringify('hello') // '"hello"'
97
+ * stringify('"hello"') // '"hello"'
98
+ */
99
+ function stringify(value) {
100
+ if (value === void 0 || value === null) return "\"\"";
101
+ return JSON.stringify(trimQuotes(value.toString()));
102
+ }
103
+ /**
104
+ * Converts a plain object into a multiline key-value string suitable for embedding in generated code.
105
+ * Nested objects are recursively stringified with indentation.
106
+ *
107
+ * @example
108
+ * stringifyObject({ foo: 'bar', nested: { a: 1 } })
109
+ * // 'foo: bar,\nnested: {\n a: 1\n }'
110
+ */
111
+ function stringifyObject(value) {
112
+ return Object.entries(value).map(([key, val]) => {
113
+ if (val !== null && typeof val === "object") return `${key}: {\n ${stringifyObject(val)}\n }`;
114
+ return `${key}: ${val}`;
115
+ }).filter(Boolean).join(",\n");
116
+ }
117
+ //#endregion
118
+ //#region ../../internals/utils/src/regexp.ts
119
+ /**
120
+ * Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
121
+ * Inline flags expressed as `^(?im)` prefixes are extracted and applied to the resulting expression.
122
+ * Pass `null` as the second argument to emit a `/pattern/flags` literal instead.
123
+ *
124
+ * @example
125
+ * toRegExpString('^(?im)foo') // → 'new RegExp("foo", "im")'
126
+ * toRegExpString('^(?im)foo', null) // → '/foo/im'
127
+ */
128
+ function toRegExpString(text, func = "RegExp") {
129
+ const raw = trimQuotes(text);
130
+ const match = raw.match(/^\^(\(\?([igmsuy]+)\))/i);
131
+ const replacementTarget = match?.[1] ?? "";
132
+ const matchedFlags = match?.[2];
133
+ const cleaned = raw.replace(/^\\?\//, "").replace(/\\?\/$/, "").replace(replacementTarget, "");
134
+ const { source, flags } = new RegExp(cleaned, matchedFlags);
135
+ if (func === null) return `/${source}/${flags}`;
136
+ return `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : ""})`;
137
+ }
138
+ //#endregion
139
+ //#region src/components/Operations.tsx
140
+ function Operations({ name, operations }) {
141
+ const operationsJSON = operations.reduce((prev, acc) => {
142
+ prev[`"${acc.node.operationId}"`] = acc.data;
143
+ return prev;
144
+ }, {});
145
+ const pathsJSON = operations.reduce((prev, acc) => {
146
+ prev[`"${acc.node.path}"`] = {
147
+ ...prev[`"${acc.node.path}"`] ?? {},
148
+ [acc.node.method]: `operations["${acc.node.operationId}"]`
149
+ };
150
+ return prev;
151
+ }, {});
152
+ return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsxs)(_kubb_renderer_jsx_jsx_runtime.Fragment, { children: [
153
+ /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
154
+ name: "OperationSchema",
155
+ isExportable: true,
156
+ isIndexable: true,
157
+ children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Type, {
158
+ name: "OperationSchema",
159
+ export: true,
160
+ children: `{
161
+ readonly request: z.ZodTypeAny | undefined;
162
+ readonly parameters: {
163
+ readonly path: z.ZodTypeAny | undefined;
164
+ readonly query: z.ZodTypeAny | undefined;
165
+ readonly header: z.ZodTypeAny | undefined;
166
+ };
167
+ readonly responses: {
168
+ readonly [status: number]: z.ZodTypeAny;
169
+ readonly default: z.ZodTypeAny;
170
+ };
171
+ readonly errors: {
172
+ readonly [status: number]: z.ZodTypeAny;
173
+ };
174
+ }`
175
+ })
176
+ }),
177
+ /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
178
+ name: "OperationsMap",
179
+ isExportable: true,
180
+ isIndexable: true,
181
+ children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Type, {
182
+ name: "OperationsMap",
183
+ export: true,
184
+ children: "Record<string, OperationSchema>"
185
+ })
186
+ }),
187
+ /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
188
+ name,
189
+ isExportable: true,
190
+ isIndexable: true,
191
+ children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Const, {
192
+ export: true,
193
+ name,
194
+ asConst: true,
195
+ children: `{${stringifyObject(operationsJSON)}}`
196
+ })
197
+ }),
198
+ /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
199
+ name: "paths",
200
+ isExportable: true,
201
+ isIndexable: true,
202
+ children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Const, {
203
+ export: true,
204
+ name: "paths",
205
+ asConst: true,
206
+ children: `{${stringifyObject(pathsJSON)}}`
207
+ })
208
+ })
209
+ ] });
210
+ }
211
+ //#endregion
212
+ //#region src/components/Zod.tsx
213
+ function Zod({ name, node, printer, inferTypeName }) {
214
+ const output = printer.print(node);
215
+ if (!output) return;
216
+ return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsxs)(_kubb_renderer_jsx_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
217
+ name,
218
+ isExportable: true,
219
+ isIndexable: true,
220
+ children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Const, {
221
+ export: true,
222
+ name,
223
+ children: output
224
+ })
225
+ }), inferTypeName && /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
226
+ name: inferTypeName,
227
+ isExportable: true,
228
+ isIndexable: true,
229
+ isTypeOnly: true,
230
+ children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Type, {
231
+ export: true,
232
+ name: inferTypeName,
233
+ children: `z.infer<typeof ${name}>`
234
+ })
235
+ })] });
236
+ }
237
+ //#endregion
238
+ //#region src/constants.ts
239
+ /**
240
+ * Import paths that use a namespace import (`import * as z from '...'`).
241
+ * All other import paths use a named import (`import { z } from '...'`).
242
+ */
243
+ const ZOD_NAMESPACE_IMPORTS = new Set(["zod", "zod/mini"]);
244
+ //#endregion
245
+ //#region src/utils.ts
246
+ /**
247
+ * Returns `true` when the given coercion option enables coercion for the specified type.
248
+ */
249
+ function shouldCoerce(coercion, type) {
250
+ if (coercion === void 0 || coercion === false) return false;
251
+ if (coercion === true) return true;
252
+ return !!coercion[type];
253
+ }
254
+ /**
255
+ * Collects all resolved schema names for an operation's parameters and responses
256
+ * into a single lookup object, useful for building imports and type references.
257
+ */
258
+ function buildSchemaNames(node, { params, resolver }) {
259
+ const pathParam = params.find((p) => p.in === "path");
260
+ const queryParam = params.find((p) => p.in === "query");
261
+ const headerParam = params.find((p) => p.in === "header");
262
+ const responses = {};
263
+ const errors = {};
264
+ for (const res of node.responses) {
265
+ const name = resolver.resolveResponseStatusName(node, res.statusCode);
266
+ const statusNum = Number(res.statusCode);
267
+ if (!Number.isNaN(statusNum)) {
268
+ responses[statusNum] = name;
269
+ if (statusNum >= 400) errors[statusNum] = name;
270
+ }
271
+ }
272
+ responses["default"] = resolver.resolveResponseName(node);
273
+ return {
274
+ request: node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : void 0,
275
+ parameters: {
276
+ path: pathParam ? resolver.resolvePathParamsName(node, pathParam) : void 0,
277
+ query: queryParam ? resolver.resolveQueryParamsName(node, queryParam) : void 0,
278
+ header: headerParam ? resolver.resolveHeaderParamsName(node, headerParam) : void 0
279
+ },
280
+ responses,
281
+ errors
282
+ };
283
+ }
284
+ /**
285
+ * Format a default value as a code-level literal.
286
+ * Objects become `{}`, primitives become their string representation, strings are quoted.
287
+ */
288
+ function formatDefault(value) {
289
+ if (typeof value === "string") return stringify(value);
290
+ if (typeof value === "object" && value !== null) return "{}";
291
+ return String(value ?? "");
292
+ }
293
+ /**
294
+ * Format a primitive enum/literal value.
295
+ * Strings are quoted; numbers and booleans are emitted raw.
296
+ */
297
+ function formatLiteral(v) {
298
+ if (typeof v === "string") return stringify(v);
299
+ return String(v);
300
+ }
301
+ /**
302
+ * Build `.min()` / `.max()` / `.gt()` / `.lt()` constraint chains for numbers
303
+ * using the standard chainable Zod v4 API.
304
+ */
305
+ function numberConstraints({ min, max, exclusiveMinimum, exclusiveMaximum, multipleOf }) {
306
+ return [
307
+ min !== void 0 ? `.min(${min})` : "",
308
+ max !== void 0 ? `.max(${max})` : "",
309
+ exclusiveMinimum !== void 0 ? `.gt(${exclusiveMinimum})` : "",
310
+ exclusiveMaximum !== void 0 ? `.lt(${exclusiveMaximum})` : "",
311
+ multipleOf !== void 0 ? `.multipleOf(${multipleOf})` : ""
312
+ ].join("");
313
+ }
314
+ /**
315
+ * Build `.min()` / `.max()` / `.regex()` chains for strings/arrays
316
+ * using the standard chainable Zod v4 API.
317
+ */
318
+ function lengthConstraints({ min, max, pattern }) {
319
+ return [
320
+ min !== void 0 ? `.min(${min})` : "",
321
+ max !== void 0 ? `.max(${max})` : "",
322
+ pattern !== void 0 ? `.regex(${toRegExpString(pattern, null)})` : ""
323
+ ].join("");
324
+ }
325
+ /**
326
+ * Build `.check(z.minimum(), z.maximum())` for `zod/mini` numeric constraints.
327
+ */
328
+ function numberChecksMini({ min, max, exclusiveMinimum, exclusiveMaximum, multipleOf }) {
329
+ const checks = [];
330
+ if (min !== void 0) checks.push(`z.minimum(${min})`);
331
+ if (max !== void 0) checks.push(`z.maximum(${max})`);
332
+ if (exclusiveMinimum !== void 0) checks.push(`z.minimum(${exclusiveMinimum}, { exclusive: true })`);
333
+ if (exclusiveMaximum !== void 0) checks.push(`z.maximum(${exclusiveMaximum}, { exclusive: true })`);
334
+ if (multipleOf !== void 0) checks.push(`z.multipleOf(${multipleOf})`);
335
+ return checks.length ? `.check(${checks.join(", ")})` : "";
336
+ }
337
+ /**
338
+ * Build `.check(z.minLength(), z.maxLength(), z.regex())` for `zod/mini` length constraints.
339
+ */
340
+ function lengthChecksMini({ min, max, pattern }) {
341
+ const checks = [];
342
+ if (min !== void 0) checks.push(`z.minLength(${min})`);
343
+ if (max !== void 0) checks.push(`z.maxLength(${max})`);
344
+ if (pattern !== void 0) checks.push(`z.regex(${toRegExpString(pattern, null)})`);
345
+ return checks.length ? `.check(${checks.join(", ")})` : "";
346
+ }
347
+ /**
348
+ * Apply nullable / optional / nullish modifiers and an optional `.describe()` call
349
+ * to a schema value string using the chainable Zod v4 API.
350
+ */
351
+ function applyModifiers({ value, nullable, optional, nullish, defaultValue, description }) {
352
+ let result = value;
353
+ if (nullish || nullable && optional) result = `${result}.nullish()`;
354
+ else if (optional) result = `${result}.optional()`;
355
+ else if (nullable) result = `${result}.nullable()`;
356
+ if (defaultValue !== void 0) result = `${result}.default(${formatDefault(defaultValue)})`;
357
+ if (description) result = `${result}.describe(${stringify(description)})`;
358
+ return result;
359
+ }
360
+ /**
361
+ * Apply nullable / optional / nullish modifiers using the functional `zod/mini` API
362
+ * (`z.nullable()`, `z.optional()`, `z.nullish()`).
363
+ */
364
+ function applyMiniModifiers({ value, nullable, optional, nullish, defaultValue }) {
365
+ let result = value;
366
+ if (nullish) result = `z.nullish(${result})`;
367
+ else {
368
+ if (nullable) result = `z.nullable(${result})`;
369
+ if (optional) result = `z.optional(${result})`;
370
+ }
371
+ if (defaultValue !== void 0) result = `z._default(${result}, ${formatDefault(defaultValue)})`;
372
+ return result;
373
+ }
374
+ //#endregion
375
+ //#region src/printers/printerZod.ts
376
+ function strictOneOfMember$1(member, node) {
377
+ if (node.type === "object" && node.additionalProperties === void 0) return `${member}.strict()`;
378
+ if (node.type === "ref") {
379
+ if (member.startsWith("z.lazy(")) return member;
380
+ const schema = _kubb_core.ast.syncSchemaRef(node);
381
+ if (schema.type === "object" && (schema.additionalProperties === void 0 || schema.additionalProperties === false)) return `${member}.strict()`;
382
+ }
383
+ return member;
384
+ }
385
+ __name(strictOneOfMember$1, "strictOneOfMember");
386
+ /**
387
+ * Zod v4 printer built with `definePrinter`.
388
+ *
389
+ * Converts a `SchemaNode` AST into a Zod v4 code string using the chainable API
390
+ * (`.optional()`, `.nullable()`, `.omit()`, etc.). For improved tree-shaking, see {@link printerZodMini}.
391
+ *
392
+ * @example Chainable API
393
+ * ```ts
394
+ * const printer = printerZod({ coercion: false })
395
+ * const code = printer.print(stringNode) // "z.string()"
396
+ * ```
397
+ */
398
+ const printerZod = _kubb_core.ast.definePrinter((options) => {
399
+ return {
400
+ name: "zod",
401
+ options,
402
+ nodes: {
403
+ any: () => "z.any()",
404
+ unknown: () => "z.unknown()",
405
+ void: () => "z.void()",
406
+ never: () => "z.never()",
407
+ boolean: () => "z.boolean()",
408
+ null: () => "z.null()",
409
+ string(node) {
410
+ return `${shouldCoerce(this.options.coercion, "strings") ? "z.coerce.string()" : "z.string()"}${lengthConstraints(node)}`;
411
+ },
412
+ number(node) {
413
+ return `${shouldCoerce(this.options.coercion, "numbers") ? "z.coerce.number()" : "z.number()"}${numberConstraints(node)}`;
414
+ },
415
+ integer(node) {
416
+ return `${shouldCoerce(this.options.coercion, "numbers") ? "z.coerce.number().int()" : "z.int()"}${numberConstraints(node)}`;
417
+ },
418
+ bigint() {
419
+ return shouldCoerce(this.options.coercion, "numbers") ? "z.coerce.bigint()" : "z.bigint()";
420
+ },
421
+ date(node) {
422
+ if (node.representation === "string") return "z.iso.date()";
423
+ return shouldCoerce(this.options.coercion, "dates") ? "z.coerce.date()" : "z.date()";
424
+ },
425
+ datetime(node) {
426
+ const offset = node.offset || this.options.dateType === "stringOffset";
427
+ const local = node.local || this.options.dateType === "stringLocal";
428
+ if (offset) return "z.iso.datetime({ offset: true })";
429
+ if (local) return "z.iso.datetime({ local: true })";
430
+ return "z.iso.datetime()";
431
+ },
432
+ time(node) {
433
+ if (node.representation === "string") return "z.iso.time()";
434
+ return shouldCoerce(this.options.coercion, "dates") ? "z.coerce.date()" : "z.date()";
435
+ },
436
+ uuid(node) {
437
+ return `${this.options.guidType === "guid" ? "z.guid()" : "z.uuid()"}${lengthConstraints(node)}`;
438
+ },
439
+ email(node) {
440
+ return `z.email()${lengthConstraints(node)}`;
441
+ },
442
+ url(node) {
443
+ return `z.url()${lengthConstraints(node)}`;
444
+ },
445
+ ipv4: () => "z.ipv4()",
446
+ ipv6: () => "z.ipv6()",
447
+ blob: () => "z.instanceof(File)",
448
+ enum(node) {
449
+ const nonNullValues = (node.namedEnumValues?.map((v) => v.value) ?? node.enumValues ?? []).filter((v) => v !== null);
450
+ if (node.namedEnumValues?.length) {
451
+ const literals = nonNullValues.map((v) => `z.literal(${formatLiteral(v)})`);
452
+ if (literals.length === 1) return literals[0];
453
+ return `z.union([${literals.join(", ")}])`;
454
+ }
455
+ return `z.enum([${nonNullValues.map(formatLiteral).join(", ")}])`;
456
+ },
457
+ ref(node) {
458
+ if (!node.name) return void 0;
459
+ const refName = node.ref ? _kubb_core.ast.extractRefName(node.ref) ?? node.name : node.name;
460
+ const resolvedName = node.ref ? this.options.resolver?.default(refName, "function") ?? refName : node.name;
461
+ if (node.ref && this.options.cyclicSchemas?.has(refName)) return `z.lazy(() => ${resolvedName})`;
462
+ return resolvedName;
463
+ },
464
+ object(node) {
465
+ let result = `z.object({\n ${node.properties.map((prop) => {
466
+ const { name: propName, schema } = prop;
467
+ const meta = _kubb_core.ast.syncSchemaRef(schema);
468
+ const isNullable = meta.nullable;
469
+ const isOptional = schema.optional;
470
+ const isNullish = schema.nullish;
471
+ const hasSelfRef = this.options.cyclicSchemas != null && _kubb_core.ast.containsCircularRef(schema, { circularSchemas: this.options.cyclicSchemas });
472
+ const savedCyclicSchemas = this.options.cyclicSchemas;
473
+ if (hasSelfRef) this.options.cyclicSchemas = void 0;
474
+ const baseOutput = this.transform(schema) ?? this.transform(_kubb_core.ast.createSchema({ type: "unknown" }));
475
+ if (hasSelfRef) this.options.cyclicSchemas = savedCyclicSchemas;
476
+ const wrappedOutput = this.options.wrapOutput ? this.options.wrapOutput({
477
+ output: baseOutput,
478
+ schema
479
+ }) || baseOutput : baseOutput;
480
+ let descriptionToApply = meta.description;
481
+ if (schema.type !== "ref" && meta.type === "ref") descriptionToApply = void 0;
482
+ const value = applyModifiers({
483
+ value: wrappedOutput,
484
+ nullable: isNullable,
485
+ optional: isOptional,
486
+ nullish: isNullish,
487
+ defaultValue: meta.default,
488
+ description: descriptionToApply
489
+ });
490
+ if (hasSelfRef) return `get "${propName}"() { return ${value} }`;
491
+ return `"${propName}": ${value}`;
492
+ }).join(",\n ")}\n })`;
493
+ if (node.additionalProperties && node.additionalProperties !== true) {
494
+ const catchallType = this.transform(node.additionalProperties);
495
+ if (catchallType) result += `.catchall(${catchallType})`;
496
+ } else if (node.additionalProperties === true) result += `.catchall(${this.transform(_kubb_core.ast.createSchema({ type: "unknown" }))})`;
497
+ else if (node.additionalProperties === false) result += ".strict()";
498
+ return result;
499
+ },
500
+ array(node) {
501
+ let result = `z.array(${(node.items ?? []).map((item) => this.transform(item)).filter(Boolean).join(", ") || this.transform(_kubb_core.ast.createSchema({ type: "unknown" }))})${lengthConstraints(node)}`;
502
+ if (node.unique) result += `.refine(items => new Set(items).size === items.length, { message: "Array entries must be unique" })`;
503
+ return result;
504
+ },
505
+ tuple(node) {
506
+ return `z.tuple([${(node.items ?? []).map((item) => this.transform(item)).filter(Boolean).join(", ")}])`;
507
+ },
508
+ union(node) {
509
+ const nodeMembers = node.members ?? [];
510
+ const members = nodeMembers.map((memberNode) => {
511
+ const member = this.transform(memberNode);
512
+ return member && node.strategy === "one" ? strictOneOfMember$1(member, memberNode) : member;
513
+ }).filter(Boolean);
514
+ if (members.length === 0) return "";
515
+ if (members.length === 1) return members[0];
516
+ if (node.discriminatorPropertyName && !nodeMembers.some((m) => m.type === "intersection")) return `z.discriminatedUnion(${stringify(node.discriminatorPropertyName)}, [${members.join(", ")}])`;
517
+ return `z.union([${members.join(", ")}])`;
518
+ },
519
+ intersection(node) {
520
+ const members = node.members ?? [];
521
+ if (members.length === 0) return "";
522
+ const [first, ...rest] = members;
523
+ if (!first) return "";
524
+ let base = this.transform(first);
525
+ if (!base) return "";
526
+ for (const member of rest) {
527
+ if (member.primitive === "string") {
528
+ const c = lengthConstraints(_kubb_core.ast.narrowSchema(member, "string") ?? {});
529
+ if (c) {
530
+ base += c;
531
+ continue;
532
+ }
533
+ } else if (member.primitive === "number" || member.primitive === "integer") {
534
+ const c = numberConstraints(_kubb_core.ast.narrowSchema(member, "number") ?? _kubb_core.ast.narrowSchema(member, "integer") ?? {});
535
+ if (c) {
536
+ base += c;
537
+ continue;
538
+ }
539
+ } else if (member.primitive === "array") {
540
+ const c = lengthConstraints(_kubb_core.ast.narrowSchema(member, "array") ?? {});
541
+ if (c) {
542
+ base += c;
543
+ continue;
544
+ }
545
+ }
546
+ const transformed = this.transform(member);
547
+ if (transformed) base = `${base}.and(${transformed})`;
548
+ }
549
+ return base;
550
+ },
551
+ ...options.nodes
552
+ },
553
+ print(node) {
554
+ const { keysToOmit } = this.options;
555
+ let base = this.transform(node);
556
+ if (!base) return null;
557
+ const meta = _kubb_core.ast.syncSchemaRef(node);
558
+ if (keysToOmit?.length && meta.primitive === "object" && !(meta.type === "union" && meta.discriminatorPropertyName)) {
559
+ const lazyMatch = base.match(/^z\.lazy\(\(\)\s*=>\s*(.+)\)$/);
560
+ if (lazyMatch) base = `z.lazy(() => ${lazyMatch[1]}.omit({ ${keysToOmit.map((k) => `"${k}": true`).join(", ")} }))`;
561
+ else base = `${base}.omit({ ${keysToOmit.map((k) => `"${k}": true`).join(", ")} })`;
562
+ }
563
+ return applyModifiers({
564
+ value: base,
565
+ nullable: meta.nullable,
566
+ optional: meta.optional,
567
+ nullish: meta.nullish,
568
+ defaultValue: meta.default,
569
+ description: meta.description
570
+ });
571
+ }
572
+ };
573
+ });
574
+ //#endregion
575
+ //#region src/printers/printerZodMini.ts
576
+ function strictOneOfMember(member, node) {
577
+ if (node.type === "object" && (node.additionalProperties === void 0 || node.additionalProperties === false)) return member.replace(/^z\.object\(/, "z.strictObject(");
578
+ return member;
579
+ }
580
+ /**
581
+ * Zod v4 **Mini** printer built with `definePrinter`.
582
+ *
583
+ * Converts a `SchemaNode` AST into a Zod v4 code string using the functional API
584
+ * (`z.optional(z.string())`) for improved tree-shaking. See {@link printerZod} for the chainable API.
585
+ *
586
+ * @example Functional Mini API
587
+ * ```ts
588
+ * const printer = printerZodMini({})
589
+ * const code = printer.print(optionalStringNode) // "z.optional(z.string())"
590
+ * ```
591
+ */
592
+ const printerZodMini = _kubb_core.ast.definePrinter((options) => {
593
+ return {
594
+ name: "zod-mini",
595
+ options,
596
+ nodes: {
597
+ any: () => "z.any()",
598
+ unknown: () => "z.unknown()",
599
+ void: () => "z.void()",
600
+ never: () => "z.never()",
601
+ boolean: () => "z.boolean()",
602
+ null: () => "z.null()",
603
+ string(node) {
604
+ return `z.string()${lengthChecksMini(node)}`;
605
+ },
606
+ number(node) {
607
+ return `z.number()${numberChecksMini(node)}`;
608
+ },
609
+ integer(node) {
610
+ return `z.int()${numberChecksMini(node)}`;
611
+ },
612
+ bigint(node) {
613
+ return `z.bigint()${numberChecksMini(node)}`;
614
+ },
615
+ date(node) {
616
+ if (node.representation === "string") return "z.iso.date()";
617
+ return "z.date()";
618
+ },
619
+ datetime() {
620
+ return "z.string()";
621
+ },
622
+ time(node) {
623
+ if (node.representation === "string") return "z.iso.time()";
624
+ return "z.date()";
625
+ },
626
+ uuid(node) {
627
+ return `${this.options.guidType === "guid" ? "z.guid()" : "z.uuid()"}${lengthChecksMini(node)}`;
628
+ },
629
+ email(node) {
630
+ return `z.email()${lengthChecksMini(node)}`;
631
+ },
632
+ url(node) {
633
+ return `z.url()${lengthChecksMini(node)}`;
634
+ },
635
+ ipv4: () => "z.ipv4()",
636
+ ipv6: () => "z.ipv6()",
637
+ blob: () => "z.instanceof(File)",
638
+ enum(node) {
639
+ const nonNullValues = (node.namedEnumValues?.map((v) => v.value) ?? node.enumValues ?? []).filter((v) => v !== null);
640
+ if (node.namedEnumValues?.length) {
641
+ const literals = nonNullValues.map((v) => `z.literal(${formatLiteral(v)})`);
642
+ if (literals.length === 1) return literals[0];
643
+ return `z.union([${literals.join(", ")}])`;
644
+ }
645
+ return `z.enum([${nonNullValues.map(formatLiteral).join(", ")}])`;
646
+ },
647
+ ref(node) {
648
+ if (!node.name) return void 0;
649
+ const refName = node.ref ? _kubb_core.ast.extractRefName(node.ref) ?? node.name : node.name;
650
+ const resolvedName = node.ref ? this.options.resolver?.default(refName, "function") ?? refName : node.name;
651
+ if (node.ref && this.options.cyclicSchemas?.has(refName)) return `z.lazy(() => ${resolvedName})`;
652
+ return resolvedName;
653
+ },
654
+ object(node) {
655
+ return `z.object({\n ${node.properties.map((prop) => {
656
+ const { name: propName, schema } = prop;
657
+ const meta = _kubb_core.ast.syncSchemaRef(schema);
658
+ const isNullable = meta.nullable;
659
+ const isOptional = schema.optional;
660
+ const isNullish = schema.nullish;
661
+ const hasSelfRef = this.options.cyclicSchemas != null && _kubb_core.ast.containsCircularRef(schema, { circularSchemas: this.options.cyclicSchemas });
662
+ const savedCyclicSchemas = this.options.cyclicSchemas;
663
+ if (hasSelfRef) this.options.cyclicSchemas = void 0;
664
+ const baseOutput = this.transform(schema) ?? this.transform(_kubb_core.ast.createSchema({ type: "unknown" }));
665
+ if (hasSelfRef) this.options.cyclicSchemas = savedCyclicSchemas;
666
+ const value = applyMiniModifiers({
667
+ value: this.options.wrapOutput ? this.options.wrapOutput({
668
+ output: baseOutput,
669
+ schema
670
+ }) || baseOutput : baseOutput,
671
+ nullable: isNullable,
672
+ optional: isOptional,
673
+ nullish: isNullish,
674
+ defaultValue: meta.default
675
+ });
676
+ if (hasSelfRef) return `get "${propName}"() { return ${value} }`;
677
+ return `"${propName}": ${value}`;
678
+ }).join(",\n ")}\n })`;
679
+ },
680
+ array(node) {
681
+ let result = `z.array(${(node.items ?? []).map((item) => this.transform(item)).filter(Boolean).join(", ") || this.transform(_kubb_core.ast.createSchema({ type: "unknown" }))})${lengthChecksMini(node)}`;
682
+ if (node.unique) result += `.refine(items => new Set(items).size === items.length, { message: "Array entries must be unique" })`;
683
+ return result;
684
+ },
685
+ tuple(node) {
686
+ return `z.tuple([${(node.items ?? []).map((item) => this.transform(item)).filter(Boolean).join(", ")}])`;
687
+ },
688
+ union(node) {
689
+ const nodeMembers = node.members ?? [];
690
+ const members = nodeMembers.map((memberNode) => {
691
+ const member = this.transform(memberNode);
692
+ return member && node.strategy === "one" ? strictOneOfMember(member, memberNode) : member;
693
+ }).filter(Boolean);
694
+ if (members.length === 0) return "";
695
+ if (members.length === 1) return members[0];
696
+ if (node.discriminatorPropertyName && !nodeMembers.some((m) => m.type === "intersection")) return `z.discriminatedUnion(${stringify(node.discriminatorPropertyName)}, [${members.join(", ")}])`;
697
+ return `z.union([${members.join(", ")}])`;
698
+ },
699
+ intersection(node) {
700
+ const members = node.members ?? [];
701
+ if (members.length === 0) return "";
702
+ const [first, ...rest] = members;
703
+ if (!first) return "";
704
+ let base = this.transform(first);
705
+ if (!base) return "";
706
+ for (const member of rest) {
707
+ if (member.primitive === "string") {
708
+ const c = lengthChecksMini(_kubb_core.ast.narrowSchema(member, "string") ?? {});
709
+ if (c) {
710
+ base += c;
711
+ continue;
712
+ }
713
+ } else if (member.primitive === "number" || member.primitive === "integer") {
714
+ const c = numberChecksMini(_kubb_core.ast.narrowSchema(member, "number") ?? _kubb_core.ast.narrowSchema(member, "integer") ?? {});
715
+ if (c) {
716
+ base += c;
717
+ continue;
718
+ }
719
+ } else if (member.primitive === "array") {
720
+ const c = lengthChecksMini(_kubb_core.ast.narrowSchema(member, "array") ?? {});
721
+ if (c) {
722
+ base += c;
723
+ continue;
724
+ }
725
+ }
726
+ const transformed = this.transform(member);
727
+ if (transformed) base = `z.intersection(${base}, ${transformed})`;
728
+ }
729
+ return base;
730
+ },
731
+ ...options.nodes
732
+ },
733
+ print(node) {
734
+ const { keysToOmit } = this.options;
735
+ let base = this.transform(node);
736
+ if (!base) return null;
737
+ const meta = _kubb_core.ast.syncSchemaRef(node);
738
+ if (keysToOmit?.length && meta.primitive === "object" && !(meta.type === "union" && meta.discriminatorPropertyName)) {
739
+ const lazyMatch = base.match(/^z\.lazy\(\(\)\s*=>\s*(.+)\)$/);
740
+ if (lazyMatch) base = `z.lazy(() => ${lazyMatch[1]}.omit({ ${keysToOmit.map((k) => `"${k}": true`).join(", ")} }))`;
741
+ else base = `${base}.omit({ ${keysToOmit.map((k) => `"${k}": true`).join(", ")} })`;
742
+ }
743
+ return applyMiniModifiers({
744
+ value: base,
745
+ nullable: meta.nullable,
746
+ optional: meta.optional,
747
+ nullish: meta.nullish,
748
+ defaultValue: meta.default
749
+ });
750
+ }
751
+ };
752
+ });
753
+ //#endregion
754
+ //#region src/generators/zodGenerator.tsx
755
+ const zodPrinterCache = /* @__PURE__ */ new WeakMap();
756
+ const zodMiniPrinterCache = /* @__PURE__ */ new WeakMap();
757
+ const zodGenerator = (0, _kubb_core.defineGenerator)({
758
+ name: "zod",
759
+ renderer: _kubb_renderer_jsx.jsxRendererSync,
760
+ schema(node, ctx) {
761
+ const { adapter, config, resolver, root, inputNode } = ctx;
762
+ const { output, coercion, guidType, mini, wrapOutput, inferred, importPath, group, printer } = ctx.options;
763
+ const dateType = adapter.options.dateType;
764
+ if (!node.name) return;
765
+ const mode = ctx.getMode(output);
766
+ const isZodImport = ZOD_NAMESPACE_IMPORTS.has(importPath);
767
+ const imports = adapter.getImports(node, (schemaName) => ({
768
+ name: resolver.resolveSchemaName(schemaName),
769
+ path: resolver.resolveFile({
770
+ name: schemaName,
771
+ extname: ".ts"
772
+ }, {
773
+ root,
774
+ output,
775
+ group
776
+ }).path
777
+ }));
778
+ const meta = {
779
+ name: resolver.resolveSchemaName(node.name),
780
+ file: resolver.resolveFile({
781
+ name: node.name,
782
+ extname: ".ts"
783
+ }, {
784
+ root,
785
+ output,
786
+ group
787
+ })
788
+ };
789
+ const inferTypeName = inferred ? resolver.resolveSchemaTypeName(node.name) : void 0;
790
+ const cyclicSchemas = _kubb_core.ast.findCircularSchemas(inputNode.schemas);
791
+ const schemaPrinter = mini ? getCachedMiniPrinter() : getCachedStdPrinter();
792
+ function getCachedStdPrinter() {
793
+ const cached = zodPrinterCache.get(resolver);
794
+ if (cached && cached.coercion === coercion && cached.guidType === guidType && cached.dateType === dateType) return cached.printer;
795
+ const p = printerZod({
796
+ coercion,
797
+ guidType,
798
+ dateType,
799
+ wrapOutput,
800
+ resolver,
801
+ cyclicSchemas,
802
+ nodes: printer?.nodes
803
+ });
804
+ zodPrinterCache.set(resolver, {
805
+ printer: p,
806
+ coercion,
807
+ guidType,
808
+ dateType
809
+ });
810
+ return p;
811
+ }
812
+ function getCachedMiniPrinter() {
813
+ const cached = zodMiniPrinterCache.get(resolver);
814
+ if (cached && cached.guidType === guidType) return cached.printer;
815
+ const p = printerZodMini({
816
+ guidType,
817
+ wrapOutput,
818
+ resolver,
819
+ cyclicSchemas,
820
+ nodes: printer?.nodes
821
+ });
822
+ zodMiniPrinterCache.set(resolver, {
823
+ printer: p,
824
+ guidType
825
+ });
826
+ return p;
827
+ }
828
+ return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsxs)(_kubb_renderer_jsx.File, {
829
+ baseName: meta.file.baseName,
830
+ path: meta.file.path,
831
+ meta: meta.file.meta,
832
+ banner: resolver.resolveBanner(inputNode, {
833
+ output,
834
+ config
835
+ }),
836
+ footer: resolver.resolveFooter(inputNode, {
837
+ output,
838
+ config
839
+ }),
840
+ children: [
841
+ /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Import, {
842
+ name: isZodImport ? "z" : ["z"],
843
+ path: importPath,
844
+ isNameSpace: isZodImport
845
+ }),
846
+ mode === "split" && imports.map((imp) => /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Import, {
847
+ root: meta.file.path,
848
+ path: imp.path,
849
+ name: imp.name
850
+ }, [node.name, imp.path].join("-"))),
851
+ /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(Zod, {
852
+ name: meta.name,
853
+ node,
854
+ printer: schemaPrinter,
855
+ inferTypeName
856
+ })
857
+ ]
858
+ });
859
+ },
860
+ operation(node, ctx) {
861
+ const { adapter, config, resolver, root, inputNode } = ctx;
862
+ const { output, coercion, guidType, mini, wrapOutput, inferred, importPath, group, paramsCasing, printer } = ctx.options;
863
+ const dateType = adapter.options.dateType;
864
+ const mode = ctx.getMode(output);
865
+ const isZodImport = ZOD_NAMESPACE_IMPORTS.has(importPath);
866
+ const params = _kubb_core.ast.caseParams(node.parameters, paramsCasing);
867
+ const meta = { file: resolver.resolveFile({
868
+ name: node.operationId,
869
+ extname: ".ts",
870
+ tag: node.tags[0] ?? "default",
871
+ path: node.path
872
+ }, {
873
+ root,
874
+ output,
875
+ group
876
+ }) };
877
+ const cyclicSchemas = _kubb_core.ast.findCircularSchemas(inputNode.schemas);
878
+ function renderSchemaEntry({ schema, name, keysToOmit }) {
879
+ if (!schema) return null;
880
+ const inferTypeName = inferred ? resolver.resolveTypeName(name) : void 0;
881
+ const imports = adapter.getImports(schema, (schemaName) => ({
882
+ name: resolver.resolveSchemaName(schemaName),
883
+ path: resolver.resolveFile({
884
+ name: schemaName,
885
+ extname: ".ts"
886
+ }, {
887
+ root,
888
+ output,
889
+ group
890
+ }).path
891
+ }));
892
+ const cachedStd = zodPrinterCache.get(resolver);
893
+ const cachedMini = zodMiniPrinterCache.get(resolver);
894
+ const schemaPrinter = mini ? keysToOmit?.length ? printerZodMini({
895
+ guidType,
896
+ wrapOutput,
897
+ resolver,
898
+ keysToOmit,
899
+ cyclicSchemas,
900
+ nodes: printer?.nodes
901
+ }) : cachedMini?.guidType === guidType ? cachedMini.printer : printerZodMini({
902
+ guidType,
903
+ wrapOutput,
904
+ resolver,
905
+ cyclicSchemas,
906
+ nodes: printer?.nodes
907
+ }) : keysToOmit?.length ? printerZod({
908
+ coercion,
909
+ guidType,
910
+ dateType,
911
+ wrapOutput,
912
+ resolver,
913
+ keysToOmit,
914
+ cyclicSchemas,
915
+ nodes: printer?.nodes
916
+ }) : cachedStd?.coercion === coercion && cachedStd?.guidType === guidType && cachedStd?.dateType === dateType ? cachedStd.printer : printerZod({
917
+ coercion,
918
+ guidType,
919
+ dateType,
920
+ wrapOutput,
921
+ resolver,
922
+ cyclicSchemas,
923
+ nodes: printer?.nodes
924
+ });
925
+ return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsxs)(_kubb_renderer_jsx_jsx_runtime.Fragment, { children: [mode === "split" && imports.map((imp) => /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Import, {
926
+ root: meta.file.path,
927
+ path: imp.path,
928
+ name: imp.name
929
+ }, [
930
+ name,
931
+ imp.path,
932
+ imp.name
933
+ ].join("-"))), /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(Zod, {
934
+ name,
935
+ node: schema,
936
+ printer: schemaPrinter,
937
+ inferTypeName
938
+ })] });
939
+ }
940
+ const paramSchemas = params.map((param) => renderSchemaEntry({
941
+ schema: param.schema,
942
+ name: resolver.resolveParamName(node, param)
943
+ }));
944
+ const responseSchemas = node.responses.map((res) => renderSchemaEntry({
945
+ schema: res.schema,
946
+ name: resolver.resolveResponseStatusName(node, res.statusCode),
947
+ keysToOmit: res.keysToOmit
948
+ }));
949
+ const responsesWithSchema = node.responses.filter((res) => res.schema);
950
+ const responseUnionSchema = responsesWithSchema.length > 0 ? (() => {
951
+ const responseUnionName = resolver.resolveResponseName(node);
952
+ if (new Set(responsesWithSchema.flatMap((res) => res.schema ? adapter.getImports(res.schema, (schemaName) => ({
953
+ name: resolver.resolveSchemaName(schemaName),
954
+ path: ""
955
+ })).flatMap((imp) => Array.isArray(imp.name) ? imp.name : [imp.name]) : [])).has(responseUnionName)) return null;
956
+ const members = responsesWithSchema.map((res) => _kubb_core.ast.createSchema({
957
+ type: "ref",
958
+ name: resolver.resolveResponseStatusName(node, res.statusCode)
959
+ }));
960
+ return renderSchemaEntry({
961
+ schema: members.length === 1 ? members[0] : _kubb_core.ast.createSchema({
962
+ type: "union",
963
+ members
964
+ }),
965
+ name: responseUnionName
966
+ });
967
+ })() : null;
968
+ const requestSchema = node.requestBody?.content?.[0]?.schema ? renderSchemaEntry({
969
+ schema: {
970
+ ...node.requestBody.content[0].schema,
971
+ description: node.requestBody.description ?? node.requestBody.content[0].schema.description
972
+ },
973
+ name: resolver.resolveDataName(node),
974
+ keysToOmit: node.requestBody.content[0].keysToOmit
975
+ }) : null;
976
+ return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsxs)(_kubb_renderer_jsx.File, {
977
+ baseName: meta.file.baseName,
978
+ path: meta.file.path,
979
+ meta: meta.file.meta,
980
+ banner: resolver.resolveBanner(inputNode, {
981
+ output,
982
+ config
983
+ }),
984
+ footer: resolver.resolveFooter(inputNode, {
985
+ output,
986
+ config
987
+ }),
988
+ children: [
989
+ /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Import, {
990
+ name: isZodImport ? "z" : ["z"],
991
+ path: importPath,
992
+ isNameSpace: isZodImport
993
+ }),
994
+ paramSchemas,
995
+ responseSchemas,
996
+ responseUnionSchema,
997
+ requestSchema
998
+ ]
999
+ });
1000
+ },
1001
+ operations(nodes, ctx) {
1002
+ const { config, resolver, root, inputNode } = ctx;
1003
+ const { output, importPath, group, operations, paramsCasing } = ctx.options;
1004
+ if (!operations) return;
1005
+ const isZodImport = ZOD_NAMESPACE_IMPORTS.has(importPath);
1006
+ const meta = { file: resolver.resolveFile({
1007
+ name: "operations",
1008
+ extname: ".ts"
1009
+ }, {
1010
+ root,
1011
+ output,
1012
+ group
1013
+ }) };
1014
+ const transformedOperations = nodes.map((node) => {
1015
+ return {
1016
+ node,
1017
+ data: buildSchemaNames(node, {
1018
+ params: _kubb_core.ast.caseParams(node.parameters, paramsCasing),
1019
+ resolver
1020
+ })
1021
+ };
1022
+ });
1023
+ const imports = transformedOperations.flatMap(({ node, data }) => {
1024
+ const names = [
1025
+ data.request,
1026
+ ...Object.values(data.responses),
1027
+ ...Object.values(data.parameters)
1028
+ ].filter(Boolean);
1029
+ const opFile = resolver.resolveFile({
1030
+ name: node.operationId,
1031
+ extname: ".ts",
1032
+ tag: node.tags[0] ?? "default",
1033
+ path: node.path
1034
+ }, {
1035
+ root,
1036
+ output,
1037
+ group
1038
+ });
1039
+ return names.map((name) => /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Import, {
1040
+ name: [name],
1041
+ root: meta.file.path,
1042
+ path: opFile.path
1043
+ }, [name, opFile.path].join("-")));
1044
+ });
1045
+ return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsxs)(_kubb_renderer_jsx.File, {
1046
+ baseName: meta.file.baseName,
1047
+ path: meta.file.path,
1048
+ meta: meta.file.meta,
1049
+ banner: resolver.resolveBanner(inputNode, {
1050
+ output,
1051
+ config
1052
+ }),
1053
+ footer: resolver.resolveFooter(inputNode, {
1054
+ output,
1055
+ config
1056
+ }),
1057
+ children: [
1058
+ /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Import, {
1059
+ isTypeOnly: true,
1060
+ name: isZodImport ? "z" : ["z"],
1061
+ path: importPath,
1062
+ isNameSpace: isZodImport
1063
+ }),
1064
+ imports,
1065
+ /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(Operations, {
1066
+ name: "operations",
1067
+ operations: transformedOperations
1068
+ })
1069
+ ]
1070
+ });
1071
+ }
1072
+ });
1073
+ //#endregion
1074
+ //#region src/resolvers/resolverZod.ts
1075
+ /**
1076
+ * Naming convention resolver for Zod plugin.
1077
+ *
1078
+ * Provides default naming helpers using camelCase with a `Schema` suffix for schemas.
1079
+ *
1080
+ * @example
1081
+ * `resolverZod.default('list pets', 'function') // → 'listPetsSchema'`
1082
+ */
1083
+ const resolverZod = (0, _kubb_core.defineResolver)(() => {
1084
+ return {
1085
+ name: "default",
1086
+ pluginName: "plugin-zod",
1087
+ default(name, type) {
1088
+ return camelCase(name, {
1089
+ isFile: type === "file",
1090
+ suffix: type ? "schema" : void 0
1091
+ });
1092
+ },
1093
+ resolveSchemaName(name) {
1094
+ return camelCase(name, { suffix: "schema" });
1095
+ },
1096
+ resolveSchemaTypeName(name) {
1097
+ return pascalCase(name, { suffix: "schema" });
1098
+ },
1099
+ resolveTypeName(name) {
1100
+ return pascalCase(name);
1101
+ },
1102
+ resolvePathName(name, type) {
1103
+ return this.default(name, type);
1104
+ },
1105
+ resolveParamName(node, param) {
1106
+ return this.resolveSchemaName(`${node.operationId} ${param.in} ${param.name}`);
1107
+ },
1108
+ resolveResponseStatusName(node, statusCode) {
1109
+ return this.resolveSchemaName(`${node.operationId} Status ${statusCode}`);
1110
+ },
1111
+ resolveDataName(node) {
1112
+ return this.resolveSchemaName(`${node.operationId} Data`);
1113
+ },
1114
+ resolveResponsesName(node) {
1115
+ return this.resolveSchemaName(`${node.operationId} Responses`);
1116
+ },
1117
+ resolveResponseName(node) {
1118
+ return this.resolveSchemaName(`${node.operationId} Response`);
1119
+ },
1120
+ resolvePathParamsName(node, param) {
1121
+ return this.resolveParamName(node, param);
1122
+ },
1123
+ resolveQueryParamsName(node, param) {
1124
+ return this.resolveParamName(node, param);
1125
+ },
1126
+ resolveHeaderParamsName(node, param) {
1127
+ return this.resolveParamName(node, param);
1128
+ }
1129
+ };
1130
+ });
1131
+ //#endregion
65
1132
  //#region src/plugin.ts
1133
+ /**
1134
+ * Canonical plugin name for `@kubb/plugin-zod`, used in driver lookups and warnings.
1135
+ */
66
1136
  const pluginZodName = "plugin-zod";
67
- const pluginZod = (0, _kubb_core.createPlugin)((options) => {
1137
+ /**
1138
+ * Generates Zod validation schemas from an OpenAPI specification.
1139
+ * Walks schemas and operations, delegates to generators, and writes barrel files
1140
+ * based on the configured `barrelType`.
1141
+ *
1142
+ * @example Zod schema generator
1143
+ * ```ts
1144
+ * import pluginZod from '@kubb/plugin-zod'
1145
+ * export default defineConfig({
1146
+ * plugins: [pluginZod({ output: { path: 'zod' } })]
1147
+ * })
1148
+ * ```
1149
+ */
1150
+ const pluginZod = (0, _kubb_core.definePlugin)((options) => {
68
1151
  const { output = {
69
1152
  path: "zod",
70
1153
  barrelType: "named"
71
- }, group, exclude = [], include, override = [], transformers = {}, dateType = "string", unknownType = "any", emptySchemaType = unknownType, integerType = "number", typed = false, mapper = {}, operations = false, mini = false, version = mini ? "4" : (0, _kubb_core.satisfiesDependency)("zod", ">=4") ? "4" : "3", guidType = "uuid", importPath = mini ? "zod/mini" : version === "4" ? "zod/v4" : "zod", coercion = false, inferred = false, generators = [require_generators.zodGenerator, operations ? require_generators.operationsGenerator : void 0].filter(Boolean), wrapOutput = void 0, contentType } = options;
1154
+ }, group, exclude = [], include, override = [], typed = false, operations = false, mini = false, guidType = "uuid", importPath = mini ? "zod/mini" : "zod", coercion = false, inferred = false, wrapOutput = void 0, paramsCasing, printer, resolver: userResolver, transformer: userTransformer, generators: userGenerators = [] } = options;
1155
+ const groupConfig = group ? {
1156
+ ...group,
1157
+ name: (ctx) => {
1158
+ if (group.type === "path") return `${ctx.group.split("/")[1]}`;
1159
+ return `${camelCase(ctx.group)}Controller`;
1160
+ }
1161
+ } : void 0;
72
1162
  return {
73
1163
  name: pluginZodName,
74
- options: {
75
- output,
76
- transformers,
77
- include,
78
- exclude,
79
- override,
80
- typed,
81
- dateType,
82
- unknownType,
83
- emptySchemaType,
84
- integerType,
85
- mapper,
86
- importPath,
87
- coercion,
88
- operations,
89
- inferred,
90
- group,
91
- wrapOutput,
92
- version,
93
- guidType,
94
- mini,
95
- usedEnumNames: {}
96
- },
97
- pre: [_kubb_plugin_oas.pluginOasName, typed ? _kubb_plugin_ts.pluginTsName : void 0].filter(Boolean),
98
- resolvePath(baseName, pathMode, options) {
99
- const root = node_path.default.resolve(this.config.root, this.config.output.path);
100
- if ((pathMode ?? (0, _kubb_core.getMode)(node_path.default.resolve(root, output.path))) === "single")
101
- /**
102
- * when output is a file then we will always append to the same file(output file), see fileManager.addOrAppend
103
- * Other plugins then need to call addOrAppend instead of just add from the fileManager class
104
- */
105
- return node_path.default.resolve(root, output.path);
106
- if (group && (options?.group?.path || options?.group?.tag)) {
107
- const groupName = group?.name ? group.name : (ctx) => {
108
- if (group?.type === "path") return `${ctx.group.split("/")[1]}`;
109
- return `${camelCase(ctx.group)}Controller`;
110
- };
111
- return node_path.default.resolve(root, output.path, groupName({ group: group.type === "path" ? options.group.path : options.group.tag }), baseName);
112
- }
113
- return node_path.default.resolve(root, output.path, baseName);
114
- },
115
- resolveName(name, type) {
116
- let resolvedName = camelCase(name, {
117
- suffix: type ? "schema" : void 0,
118
- isFile: type === "file"
119
- });
120
- if (type === "type") resolvedName = pascalCase(resolvedName);
121
- if (type) return transformers?.name?.(resolvedName, type) || resolvedName;
122
- return resolvedName;
123
- },
124
- async install() {
125
- const root = node_path.default.resolve(this.config.root, this.config.output.path);
126
- const mode = (0, _kubb_core.getMode)(node_path.default.resolve(root, output.path));
127
- const oas = await this.getOas();
128
- if (this.plugin.options.typed && this.plugin.options.version === "3") await this.addFile({
129
- baseName: "ToZod.ts",
130
- path: node_path.default.resolve(root, ".kubb/ToZod.ts"),
131
- sources: [{
132
- name: "ToZod",
133
- value: require_templates_ToZod_source.source
134
- }],
135
- imports: [],
136
- exports: []
137
- });
138
- const schemaFiles = await new _kubb_plugin_oas.SchemaGenerator(this.plugin.options, {
139
- fabric: this.fabric,
140
- oas,
141
- driver: this.driver,
142
- events: this.events,
143
- plugin: this.plugin,
144
- contentType,
145
- include: void 0,
146
- override,
147
- mode,
148
- output: output.path
149
- }).build(...generators);
150
- await this.upsertFile(...schemaFiles);
151
- const operationFiles = await new _kubb_plugin_oas.OperationGenerator(this.plugin.options, {
152
- fabric: this.fabric,
153
- oas,
154
- driver: this.driver,
155
- events: this.events,
156
- plugin: this.plugin,
157
- contentType,
1164
+ options,
1165
+ hooks: { "kubb:plugin:setup"(ctx) {
1166
+ ctx.setOptions({
1167
+ output,
158
1168
  exclude,
159
1169
  include,
160
1170
  override,
161
- mode
162
- }).build(...generators);
163
- await this.upsertFile(...operationFiles);
164
- const barrelFiles = await (0, _kubb_core.getBarrelFiles)(this.fabric.files, {
165
- type: output.barrelType ?? "named",
166
- root,
167
- output,
168
- meta: { pluginName: this.plugin.name }
1171
+ group: groupConfig,
1172
+ typed,
1173
+ importPath,
1174
+ coercion,
1175
+ operations,
1176
+ inferred,
1177
+ guidType,
1178
+ mini,
1179
+ wrapOutput,
1180
+ paramsCasing,
1181
+ printer
169
1182
  });
170
- await this.upsertFile(...barrelFiles);
171
- }
1183
+ ctx.setResolver(userResolver ? {
1184
+ ...resolverZod,
1185
+ ...userResolver
1186
+ } : resolverZod);
1187
+ if (userTransformer) ctx.setTransformer(userTransformer);
1188
+ ctx.addGenerator(zodGenerator);
1189
+ for (const gen of userGenerators) ctx.addGenerator(gen);
1190
+ } }
172
1191
  };
173
1192
  });
174
1193
  //#endregion
1194
+ exports.default = pluginZod;
175
1195
  exports.pluginZod = pluginZod;
176
1196
  exports.pluginZodName = pluginZodName;
1197
+ exports.printerZod = printerZod;
1198
+ exports.printerZodMini = printerZodMini;
1199
+ exports.resolverZod = resolverZod;
1200
+ exports.zodGenerator = zodGenerator;
177
1201
 
178
1202
  //# sourceMappingURL=index.cjs.map